旋转位图时出现 OutOfMemoryError 错误

OutOfMemoryError error while rotating a bitmap

目标: 我想将捕获的图像文件发送到服务器,在代码中我可以使用改造将 photoFile 发送到服务器,但是图像在服务器上旋转边,所以我的目标是观察旋转,旋转回真实状态,然后 post 将该文件发送到服务器。

问题:我从 cam 捕获图像,然后观察它的旋转,并基于此尝试将它旋转回来,但在创建第二个旋转位图时出现内存不足错误.

问题:我正在寻找可以旋转并将其发送到服务器而不创建位图的解决方案,如果不能,避免内存不足错误并将正确旋转的文件发送到服务器。

       else if (requestCode == CAPTURE_IMAGE) {
            ExifInterface exifInterface = new ExifInterface(photoFile.getAbsolutePath());
            Bitmap bitmapOrg = BitmapFactory.decodeFile(photoFile.getAbsolutePath(), new BitmapFactory.Options());
            Matrix matrix = new Matrix();

            //getRotation method rightly gives 90 as rotation.
            matrix.postRotate(getRotation(exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, 
                                  ExifInterface.ORIENTATION_NORMAL)));

            //point of outofmemory error while creating this bitmap
            Bitmap rotated = Bitmap.createBitmap(bitmapOrg, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
            Log.d(TAG, "onActivityResult: ");
        } 

it gives out of memory error while creating second rotated bitmap

您可能没有可用的系统 RAM 来加载单张全分辨率照片,更不用说其中两张了。您的主要选择是:

  • 不要加载全分辨率照片。相反,选择较小的分辨率,使用 BitmapFactory.OptionsinSampleSize 在加载图像时 Android 缩小图像。这不能保证它会工作,因为你的堆可能相当大碎片化,但它增加了它起作用的可能性。

  • 在服务器上进行轮换,那里有大量 RAM,大量 CPU 时间等

  • 加载照片并在 C/C++ 代码中进行旋转,使用 Android NDK,因为本机分配(例如,malloc())不会计入您的堆限制。

  • 在您的 <application> 的清单中使用 android:largeHeap="true"。在某些设备上,这将为您提供更大的堆。无法保证您会获得更大的堆,即使使用更大的堆,您仍然可能 运行 内存不足。

I am looking for solution where I can rotate and send it to server without creating bitmap

Android 中没有任何内容,抱歉。

我知道您有时必须旋转位图,所以这是我在大部分项目中使用的助手,如果它解决了您的问题,请告诉我:

public static Bitmap getRotatedBitmap(Bitmap bm, float degree) {
        Bitmap bitmap = bm;
        if (degree != 0) {
            Matrix matrix = new Matrix();
            matrix.preRotate(degree);
//            if(shouldFlip)
//                matrix.preScale(-1,1);
            bitmap = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(),
                    bm.getHeight(), matrix, true);
        }

        return bitmap;
    }