Android error saving pictures to sd card - android

I have an Android app which is crashing on some phones, and not on others. It has about 5k downloads, and so far has received about 50 crash reports. However, based on the amount of ratings/comments I get from users saying that it's force crashing, I think the percentage of affected users is actually much higher.
As the issue doesn't affect my phone, I've been unable to reproduce the error and debug it as I would like to.
The app takes a picture from the camera, overlays a bitmap on it, and saves the resulting image to the SD card.
Below is my code for the onPictureTaken PictureCallback method.
private Camera.PictureCallback mPicture = new Camera.PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
captureBtn.setVisibility(ImageButton.INVISIBLE);
File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);
if (pictureFile == null){
return;
}
BitmapFactory.Options options = new BitmapFactory.Options();
Bitmap mutableBitmap = null;
Bitmap finalBitmap = null;
byte[] byteArray = null;
try {
mutableBitmap = BitmapFactory.decodeByteArray(data, 0, data.length, options).copy(Bitmap.Config.RGB_565, true);
Matrix matrix = new Matrix();
int width = mutableBitmap.getWidth();
int height = mutableBitmap.getHeight();
int newWidth = overlayView.getDrawable().getBounds().width();
int newHeight = overlayView.getDrawable().getBounds().height();
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
matrix.postScale(scaleWidth, scaleHeight);
matrix.postRotate(90);
Bitmap resizedBitmap = Bitmap.createBitmap(mutableBitmap, 0, 0, mutableBitmap.getWidth(), mutableBitmap.getHeight(), matrix, true);
finalBitmap = resizedBitmap.copy(Bitmap.Config.RGB_565, true);
Canvas canvas = new Canvas(finalBitmap);
Bitmap overlayBitmap = null;
if (mWeaponType == wep1) {
overlayBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.wep1);
} else if (mWeaponType == wep2) {
overlayBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.wep2);
}
if (overlayBitmap != null) {
matrix = new Matrix();
matrix.postRotate(90);
Bitmap resizedOverlay = Bitmap.createBitmap(overlayBitmap, 0, 0, overlayBitmap.getWidth(), overlayBitmap.getHeight(), matrix, true);
canvas.drawBitmap(resizedOverlay, 0, 0, new Paint());
canvas.scale(50, 0);
canvas.save();
//finalBitmap is the image with the overlay on it
// rotate image to save in landscape mode
matrix = new Matrix();
matrix.postRotate(270);
finalBitmap = Bitmap.createBitmap(finalBitmap, 0, 0, finalBitmap.getWidth(), finalBitmap.getHeight(), matrix,
true);
// convert final bitmap to byte array
ByteArrayOutputStream stream = new ByteArrayOutputStream();
finalBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byteArray = stream.toByteArray();
}
}
catch(OutOfMemoryError e) {
//fail
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(byteArray);
fos.close();
// Notify system that SD card has been updated
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"+ Environment.getExternalStorageDirectory())));
Log.i(TAG, "Picture saved, intent broadcast that SD has been updated");
} catch (FileNotFoundException e) {
Log.d(TAG, "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d(TAG, "Error accessing file: " + e.getMessage());
} catch (NullPointerException e) {
}
finally {
mCamera.startPreview();
captureBtn.setVisibility(ImageButton.VISIBLE);
}
}
};
I get a NullPointerException as follows:
java.lang.NullPointerException
at java.io.FileOutputStream.write(FileOutputStream.java:256)
at com.mypackage.MyActivity.onPictureTaken(MyActivity.java:215)
which is the
fos.write(byteArray);
line.
The getOutputMediaFile method listed above is as follows:
/** Create a File for saving an image or video */
private static File getOutputMediaFile(int type){
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
// Create the storage directory if it does not exist
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
Log.d("HalfLife2 Booth", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE){
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"IMG_"+ timeStamp + ".jpg");
} else if(type == MEDIA_TYPE_VIDEO) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"VID_"+ timeStamp + ".mp4");
} else {
return null;
}
return mediaFile;
}
I think that the problem may be in here somewhere, in trying to get an output media file. I've tried updating the app to use:
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "MyApp");
instead, and one user has reported the issue to be fixed, but several have reported that it persists.
Any ideas, anyone? I'm finding this a tricky one to debug/fix when I can't reproduce or get anywhere near it.

