【发布时间】:2013-07-24 05:54:47
【问题描述】:
我想创建一个缩放位图,但我似乎得到了一个不成比例的图像。它看起来像一个正方形,而我想要长方形。
我的代码:
Bitmap resizedBitmap = Bitmap.createScaledBitmap(myBitmap, 960, 960, false);
我希望图像的 MAX 为 960。我该怎么做?将宽度设置为 null 不会编译。这可能很简单,但我无法理解它。谢谢
【问题讨论】:
我想创建一个缩放位图,但我似乎得到了一个不成比例的图像。它看起来像一个正方形,而我想要长方形。
我的代码:
Bitmap resizedBitmap = Bitmap.createScaledBitmap(myBitmap, 960, 960, false);
我希望图像的 MAX 为 960。我该怎么做?将宽度设置为 null 不会编译。这可能很简单,但我无法理解它。谢谢
【问题讨论】:
如果内存中已经有了原始位图,则不需要进行inJustDecodeBounds、inSampleSize等全过程,只需要弄清楚要使用什么比例并进行相应的缩放即可。
final int maxSize = 960;
int outWidth;
int outHeight;
int inWidth = myBitmap.getWidth();
int inHeight = myBitmap.getHeight();
if(inWidth > inHeight){
outWidth = maxSize;
outHeight = (inHeight * maxSize) / inWidth;
} else {
outHeight = maxSize;
outWidth = (inWidth * maxSize) / inHeight;
}
Bitmap resizedBitmap = Bitmap.createScaledBitmap(myBitmap, outWidth, outHeight, false);
如果此图像的唯一用途是缩放版本,则最好使用 Tobiel 的答案,以尽量减少内存使用。
【讨论】:
outHeight = inHeight * (outWidth / inWidth);而不是outHeight = (inHeight * maxSize) / inWidth;会更易读/易懂
您的图像是方形的,因为您设置了width = 960 和height = 960。
您需要创建一个方法来传递您想要的图像大小,如下所示:http://developer.android.com/training/displaying-bitmaps/load-bitmap.html
在代码中是这样的:
public static Bitmap lessResolution (String filePath, int width, int height) {
int reqHeight = height;
int reqWidth = width;
BitmapFactory.Options options = new BitmapFactory.Options();
// First decode with inJustDecodeBounds=true to check dimensions
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(filePath, options);
}
private static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
// Calculate ratios of height and width to requested height and width
final int heightRatio = Math.round((float) height / (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
// Choose the smallest ratio as inSampleSize value, this will guarantee
// a final image with both dimensions larger than or equal to the
// requested height and width.
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
}
return inSampleSize;
}
【讨论】:
bmpimg = Bitmap.createScaledBitmap(srcimg, 100, 50, true);
【讨论】: