首页 > 解决方案 > 我正在尝试保存从 Android 相机拍摄的照片,但收到 OutOfMemoryError 错误

问题描述

我正在尝试保存从 Android 相机拍摄的照片,但出现以下错误

抛出 OutOfMemoryError “无法分配 51916812 字节分配,其中 12763771 个可用字节和 12MB 直到 OOM”

我想以最佳图像质量存储它。

可能吗?

下面是源代码

private class SaveImageTask extends AsyncTask<byte[], Void, Void> {


    @Override
    protected void onPreExecute() {
        super.onPreExecute();

    }

    @Override
    protected Void doInBackground(byte[]... data) {

        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inPreferredConfig = Bitmap.Config.ARGB_8888;
        Bitmap bitmap = BitmapFactory.decodeByteArray(data[0], 0, data[0].length, options);

        Log.i("sinwhod","matrix = " + orientation);


        Matrix matrix = new Matrix();
        //matrix.postRotate(orientation);
        matrix.setRotate(orientation);
        bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);

        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
        byte[] currentData = stream.toByteArray();

        Date day = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault());
        fileName = String.valueOf(sdf.format(day));

        savePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString();

        temp = savePath + "/" + fileName + ".jpg";

        File file = new File(temp);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(currentData);
            fos.flush();
            fos.close();
        } catch (Exception e) {
            Log.i("sinwhod", "error = " + e);

        }


        sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + temp)));


        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);

        Toast.makeText(MainActivity.this, temp, Toast.LENGTH_SHORT).show();

    }
}

'''

标签: android

解决方案


推荐阅读