I want to capture image and save it to storage. For storing am using below code
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(this.requestCode == requestCode && resultCode == RESULT_OK){
File root = new File(Environment.getExternalStorageDirectory(), "Feedback");
if (!root.exists()) {
root.mkdirs();
}
File file = new File(root, Constants.PROFILE_IMAGE_NAME+".jpeg");
checkFlowIdisPresent(file);
Bitmap photo = (Bitmap)data.getExtras().get("data");
photo = ThumbnailUtils.extractThumbnail(photo, 300, 300);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
try {
FileOutputStream fo = new FileOutputStream(file);
fo.write(bytes.toByteArray());
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
displayPic();
}
}
Now the problem is image quality is lost. So how to save an image without losing its quality.
if am using photoPickerIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri); to save image it doesn't losing its quality but the problem is i wanted to resize the image 300*300.
Please help me out.
User same code for capturing the photo. like -
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, "New Picture");
values.put(MediaStore.Images.Media.DESCRIPTION, "From your Camera");
selectedImageUri = getActivity().getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
intent.putExtra(MediaStore.EXTRA_OUTPUT, selectedImageUri);
startActivityForResult(intent, REQUEST_CAMERA);
// - selectedImageUri is global variable
now onActivityResult
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImageUri );
after getting the result just resize your image using this method
public static bitmap resizeBitmap(Bitmap bitmap){
int width = 300; // - Dimension in pixels
int height= 300; // - Dimension in pixels
return Bitmap.createScaledBitmap(bitmap, width, height, false);
}
If you don't want any compression,then use direct bitmap what you are fetching from gallery for camera.Thanks
if(this.requestCode == requestCode && resultCode == RESULT_OK){
File root = new File(Environment.getExternalStorageDirectory(), "Feedback");
if (!root.exists()) {
root.mkdirs();
}
File file = new File(root, Constants.PROFILE_IMAGE_NAME+".jpeg");
checkFlowIdisPresent(file);
Bitmap photo = (Bitmap)data.getExtras().get("data");
// use this bitmap as it is
}
Related
I have 3 images taken from camera and I want to set to 3 ImageView. But it throws OutOfMemory because the image has large size. I've read that bitmap factory can compress the size without reducing the quality. The problem is I don't know how to do that.
This is my onClick Button:
openCameraButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
file = new File(Environment.getExternalStorageDirectory(),
"imagename.jpg");
outPutfileUri = Uri.fromFile(file);
intent.putExtra(MediaStore.EXTRA_OUTPUT, outPutfileUri);
startActivityForResult(intent,0);
dialog.cancel();
}
});
And this is my onActivityResult:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//result from camera
try{
if (requestCode==0 && resultCode==RESULT_OK){
//bitmap = (Bitmap)data.getExtras().get("data");
bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), outPutfileUri);
drawable = new BitmapDrawable(getResources(), bitmap);
imageSelfie.setImageDrawable(drawable);
}
} catch (Exception ignored){}}
Anyone can help me?
Use like this :
File file = new File(Environment.getExternalStorageDirectory(),"imagename.jpg");
fileDeleted = !file.exists() || file.delete();
if (fileDeleted) {
FileOutputStream out = new FileOutputStream(file);
if (imageToSave != null) {
imageToSave.compress(Bitmap.CompressFormat.JPEG, 65, out);
}}
out.flush();
out.close();
Instead of using the media store which tries to give you a full bitmap you better open an inputstream and load a resized bitmap from it.
InputStream is = getContentResolver().openInputStream(outPutfileUri);
Then use BitmapFactory.decodeStream() with an options parameter where you scale down the image several times.
I want to take image from camera and store it and view it from internal storage.
I use this code to take image from camera.
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, TAKE_PIC);
I tried the following to save the bitmap in internal storage.
public String saveToInternalSorage(Bitmap bitmapImage, String fileName){
File file = new File(createBasePath(), fileName + ".png");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
return file.getName();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == TAKE_PIC && resultCode == RESULT_OK) {
Intent i=new Intent(Intent.ACTION_VIEW);
i.setDataAndType(Uri.fromFile(output), "image/png");
startActivity(i);
}
}
My path is /data/user/0/com.dev/app/1454351400000/33352/capture_Image1.png
But here I am facing one issue. The bit map size is very small. I want exact image what I taken from camera.
Then I found one solution. Set the path before intent. So I tried like this.
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
output = new File(createBasePath(), "capture_Image1" + ".png");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(output));
startActivityForResult(intent, TAKE_PIC);
When I use this code the image is not showing. on onActivityResult the resultCode showing -1.
If I use the following code
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File dir= Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
output=new File(dir, "CameraContentDemo.png");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(output));
startActivityForResult(intent, TAKE_PIC);
This code is working fine. After taking the image it showing image.
So please let me know store and retrieve the image from internal db with original quality.
Below is code to save the image to internal directory.
private String saveToInternalStorage(Bitmap bitmapImage){
ContextWrapper cw = new ContextWrapper(getApplicationContext());
// path to imageDir
File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
// Now Create imageDir
File mypath=new File(directory,"abc.jpg");
FileOutputStream foss = null;
try {
foss = new FileOutputStream(mypath);
// Using compress method on the BitMap object to write image to the OutputStream
bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, foss);
} catch (Exception e) {
e.printStackTrace();
} finally {
foss.close();
}
return directory.getAbsolutePath();
}
Use below code for Reading a file from internal storage
private void loadImageFromStorage(String path)
{
try {
File f=new File(path, "abc.jpg");
Bitmap b = BitmapFactory.decodeStream(new FileInputStream(f));
ImageView img=(ImageView)findViewById(R.id.imgPicker);
img.setImageBitmap(b);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
void openMultiSelectGallery() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri =getOutputMediaFile();
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
/* start activity for result pass intent as argument and request code */
startActivityForResult(intent, CAMERA_REQUEEST_CODE);
}
/**
* This method set the path for the captured image from camera for updating
* the profile pic
*/
private Uri getOutputMediaFile() {
File mediaStorageDir = new File(
Environment.getExternalStorageDirectory(), "."
+ Constants.CONTAINER);
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
mediaStorageDir.mkdirs();
}
File mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + System.currentTimeMillis() + ".png");
Uri uri = null;
if (mediaFile != null) {
uri = Uri.fromFile(mediaFile);
}
return uri;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK
&& requestCode == CAMERA_REQUEEST_CODE) {
String path =fileUri.getPath();
//decode the path to bitmap here
}
}
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
I have gallery intent that copy imege to folder, and the all that images shown in the ListView. I have an OutOfMemory Exception with bitmap decoding in my compress method - what is the simpliest way to fix it? I have recycle() option, but it's not helped.
here is my onActivityResult and compress:
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
//Toast.makeText(this, selectedImagePath, Toast.LENGTH_SHORT).show();
File sdcard = Environment.getExternalStorageDirectory();
String path = "MANUAL/workflow/img" + actions.id() + ".png";
String pathCom = "/MANUAL/workflow/img" + actions.id() + ".png";
File from = new File(selectedImagePath);
File to = new File(sdcard, path);
try {
copy(from, to);
compress(pathCom);
} catch (IOException io){}
//from.renameTo(to);
}
}
}
public void compress(String comp) {
try {
String path = Environment.getExternalStorageDirectory() + comp;
BitmapFactory.Options buffer = new BitmapFactory.Options();
buffer.inSampleSize = 1;
Bitmap bmp = BitmapFactory.decodeFile(path, buffer);
if (bmp.getWidth() > width || bmp.getHeight() > height){
Bitmap resized = Bitmap.createScaledBitmap(bmp,(int)(bmp.getWidth()*0.2), (int)(bmp.getHeight()*0.2), true);
bmp.recycle();
FileOutputStream out = new FileOutputStream(path);
resized.compress(Bitmap.CompressFormat.PNG, 70, out);
resized.recycle();
out.flush();
out.close();
}
} catch (Exception e) {
e.printStackTrace();
Log.e("saveBitmap", e.getMessage());
}
}
herŅ is my intent:
switch (item.getItemId()) {
case R.id.gallery:
// in onCreate or any event where your want the user to
// select a file
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURE);
Your inSampleSize is set to 1 which means its basically not being used.. 1= no downsampling 2 would be 1/2, 4 a 1/4.
also look into this http://developer.android.com/training/displaying-bitmaps/load-bitmap.html
hope that helps.
also if the purpose of this is to just simply create a scaled image file, perhaps that task should be handled on it's own thread using an AsyncTask for that image resizing
I am new to this site and android. how to save the camera's picture into specific folder and save the picture's name into sqlite databse also.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.camera);
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
File photo = new File(Environment.getExternalStorageDirectory(), "Pic.jpg");
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photo));
imageUri = Uri.fromFile(photo);
startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
onActivityResult(1337, 0, cameraIntent);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == CAMERA_PIC_REQUEST) {
}
I opened camera activity. How to get the picture name & save it to particular location?
please help me on this.
thank you in advance.
I'm calling camera
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
and saving to sd card like this
final ImageView img = new ImageView(this);
img.setLayoutParams(new LayoutParams(100, 100));
image2 = (Bitmap) data.getExtras().get("data");
img.setImageBitmap(image2);
String incident_ID = IncidentFormActivity.incident_id;
//l2.addView(img);
imagepath="/sdcard/RDMS/"+incident_ID+ x + ".png";
File file = new File(imagepath);
try {
bm = Bitmap.createScaledBitmap( image2,400, 300, true);
file.createNewFile();
FileOutputStream ostream = new FileOutputStream(file);
bm.compress(CompressFormat.PNG, 90, ostream);
ostream.close();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),"yourfirst error message is "
+ e.toString(), 1000).show();
}
You may need to change the line
if (resultCode == CAMERA_PIC_REQUEST) {
to
if (requestCode == CAMERA_PIC_REQUEST) {
You are already saving the picture. You provided the location in MediaStore.EXTRA_OUTPUT.
Link
Doing a DB you will have to have a look at this link is a little bit to much to explain