有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java会降低图像质量。OutOfMemory异常Android

我正在尝试实现一个应用程序,它在一个图像上做很多操作。我有优化的问题。运行我的应用程序的时间太长。我需要压缩我正在处理的图像。我试着用这个教程:

http://developer.安卓.com/training/displaying-bitmaps/load-bitmap.html

当我想从drawable文件夹中获取图像时,它工作得很好。问题是当我想从相机或画廊拍照时。我不知道我应该在“R.id.myimage”中放什么

所以问题是,如何使用这行代码:

BitmapFactory.decodeResource(getResources(), R.id.myimage, options);

当我想使用相机或图库而不是可绘图文件夹时


共 (1) 个答案

  1. # 1 楼答案

    为避免OOM错误,请使用以下方法缩放图像:

    //For resource
    image.setImageBitmap(decodeSampledBitmapFromResource("android.resource://com.my.package/drawable/image_name"));
    //For file
    image.setImageBitmap(decodeSampledBitmapFromResource(filepath));
    

    采样功能:

    public static int calculateInSampleSize(BitmapFactory.Options options,
        int reqWidth, int reqHeight) {
    
    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 2;
    if (height >= reqHeight || width >= reqWidth) {
        inSampleSize *= 2;
    }
    return inSampleSize;
    }
    
    public static Bitmap decodeSampledBitmapFromResource(String file,
        int reqWidth, int reqHeight) {
    
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(file, options);
    options.inSampleSize = calculateInSampleSize(options, reqWidth,
            reqHeight);
    options.inJustDecodeBounds = false;
    return BitmapFactory.decodeFile(file, options);
    }