android - 保存从相机拍摄的图片时,android 中出现 java.lang.OutOfMemoryError

标签 android bitmap android-camera out-of-memory

我有一个应用程序,需要在从相机拍摄图像后将图像保存到 SD 卡中。

这是代码:

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);

这一行的代码炸弹:

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

它说:

异常类java.lang.OutOfMemoryError 源方法 BitmapFactory.nativeDecodeByteArray()。

请帮忙

最佳答案

如果您只是想将图片存储到SD卡中,则无需创建Bitmap。假设您想要获取宽度 >= 640px 的图像:

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);

BitmapFactory.Options 中还有很多其他有趣的设置

关于android - 保存从相机拍摄的图片时,android 中出现 java.lang.OutOfMemoryError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8419140/

相关文章:

android - 如何覆盖 Dialog 中的 dismiss() ?安卓

android - IOS/Android 上的 NodeJS

arrays - 当像素阵列为小型可编辑文本 AS3 时,未生成 8 位 BMP 图像

android - RoundedImageView - 添加填充而不裁剪图像

bitmap - nreco 包装位图通过 rtmp 流式传输

android - 相机图片到位图导致图像困惑

android - 如何以编程方式打开设备扩展坞设置?

Java 是一个数组列表按顺序包含另一个数组列表

android - 想要在 Android 中使用 ZBar 扫描仪库进行更大的相机预览

Android - 无法从 4.2.2 上的相机 Intent 获取图像