Make sure you are scaling your pictures in their raw format. I found that the raw images are HUGE on some phone models. I recommend scaling the image if it's very large because you will run your virtual machine out of memory.
Example:
imageRef = sd_card_path+"/"+ImageName;
BitmapFactory.Options resample = new BitmapFactory.Options();
resample.inJustDecodeBounds = true;
BitmapFactory.decodeFile(imageRef, resample);
int width = resample.outWidth;
int height = resample.outHeight;
if(width*height > utility.IMAGE_SIZE_MIN){
int imageSizef = (int)(width*height/utility.IMAGE_SIZE_MIN);
String imageSize = imageSizef+"";
resample.inSampleSize = Integer.parseInt(imageSize);
resample.inJustDecodeBounds = false;
image.setImageBitmap(BitmapFactory.decodeFile(imageRef , resample));
}else{
image.setImageBitmap(BitmapFactory.decodeFile(imageRef ));
}

Given the Exception trace it would suggest that you are hitting an OutOfMemorryError and as such the byteArray is never getting populated so you are passing null to the fos.write method

Related

Bitmap Rotate And Save Image

I would like to rotate and save the rotated image and move it elsewhere within my android device.
I am able to rotate my image and set it to image view.
I can copy an UN-ROTATED image to a destination of my choice.
The only thing I am unable to do is get the saved rotated image FILE (rotated.jpg)
My code below to rotate: (this does not save rotated file to storage?)
Bitmap bmp = BitmapFactory.decodeFile(filePathLocal);
Matrix matrix = new Matrix();
matrix.postRotate(getImageOrientation(filePathLocal));
rotatedBitmap = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp.getHeight(), matrix, true);
//Set Image
ImageButton ibProfile = (ImageButton) findViewById(R.id.ibProfile);
ibProfile.setImageBitmap(rotatedBitmap);
Now the above only rotates temporarily until the activity is ended, now I would like to save this rotated image from above code and move it somehwere before uploading it to server, I already know how to copy/move files and upload so no need to post those codes - all I need is the code for SAVING ROTATED IMAGE, so that I have something like /sdcard/saved_rotated_image.jpg
Bitmap bmp = BitmapFactory.decodeFile(filePathLocal);
Matrix matrix = new Matrix();
matrix.postRotate(getImageOrientation(filePathLocal));
rotatedBitmap = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp.getHeight(), matrix, false);
//Set Image
ImageButton ibProfile = (ImageButton) findViewById(R.id.ibProfile);
ibProfile.setImageBitmap(rotatedBitmap);
Put false in the createbitmap's last argument
Refere my code:
#Override
protected Uri doInBackground(String... params) {
String filepath = params[0];
String filename = params[1];
String filetype = params[2];
Bitmap bitmap = takeScreenShot(root);
Matrix rotateMatrix = new Matrix();
rotateMatrix.postRotate(Datas.rotationvalue);
Log.e("rotationvalue", Datas.rotationvalue+"...");
Bitmap rotatedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), rotateMatrix, false);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
rotatedBitmap.compress(Bitmap.CompressFormat.PNG, 100, bytes);
try {
File f = new File(filepath);
if (!f.exists()) {
f.mkdir();
}
String folderpath = f.toString();
File file = new File(folderpath, filename + "." + filetype);
file.createNewFile();
FileOutputStream fo = new FileOutputStream(file);
fo.write(bytes.toByteArray());
fo.close();
Uri uri = Uri.fromFile(file);
Log.e("Edited img uri", uri.toString());
return uri;
} catch (Exception e) {
Log.e("Exception...occured", e.toString());
e.printStackTrace();
return null;
}
}
This code is working fine.At my own side, try at your side.
According to doc: last argument is filter boolean: true if the source
should be filtered. Only applies if the matrix contains more than just
translation.
Link for more info: Last argument more info
Save the image function is as follows:
private void saveBitmap(Bitmap bitmap, String fileName) {
File file = new File(Environment.getExternalStorageDirectory(), fileName);
FileOutputStream fileOS = null;
try {
fileOS = new FileOutputStream(file);
// quality: Hint to the compressor, 0-100. 0 meaning compress for small size, 100 meaning compress for max quality.
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fileOS);
fileOS.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fileOS != null) {
try {
fileOS.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Use the sample:
Bitmap bmp = BitmapFactory.decodeFile(filePathLocal);
Matrix matrix = new Matrix();
matrix.postRotate(getImageOrientation(filePathLocal));
rotatedBitmap = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp.getHeight(), matrix, true);
saveBitmap(rotatedBitmap, "saved_rotated_image.jpg");

Android Tesseract taking too long and returning absurd data

I'm building an android tesseract app. It was reading the data fine until I was taking photos from the default camera app. Now, I needed to implement my own custom camera, that caused it to start giving wrong result.
public class getButtonClicked implements View.OnClickListener{
public void onClick(View arg0) {
DATA_PATH = Environment.getExternalStorageDirectory().toString() + "/MyOCRApp/";
File tessdata = new File(DATA_PATH);
if (!tessdata.isDirectory()){
throw new IllegalArgumentException("Data path must contain subfolder tessdata!");
}
TessBaseAPI baseApi = new TessBaseAPI();
baseApi.setDebug(true);
baseApi.init(DATA_PATH, lang);
if (newImg == null){
baseApi.setImage(imageBitmap);
}
else{
baseApi.setImage(newImg);
}
String recognizedText = baseApi.getUTF8Text();
// 1. Instantiate an AlertDialog.Builder with its constructor
AlertDialog.Builder builder = new AlertDialog.Builder(context);
// 2. Chain together various setter methods to set the dialog characteristics
builder.setMessage("Recognized Text:\n\n" + recognizedText);
// 3. Get the AlertDialog from create()
AlertDialog dialog = builder.create();
dialog.show();
//baseApi.end();
}
}
This is the code that calls the tesseract APIs.
private Camera.PictureCallback mPicture = new Camera.PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);
if (pictureFile == null){
Log.d("Error creating file" ,"!");
return;
}
int screenWidth = getResources().getDisplayMetrics().widthPixels;
int screenHeight = getResources().getDisplayMetrics().heightPixels;
bm = BitmapFactory.decodeByteArray(data, 0, (data != null) ? data.length : 0);
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
// Notice that width and height are reversed
Bitmap scaled = Bitmap.createScaledBitmap(bm, screenHeight, screenWidth, true);
int w = scaled.getWidth();
int h = scaled.getHeight();
// Setting post rotate to 90
Matrix mtx = new Matrix();
mtx.postRotate(90);
// Rotating Bitmap
MainActivity.imageBitmap = Bitmap.createBitmap(scaled, 0, 0, w, h, mtx, true);
}else{// LANDSCAPE MODE
//No need to reverse width and height
Bitmap scaled = Bitmap.createScaledBitmap(bm, screenWidth,screenHeight , true);
MainActivity.imageBitmap = scaled;
}
Calendar c = Calendar.getInstance();
String time = Integer.toString(c.get(Calendar.DATE));
//MediaStore.Images.Media.insertImage(getContentResolver(), MainActivity.imageBitmap, time+"MyOCR", "Hello!!");
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/MyOCRApp");
if (! myDir.exists()){
if (! myDir.mkdirs()){
Log.d("MyCameraApp", "failed to create directory");
return;
}
}
String fname = "Image-" +time+ ".jpg";
File file = new File(myDir, fname);
if (file.exists())
file.delete();
try {
FileOutputStream out = new FileOutputStream(file);
MainActivity.imageBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
MediaStore.Images.Media.insertImage(getContentResolver(), file.getAbsolutePath(), file.getName(), file.getName());
} catch (Exception e) {
e.printStackTrace();
}
surfaceDestroyed(mSurfaceHolder);
}
};
This is the code in my camera class. I even debugged and checked that the picture was perfectly fine, when the tesseract APIs are called. I can't post photos, otherwise I have posted one. What should I do??
I am experimenting with tesseract on android as well. Try to rescale your image. An image taken by the camera activity maybe to big. Additionaly you probably have to pre-process the image (contrast, horizontal alignment of text, ...)

