【问题标题】:How do you deal with insanely high MP cameras (and images) on Android? - "Canvas: trying to draw too large bitmap"您如何处理 Android 上的高 MP 相机(和图像)? - “画布:试图绘制过大的位图”
【发布时间】:2021-06-22 13:34:12
【问题描述】:

我有一个活动,用户可以像这样打开相机

getPictureUri(createImageFromFile = true)?.let {
        photoUri = it
        openCameraActivity(REQUEST_IMAGE_CAPTURE, it)
    } ?: photoViewModel.onRequestUriError()

openCamera 是一个看起来像这样的 Activity 扩展

fun Activity.openCameraActivity(requestCode: Int, pictureUri: Uri) {
Intent(MediaStore.ACTION_IMAGE_CAPTURE).also { takePictureIntent ->
    takePictureIntent.resolveActivity(packageManager)?.also {
        takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, pictureUri)
        takePictureIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
        startActivityForResult(takePictureIntent, requestCode)
    }
}

}

当我们取回图像时,我们将图像写入文件,并将 photoUri 存储在应用程序的某个地方。效果很好!问题是一些用户有超高像素相机,比如 64mp,当他们拍照时,它试图在 UI 中显示,但它崩溃了。

FATAL EXCEPTION: main
Process: co.app.staging, PID: 27859
java.lang.RuntimeException: Canvas: trying to draw too large(256576512bytes) bitmap.

有没有办法可以限制相机的分辨率?我可以降低质量,但这似乎充其量只是一个创可贴。有哪些不错的解决方案?

【问题讨论】:

  • 考虑使用像github.com/davemorrissey/subsampling-scale-image-view 这样可以处理高分辨率图像的东西。
  • 它不仅仅是显示它,我也不想存储非常大的图像。超过 1080p 的任何内容都超出了我的需要。
  • “我也不想存储过大的图像”——那么不要使用ACTION_IMAGE_CAPTURE。直接或通过包装库(CameraX、FotoApparat、CameraKit-Android 等)使用相机 API。
  • 不知道CameraX,让我试一试

标签: android image kotlin canvas camera


【解决方案1】:

我尝试用这种方法从URI 在画布上绘制位图,试试这个:

(解释如下代码)

private void drawBitmapUriOnCanvas(Uri selectedImage) {
    if (selectedImage != null) {
        BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
        bmpFactoryOptions.inJustDecodeBounds = true;

        try {
            BitmapFactory.decodeStream(getContentResolver().openInputStream(
                    selectedImage), null, bmpFactoryOptions);

            bmpFactoryOptions.inSampleSize = 2;
            bmpFactoryOptions.inJustDecodeBounds = false;
            Bitmap bmp = BitmapFactory
                    .decodeStream(getContentResolver().openInputStream(
                            selectedImage), null, bmpFactoryOptions);

            Bitmap alteredBitmap;
            if (bmp != null) {
                if (getDeviceRam(this) <= 1024) {
                    bmp = getResizedBitmap(bmp, displayWidth);
                }
                bmp = checkAndRotateBitmap(bmp);
                alteredBitmap = Bitmap.createBitmap(bmp.getWidth(), bmp
                        .getHeight(), bmp.getConfig());

                Canvas canvas = new Canvas(alteredBitmap);
                Paint paint = new Paint();
                paint.setColor(Color.WHITE);
                paint.setStrokeWidth(5);
                paint.setAntiAlias(true);
                Matrix matrix = new Matrix();
                canvas.drawBitmap(bmp, matrix, paint);

                (now alteredBitmap is processed bitmap and you can use it)
            }
        } catch (FileNotFoundException e) {
            Toast.makeText(this, "Error reading Image Metadata", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }
    }
}

其他包含的方法:

public static long getDeviceRam(Context context) {
    ActivityManager actManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    ActivityManager.MemoryInfo memInfo = new ActivityManager.MemoryInfo();
    actManager.getMemoryInfo(memInfo);
    long totalMemory = memInfo.totalMem;
    long fileSizeInKB = totalMemory / 1024;
    // Convert the KB to MegaBytes (1 MB = 1024 KBytes)
    return fileSizeInKB / 1024;
}

public static Bitmap getResizedBitmap(Bitmap image, int maxSize) {
    int width = image.getWidth();
    int height = image.getHeight();

    float bitmapRatio = (float) width / (float) height;
    if (bitmapRatio > 1) {
        width = maxSize;
        height = (int) (width / bitmapRatio);
    } else {
        height = maxSize;
        width = (int) (height * bitmapRatio);
    }
    return Bitmap.createScaledBitmap(image, width, height, true);
}

在这里,首先我使用BitmapFactory 解码了图像 uri,然后我检查了设备内存,它是 1GB,然后我调整位图的大小,其他明智的原始位图将可以用于下一步,

接下来只是在画布上绘制位图,你会得到alteredBitmap 将是处理后的位图,它会很容易使用。

如果这不起作用,那么还有另一个选项可以满足您的要求,如下所示:

Bitmap bitmap = getBitmapFromGallery(selectedImage.getPath(), 800, 800);

private Bitmap getBitmapFromGallery(String path, int width, int height) {

    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(path, options);

    // Calculate inSampleSize
    options.inSampleSize = calculateInSampleSize(options, width, height);

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;
    Bitmap bitmap = BitmapFactory.decodeFile(path, options);

    // if you use image from camera then in some cases it will rotated automatically like it was captured landscape but displays portrait then you have to use method `checkAndRotateBitmap()` which was also given below
    //    bitmap = checkAndRotateBitmap(bitmap);
    return bitmap;
}

public static int calculateInSampleSize(
        BitmapFactory.Options options, int reqWidth, int reqHeight) {
    // Raw height and width of image
    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;

    if (height > reqHeight || width > reqWidth) {

        final int halfHeight = height / 2;
        final int halfWidth = width / 2;

        // Calculate the largest inSampleSize value that is a power of 2 and keeps both
        // height and width larger than the requested height and width.
        while ((halfHeight / inSampleSize) >= reqHeight
                && (halfWidth / inSampleSize) >= reqWidth) {
            inSampleSize *= 2;
        }
    }
    return inSampleSize;
}

private Bitmap checkAndRotateBitmap(Bitmap bmp) {
    try {
        ExifInterface ei = new ExifInterface(imgPath);
        int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                ExifInterface.ORIENTATION_UNDEFINED);

        Bitmap rotatedBitmap;

        switch (orientation) {

            case ExifInterface.ORIENTATION_ROTATE_90:
                rotatedBitmap = Helper.rotateImage(bmp, 90);
                break;

            case ExifInterface.ORIENTATION_ROTATE_180:
                rotatedBitmap = Helper.rotateImage(bmp, 180);
                break;

            case ExifInterface.ORIENTATION_ROTATE_270:
                rotatedBitmap = Helper.rotateImage(bmp, 270);
                break;

            case ExifInterface.ORIENTATION_NORMAL:
            default:
                rotatedBitmap = bmp;
        }
        return rotatedBitmap;

    } catch (IOException e) {
        e.printStackTrace();
        return bmp;
    }
}

编辑

有关getBitmapFromGallery() 方法如何工作的更多信息,您应该查看https://medium.com/android-news/loading-large-bitmaps-efficiently-in-android-66826cd4ad53

这就是我的朋友,现在尝试一种满足您要求的方法,让我知道这是否可行,如果有任何问题,也请帮助我改进我的答案..谢谢!!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-23
    • 1970-01-01
    • 2020-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多