java.lang.OutOfMemoryError in android while saving

2019-04-01 16:47发布

问题:

I have an app in which I need to save my images into sdcard after taking them from camera.

Here is the code:

camera.takePicture(myShutterCallback, myPictureCallback_RAW,
                        myPictureCallback_JPG);

PictureCallback myPictureCallback_JPG = new PictureCallback() {

        @Override
        public void onPictureTaken(byte[] arg0, Camera arg1) {

            Bitmap bitmapPicture = BitmapFactory.decodeByteArray(arg0, 0,
                    arg0.length);

            FileOutputStream outStream = null;
            try {
                outStream = new FileOutputStream(UploadedFilename);
            } catch (FileNotFoundException e2) {
                // TODO Auto-generated catch block
                e2.printStackTrace();
            }

            final Bitmap result = Bitmap.createScaledBitmap(bitmapPicture, 640,
                    480, false);

The code bombs on this line:

Bitmap bitmapPicture = BitmapFactory.decodeByteArray(arg0, 0, arg0.length);

It says its :

Exception class java.lang.OutOfMemoryError Source method BitmapFactory.nativeDecodeByteArray().

Please Help

回答1:

If you just want to store the picture to the SD card, there's no need to create a Bitmap. Let's say you want to get an image which is >= 640px wide:

final int DESIRED_WIDTH = 640;

// Set inJustDecodeBounds to get the current size of the image; does not
// return a Bitmap
final BitmapFactory.Options sizeOptions = new BitmapFactory.Options();
sizeOptions.inJustDecodeBounds = true;
BitmapFactory.decodeByteArray(data, 0, data.length, sizeOptions);
Log.d(TAG, "Bitmap is " + sizeOptions.outWidth + "x"
            + sizeOptions.outHeight);

// Now use the size to determine the ratio you want to shrink it
final float widthSampling = sizeOptions.outWidth / DESIRED_WIDTH;
sizeOptions.inJustDecodeBounds = false;
// Note this drops the fractional portion, making it smaller
sizeOptions.inSampleSize = (int) widthSampling;
Log.d(TAG, "Sample size = " + sizeOptions.inSampleSize);

// Scale by the smallest amount so that image is at least the desired
// size in each direction
final Bitmap result = BitmapFactory.decodeByteArray(data, 0, data.length,
        sizeOptions);

There are lots of other interesting settings in BitmapFactory.Options