How can I rotate the photos taken with the camera?

I inserted on my App a option to take a photo and save it on a directory.
But when I check the taken photo it appears turned. The horizontal photos appears vertical, and the vertical photos appears horizontal.
how can change my code and automatically rotate the photos?
My code:
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);
}
...
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 {
Bitmap bitmap;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),
bitmapOptions);
int nh = (int) ( bitmap.getHeight() * (612.0 / bitmap.getWidth()) );
Bitmap scaled = Bitmap.createScaledBitmap(bitmap, 612, nh, true);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
scaled.compress(Bitmap.CompressFormat.JPEG, 90, stream);
byte [] byte_arr = stream.toByteArray();
String image_str = Base64.encodeBytes(byte_arr);
viewImage.setScaleType(ScaleType.CENTER);
viewImage.setImageBitmap(scaled);
task = new getinfo();
task.execute(image_str);
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();
}
This piece helped me to do the same task
private Bitmap rotateImage(String pathToImage) {
// 1. figure out the amount of degrees
int rotation = getImageRotation();
// 2. rotate matrix by postconcatination
Matrix matrix = new Matrix();
matrix.postRotate(rotation);
// 3. create Bitmap from rotated matrix
Bitmap sourceBitmap = BitmapFactory.decodeFile(pathToImage);
return Bitmap.createBitmap(sourceBitmap, 0, 0, sourceBitmap.getWidth(), sourceBitmap.getHeight(), matrix, true);
}
Also check this,this and this for more details.

