从Uri创建调整大小的位图的正确方法是什么?

时间:2012-05-16 11:06:53

标签: java android

我正在尝试从Uri创建一个调整大小的位图 在网上搜索时,我看到几个部分例子,只是感到困惑 创建此任务的正确方法是什么?

感谢。

2 个答案:

答案 0 :(得分:1)

你应该阅读一篇非常好的资源文章:

http://developer.android.com/training/displaying-bitmaps/index.html

这里有一些代码,取自本文:

public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId, int reqWidth, int reqHeight) {
   // First decode with inJustDecodeBounds=true to check dimensions
   final BitmapFactory.Options options = new BitmapFactory.Options();
   options.inJustDecodeBounds = true;
   BitmapFactory.decodeResource(res, resId, options);
   // Calculate inSampleSize
   options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
   // Decode bitmap with inSampleSize set
   options.inJustDecodeBounds = false;
   return BitmapFactory.decodeResource(res, resId, options);
}

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) {
        if (width > height) {
            inSampleSize = Math.round((float) height / (float) reqHeight);
        } else {
            inSampleSize = Math.round((float) width / (float) reqWidth);
        }

        // This offers some additional logic in case the image has a strange
        // aspect ratio. For example, a panorama may have a much larger
        // width than height. In these cases the total pixels might still
        // end up being too large to fit comfortably in memory, so we should
        // be more aggressive with sample down the image (=larger
        // inSampleSize).

        final float totalPixels = width * height;

        // Anything more than 2x the requested pixels we'll sample down
        // further.
        final float totalReqPixelsCap = reqWidth * reqHeight * 2;

        while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) {
            inSampleSize++;
        }
    }
    return inSampleSize;
}

答案 1 :(得分:0)

Matrix matrix = new Matrix(); matrix.postScale(xScale,yScale); 位图newBitmap = Bitmap.createBitmap(oldBitmap,0,0,orgWidth,orgHeight,matrix,true);

如果你想减小其他正面的尺寸,那么xScale和yScale应该是负数:)