I captured an image of 2592x1936 from mobile's camera, converted it into bitmap. I displayed it my imageview asmyImageVew.setImageBitmap(myBitmap);
after displaying this bitmap i perform some manipulation over this image(inside the imageview), now i m saving this using
Bitmap bitmap;
// frmCaptureThis is the root framelayout (this contains my imageview)
View v1 = frmCaptureThis;
v1.setDrawingCacheEnabled(true);
bitmap = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);
saveImgToSDcard(bitmap);
this is saving my image to SD card but not with the 2592x1936 resolutions, its saving my image with size equal to the imageView size (i.e 400X620). i want to save the image with original resolution i.e 2592x1936
EDIT
here is my code for taking image via intent
// ////////// Capture Button Handler//////////////////
btnCapture.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, "New Picture");
values.put(MediaStore.Images.Media.DESCRIPTION,
"From your Camera");
imageUri = getActivity().getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_SCREEN_ORIENTATION,
ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, REQUEST_OPEN_CAMERA);
}
});
and Here is my on Activity Result method
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
String imageurl = null;
if (requestCode == REQUEST_OPEN_CAMERA
&& resultCode == Activity.RESULT_OK) {
captureFlage = true;
relTapToCapture.setEnabled(false);
relHeader.setVisibility(View.INVISIBLE);
frmCaptureThis.setVisibility(View.VISIBLE);
btnCapture.setVisibility(View.VISIBLE);
btnSave.setVisibility(View.VISIBLE);
txtTapToCapture.setVisibility(View.INVISIBLE);
try {
thumbnail = MediaStore.Images.Media.getBitmap(getActivity()
.getContentResolver(), imageUri);
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
imageurl = getRealPathFromURI(imageUri);
if (thumbnail.getWidth() > thumbnail.getHeight()) {
// Log.i("Orientation", "LandScape");
// thumbnail = rotateImage_90(thumbnail);
imgCaptured.setImageBitmap(thumbnail);
} else {
// Log.i("Orientation", "Portrait");
imgCaptured.setImageBitmap(thumbnail);
}
File file = new File(imageurl);
boolean deleted = file.delete();
}
super.onActivityResult(requestCode, resultCode, data);
}
and here is my method for saving the image in SD card
public void saveImgToSDcard(Bitmap bitmap) {
Calendar cal = Calendar.getInstance();
System.out.println("Current milliseconds since 13 Oct, 2008 are :"
+ cal.getTimeInMillis());
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
File f = new File(Environment.getExternalStorageDirectory()
+ File.separator + "brandYourImage" + cal.getTimeInMillis()
+ ".jpg");
try {
f.createNewFile();
} catch (IOException e) {
}
// write the bytes in file
FileOutputStream fo = null;
try {
fo = new FileOutputStream(f);
} catch (FileNotFoundException e) {
}
try {
fo.write(bytes.toByteArray());
} catch (IOException e) {
}
// remember close de FileOutput
try {
fo.close();
Toast.makeText(getActivity(), "Saved Successfully",
Toast.LENGTH_SHORT).show();
} catch (IOException e) {
}
}
Related
I have a problem when I'm trying to load a picture that saved on the phone.
I have a "Helper class"
public class FileHelper {
public static String saveBitmapToFile(Bitmap bitmap, Context context, String fileName) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
// write the compressed bitmap to the outputStream(bytes)
bitmap.compress(Bitmap.CompressFormat.PNG, 100, bytes);
FileOutputStream fo = null;
try {
fo = context.openFileOutput(fileName, Context.MODE_PRIVATE);
} catch (FileNotFoundException e) {
Toast.makeText(context, "בעיה ,", Toast.LENGTH_SHORT).show();
}
try {
fo.write(bytes.toByteArray());
fo.close();// close file output
} catch (IOException e) {
e.printStackTrace();
}
return fileName;
}
}
Here's where I'm trying to upload the photo:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile2);
iv = (ImageView) findViewById(R.id.ivPic);
btnTakePic = (Button) findViewById(R.id.btnpic);
btnPickPicture = (Button) findViewById(R.id.btnpicpic);
try {
bitmap = BitmapFactory.decodeStream(this.openFileInput(PIC_FILE_NAME));
} catch (FileNotFoundException e) {
bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.cam);
}
iv.setImageBitmap(bitmap);
btnTakePic.setOnClickListener(this);
btnPickPicture.setOnClickListener(this);
}
public void onClick(View v) {
Intent intent = null;
if (v == btnTakePic) {
intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, TAKE_PICTURE);
} else if (v == btnPickPicture) {
Intent pickPickIntent = new Intent(Intent.ACTION_PICK);
File picDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
String picDirPath = picDir.getPath();
Uri uData = Uri.parse(picDirPath);
pickPickIntent.setDataAndType(uData, "image/*");
startActivityForResult(pickPickIntent, PICK_PICTURE);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == TAKE_PICTURE && resultCode == RESULT_OK)
{
bitmap = (Bitmap) data.getExtras().get("data");
iv.setImageBitmap(bitmap);
FileHelper.saveBitmapToFile(bitmap,getApplicationContext(),PIC_FILE_NAME);
Bitmap bitmapx = iv.getDrawingCache();
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra("BitmapImage", bitmapx);
} else if (requestCode == PICK_PICTURE) {
if (resultCode == RESULT_OK) {
Uri URI = data.getData();
String[] FILE = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(URI,
FILE, null, null, null);
cursor.moveToFirst();
options = new BitmapFactory.Options();
int columnIndex = cursor.getColumnIndex(FILE[0]);
String ImageDecode = cursor.getString(columnIndex);
cursor.close();
options.inSampleSize = 5;
Bitmap bmp = BitmapFactory.decodeFile(ImageDecode, options);
iv.setImageBitmap(bmp);
FileHelper.saveBitmapToFile(bmp,getApplicationContext(),PIC_FILE_NAME);
Bitmap bitmapx = iv.getDrawingCache();
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra("BitmapImage", bitmapx);
}
}
}
and Here is where I am trying to load the saved pic:
private void updateHeader()
{
ImageView ivHeader = (ImageView) mNavigationView.getHeaderView(0).findViewById(R.id.ivHeader);
try{
bitmap= BitmapFactory.decodeStream(this.openFileInput(PIC_FILE_NAME));
ivHeader.setImageBitmap(bitmap);
}
catch (FileNotFoundException e){
Toast.makeText(getApplicationContext(),"error occured",Toast.LENGTH_LONG);
}
}
I have to say that the Toast message is not shown and There are no errors. App not crashing but the pic stays with no change.
Make sure you have external read storage permission. Here is how to request permission.
PS: Also make sure you have added that permission to AndroidManifest.xml
How can I add a button in my android app that posts the picture which is in image view only to face book page?
this button here shares the image to all media which is not the requirement.
here init is the method which is performing the task.
Here is what i was trying:
`private void init(){
File dir = new File("/sdcard/Testing/");
try {
if (dir.mkdir()) {
System.out.println("Directoryted");
} else {
System.out.println("Directoryot created");
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_click:
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent,CAMERA_REQUEST);
break;
case R.id.btn_share:
Bitmap bitmap1 = loadBitmapFromView(relativeLayout, relativeLayout.getWidth(), relativeLayout.getHeight());
saveBitmap(bitmap1);
String str_screenshot = "/sdcard/Testing/" + "testing" + ".jpg";
fn_share(str_screenshot);
break;
}
}
public void saveBitmap(Bitmap bitmap) {
File imagePath = new File("/sdcard/Testing/" + "testing" + ".jpg");
FileOutputStream fos;
try {
fos = new FileOutputStream(imagePath);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.flush();
fos.close();
Log.e("ImageSave", "Saveimage");
} catch (FileNotFoundException e) {
Log.e("GREC", e.getMessage(), e);
} catch (IOException e) {
Log.e("GREC", e.getMessage(), e);
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
image.setImageBitmap(photo);
}
}
public static Bitmap loadBitmapFromView(View v, int width, int height) {
Bitmap b = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
v.draw(c);
return b;
}
public void fn_share(String path) {
File file = new File("/mnt/" + path);
Bitmap bmp = BitmapFactory.decodeFile(file.getAbsolutePath());
Uri uri = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(intent, "Share Image"));
}`
You can use facebook share sdk https://developers.facebook.com/docs/sharing/android
I have a problem. I am making an app with backend firebase and i want to save the image in firebase. Is there any way to store the bitmap images in Firebase. I didn't get the right tutorial.. Please help.
here is code where I get the images and want to save that images in Firebase
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
File f = new File(Environment.getExternalStorageDirectory().toString());
for (File temp : f.listFiles()) {
if (temp.getName().equals("temp.jpg")) {
f = temp;
break;
}
}
try {
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),
bitmapOptions);
mImageCapture.setImageBitmap(bitmap);
mTextImage.setVisibility(View.GONE);
String path = android.os.Environment
.getExternalStorageDirectory()
+ File.separator
+ "Phoenix" + File.separator + "default";
f.delete();
OutputStream outFile = null;
File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");
try {
outFile = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
outFile.flush();
outFile.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
} else if (requestCode == 2) {
Uri selectedImage = data.getData();
String[] filePath = { MediaStore.Images.Media.DATA };
Cursor c = getContentResolver().query(selectedImage,filePath, null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
String picturePath = c.getString(columnIndex);
c.close();
Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
mImageCapture.setImageBitmap(thumbnail);
mTextImage.setVisibility(View.GONE);
}
}
}
And this is the code where I save the name , phone no and location in Firebase
if(isOnline()){
User myData = new User();
myData.setUsername(name);
myData.setPhoneno(phone);
myData.setLocation(location);
ref.child("DataBase").push().setValue(myData);
Toast.makeText(BasicInformation.this, "Data saved", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(BasicInformation.this, HomePage.class);
startActivity(intent);
finish();
}else{
openDialog();
}
using custom camera how can we show the preview of the fullsize image after the image is being clicked from camera clicked and in preview if we can show whether to accept the image or discard the image before saving it to SD card.(Hint: As used in watsapp)
You will get image in byte[], you can convert this byte[] into bitmap and can show it in ImageView
Bitmap bitmap = BitmapFactory.decodeByteArray(yourbytearray, 0, yourbytearray.length);
The complete code according to your requirement is given below. Just follow this.Here uImage is Bitmap and imageView is the imageview where your image will be displayed.
private void selectImage() {
final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(AddownRecipeFromHome.this);
builder.setTitle("Add Photo!");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Take Photo"))
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(intent, 1);
}
else if (options[item].equals("Choose from Gallery"))
{
Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 2);
}
else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
private Uri getTempUri() {
return Uri.fromFile(getTempFile());
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
File f = new File(Environment.getExternalStorageDirectory().toString());
for (File temp : f.listFiles()) {
if (temp.getName().equals("temp.jpg")) {
f = temp;
break;
}
}
try {
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
uImage = BitmapFactory.decodeFile(f.getAbsolutePath(),
bitmapOptions);
imageView.setImageBitmap(uImage);
String path = android.os.Environment
.getExternalStorageDirectory()
+ File.separator
+ "Phoenix" + File.separator + "default";
f.delete();
OutputStream outFile = null;
File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");
try {
outFile = new FileOutputStream(file);
uImage.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
outFile.flush();
outFile.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
} else if (requestCode == 2) {
Uri selectedImage = data.getData();
String[] filePath = { MediaStore.Images.Media.DATA };
Cursor c = getContentResolver().query(selectedImage,filePath, null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
String picturePath = c.getString(columnIndex);
c.close();
uImage = (BitmapFactory.decodeFile(picturePath));
Log.e("path of imag", ""+picturePath);
imageView.setImageBitmap(uImage);
}
else if (requestCode == 3) {
try {
Log.e("testing", "return data is " + data.getData());
String filePath = Environment.getExternalStorageDirectory()
+ "/" + TEMP_PHOTO_FILE;
System.out.println("path " + filePath);
uImage = BitmapFactory.decodeFile(filePath);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
uImage.compress(Bitmap.CompressFormat.PNG, 100, bao);
ba = bao.toByteArray();
imageView.setImageBitmap(uImage);
} catch (Exception e) {
e.printStackTrace();
}
}
}
private File getTempFile() {
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
File file = new File(Environment.getExternalStorageDirectory(),
TEMP_PHOTO_FILE);
try {
file.createNewFile();
} catch (IOException e) {
}
return file;
} else {
return null;
}
}
I have task to capture image from camera and send that image to crop Intent. following is the code i have written
for camera capture
Intent captureIntent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(captureIntent, CAMERA_CAPTURE);
In on Activity result
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == CAMERA_CAPTURE) {
// get the Uri for the captured image
picUri = data.getData(); // picUri is global string variable
performCrop();
}
}
}
public void performCrop() {
try {
Intent cropIntent = new Intent("com.android.camera.action.CROP");
cropIntent.setDataAndType(picUri, "image/*");
cropIntent.putExtra("crop", "true");
cropIntent.putExtra("aspectX", 3);
cropIntent.putExtra("aspectY", 2);
cropIntent.putExtra("outputX", 256);
cropIntent.putExtra("outputY", 256);
cropIntent.putExtra("return-data", true);
startActivityForResult(cropIntent, CROP_PIC);
} catch (ActivityNotFoundException anfe) {
String errorMessage = "Your device doesn't support the crop action";
Toast toast = Toast.makeText(getApplicationContext(), errorMessage,
Toast.LENGTH_SHORT);
toast.show();
}
}
I am getting different behaviours on different devices
In some devices i am getting error "couldn't find item".
In some devices after capturing image activity stuck and doesn't go ahead
I have also tried this
Please tell me the Right way to do this
You can by calling the intent like below:
int REQUEST_IMAGE_CAPTURE = 1;
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
((Activity) context).startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
And in your activity inside OnActivityResult you get the path like this:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_IMAGE_CAPTURE) {
File f = new File(Environment.getExternalStorageDirectory().toString());
for (File temp : f.listFiles()) {
if (temp.getName().equals("temp.jpg")) {
f = temp;
break;
}
}
try {
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
Bitmap bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),
bitmapOptions);
Matrix matrix = new Matrix();
matrix.postRotate(-90);
Bitmap rotatedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
rotatedBitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
byte[] attachmentBytes = byteArrayOutputStream.toByteArray();
String attachmentData = Base64.encodeToString(attachmentBytes, Base64.DEFAULT);
String path = android.os.Environment
.getExternalStorageDirectory()
+ File.separator
+ "CTSTemp" + File.separator + "default";
f.delete();
ESLogging.debug("Bytes size = " + attachmentBytes.length);
ESLogging.debug("FilePath = " + path);
OutputStream outFile = null;
File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");
try {
outFile = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
outFile.flush();
outFile.close();
} catch (FileNotFoundException e) {
ESLogging.error("FileNotFoundException while uploading new attachment in class HomeActivity", e);
e.printStackTrace();
} catch (IOException e) {
ESLogging.error("IOException while uploading new attachment in class HomeActivity", e);
e.printStackTrace();
} catch (Exception e) {
ESLogging.error("Exception while uploading new attachment in class HomeActivity", e);
e.printStackTrace();
}
} catch (Exception e) {
ESLogging.error("Exception while uploading new attachment in class HomeActivity", e);
e.printStackTrace();
}
}
}
}
//Declare this in class
private static int RESULT_LOAD_IMAGE = 1;
String picturePath="";
// write in button click event
Intent i = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
//copy this code in after onCreate()
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK
&& null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
picturePath = cursor.getString(columnIndex);
cursor.close();
ImageView imageView = (ImageView) findViewById(R.id.img); //place imageview in your xml file
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}
write the following permission in manifest file
1.read external storage
2.write external storage
try this tutorial http://www.androidhive.info/2013/09/android-working-with-camera-api/ this will help you