How to save image bitmap after rotation? [duplicate]

This question already has answers here:
Android saving file to external storage
(13 answers)
Closed 2 years ago.
I develop app that save images to sd Card and all the pictures are upside i want to rotate them and save them in the rotate position i choose .
i know how to rotate on my code but the image is not saved permanently.
here is my code :
//Rotate the picture
public static Bitmap rotate(Bitmap source, float angle) {
Matrix matrix = new Matrix();
matrix.postRotate(angle);
return Bitmap.createBitmap(source, 0, 0, source.getWidth(),source.getHeight(), matrix, false);
}
//Resize image
public void resizeImage(String path , int Wdist,int Hdist){
try
{
int inWidth = 0;
int inHeight = 0;
InputStream in = new FileInputStream(path);
// decode image size (decode metadata only, not the whole image)
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(in, null, options);
in.close();
in = null;
// save width and height
inWidth = options.outWidth;
inHeight = options.outHeight;
// decode full image pre-resized
in = new FileInputStream(path);
options = new BitmapFactory.Options();
// calc rought re-size (this is no exact resize)
options.inSampleSize = Math.max(inWidth/Wdist, inHeight/Hdist);
// decode full image
Bitmap roughBitmap = BitmapFactory.decodeStream(in, null, options);
// calc exact destination size
Matrix m = new Matrix();
RectF inRect = new RectF(0, 0, roughBitmap.getWidth(), roughBitmap.getHeight());
RectF outRect = new RectF(0, 0, Wdist, Hdist);
m.setRectToRect(inRect, outRect, Matrix.ScaleToFit.CENTER);
float[] values = new float[9];
m.getValues(values);
// resize bitmap
Bitmap resizedBitmap = Bitmap.createScaledBitmap(roughBitmap, (int) (roughBitmap.getWidth() * values[0]), (int) (roughBitmap.getHeight() * values[4]), true);
// save image
try
{
FileOutputStream out = new FileOutputStream(path);
resizedBitmap.compress(Bitmap.CompressFormat.JPEG, 80, out);
}
catch (Exception e)
{
Log.e("Image", e.getMessage(), e);
}
}
catch (IOException e)
{
Log.e("Image", e.getMessage(), e);
}
}
thanks for the helpers :)
You'll need to save the Bitmap back.
try {
File dir = new File("path/to/directory");
if(!dir.exists())
dir.mkdirs();
File file = new File(dir, "original_img_name.png");
FileOutputStream out;
out = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
} catch (Exception e) {
e.printStackTrace();
} finally {
try{
out.close();
} catch(Throwable ignore) {}
}
Edit 1 :
Replace
bmp.compress(Bitmap.CompressFormat.PNG, 90, out); with
resizedBitmap.compress(Bitmap.CompressFormat.JPEG, 80, out); and set correct values for the directory path and the image name. If you want to replace the previous images, use the original path and image name.
Also, make sure you include the following permission.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
You can also try this one
return Bitmap.createBitmap(source, 0, 0, source.getWidth(),source.getHeight(), matrix, true);
Go through this link
how to rotate a bitmap 90 degrees
The following code can help you compress and resize the bitmap.
Note:
Create a String type variable with name of photoPath and store the photo url in it.
public void compressImage(){
Log.i("compressPhoto", "Compress and resize photo started.");
// Getting Image
InputStream in = null;
try {
in = new FileInputStream(photoPath);
} catch (FileNotFoundException e) {
Log.e("TAG","originalFilePath is not valid", e);
}
BitmapFactory.Options options = new BitmapFactory.Options();
Bitmap bitmap = BitmapFactory.decodeStream(in, null, options);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap = bitmap.createScaledBitmap(bitmap,(int)(bitmap.getWidth()*0.2), (int)(bitmap.getHeight()*0.2), true);
bitmap.compress(Bitmap.CompressFormat.JPEG, 50, stream);
byte[] byteArray = stream.toByteArray();
// Storing Back
FileOutputStream outStream = null;
try {
outStream = new FileOutputStream(photoPath);
outStream.write(byteArray);
outStream.close();
} catch (Exception e) {
Log.e("TAG","could not save", e);
}
}

