我想创建一个缩放的位图,但我似乎得到了一个不成比例的图像。它看起来像一个正方形,而我想要长方形。
我的代码:
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 的答案,以最大程度地减少内存使用。
您的图像是方形的,因为您正在设置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);