Camera Preview Out of Memory Error

Objective of the program: the user is able to place one picture on the top of camera preview and move it freely (image is big 1920x1080 pixels) and can store this two layers (picture and camera preview) pressing the photo button. So far he is only able to save one picture of this kind because when he takes the second one the out of memory error problem appears.
Solution It seems that the problem can be solved if you use recycle bitmap function when you dont need to use bitmaps anymore. Or you can resize them (didn't want to)... Are these good ideas?
Code:
private PictureCallback mPicture = new PictureCallback()
{
#Override
public void onPictureTaken(byte[] data, Camera camera)
{
File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);
mPreview.setDrawingCacheEnabled(true);
mPreview.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_AUTO);
Bitmap bitmap = mPreview.getDrawingCache();
bmp = BitmapFactory.decodeByteArray(data, 0, data.length);
combination = overlay(bmp, bitmap);
if(pictureFile == null)
{
return;
}
try
{
FileOutputStream fos = new FileOutputStream(pictureFile);
combination.compress(CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "MyCameraApp");
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://"+ mediaStorageDir)));
}
catch(FileNotFoundException e)
{
Log.d(TAG, "File not found: "+e.getMessage());
}
catch(IOException e)
{
Log.d(TAG, "Error accessing file: "+e.getMessage());
}
}
};
public static Bitmap overlay(Bitmap bmp1, Bitmap bmp2)
{
Bitmap bmOverlay = Bitmap.createBitmap(bmp1.getWidth(), bmp1.getHeight(),bmp1.getConfig());
Canvas canvas = new Canvas(bmOverlay);
canvas.drawBitmap(bmp1, new Matrix(), null);
canvas.drawBitmap(bmp2, null, new Rect(0,0,bmp1.getWidth(), bmp1.getHeight()), null);
return bmOverlay;
}
private static File getOutputMediaFile(int type)
{
File mediaFile = null;
if(isSdPresent() == false)
{
Log.d(TAG, "There is no Sd card. Cannot use the camera");
}
else
{
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "World Cup Camera");
if(!mediaStorageDir.exists())
{
if(!mediaStorageDir.mkdirs())
{
Log.d("WorldCupApp", "failed to create directory");
return null;
}
}
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
if (type == MEDIA_TYPE_IMAGE)
{
mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_"+ timeStamp + ".jpg");
}
else
{
return null;
}
}
return mediaFile;
}
I heard about this code should I use?
private Bitmap decodeFile(File f)
{
try
{
//Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f),null,o);
//The new size we want to scale to
final int REQUIRED_SIZE=70;
//Find the correct scale value. It should be the power of 2.
int scale=1;
while(o.outWidth/scale/2>=REQUIRED_SIZE && o.outHeight/scale/2>=REQUIRED_SIZE)
scale*=2;
//Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize=scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
}
catch (FileNotFoundException e) {}
return null;
}
You can use android:largeHeap="true" inside the application tag on AndroidManifest when you're having outofmemory errors.

Categories

Resources