我想缩放现有的位图。所以我使用Bitmap.createBitmap(位图b,int x,int y,int width,int height,Matrix m,boolean filter)来创建缩放位图。如果Matrix对象的比例小于1,则此方法效果很好。但是,如果该比率等于或大于1,则该方法返回具有我想要的宽度和高度但没有图像(是透明的)的位图。我想知道为什么以及如何解决这个问题。
Bitmap imageBitmap;
imageBitmap = weiboView.getDrawingCache();
Log.d("cosmo", "bitmap generated: "+imageBitmap.getWidth()+" * "+imageBitmap.getHeight());
//Init and configure and load the image view
ImageView imageView = new ImageView(this);
imageView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
imageView.setScaleType(ScaleType.FIT_CENTER);
containerLayout.addView(imageView);
//create a scaled bitmap to assign to the image view
Bitmap scaledImageBitmap = MyBitmapUtils.getBitmapScaledToFitWidth(getWindowManager().getDefaultDisplay().getWidth(), imageBitmap);
Log.d("cosmo", "scaled: "+scaledImageBitmap.getWidth()+" * "+scaledImageBitmap.getHeight());
//Here if I set imageBitmap as the image of imageView it works well
imageView.setImageBitmap(scaledImageBitmap);
这是MyBitmapUtils.getBitmapScaledToFitWidth:
public static Bitmap getBitmapScaledToFitWidth(int targetWidth, Bitmap bitmap) {
float ratio = (float)targetWidth/(float)bitmap.getWidth();
Log.d("cosmo", "ratio is "+ratio);
//ratio = 0.5f;
Matrix matrix = new Matrix();
matrix.postScale(ratio, ratio);
Bitmap target = Bitmap.createBitmap(bitmap,0,0,bitmap.getWidth(),bitmap.getHeight(),matrix,false);
return target;
}
我知道这是怎么发生的。这是因为Image的高度大于2048,并且在android系统中创建大于2048 * 2048的位图会导致OOM(奇怪的是我的logcat没有报告此错误)
答案 0 :(得分:0)
为什么不使用createScaledBitmap
?
Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, targetWidth, targetHeight, true);
您可以直接提供targetWidth和targetHeight,它应该比使用Matrix
自己缩放位图更可靠。
如果您只是为您的方法提供targetWidth,那么您必须计算targetHeight,它看起来像这样:
float ratio = (float)targetWidth/(float)bitmap.getWidth();
int targetHeight = (int)((float)bitmap.getHeight * ratio);
如果你把它放在你的方法中,它会是这样的:
public static Bitmap getBitmapScaledToFitWidth(double targetWidth, Bitmap bitmap) {
double bitmapWidth = bitmap.getWidth();
double bitmapHeight = bitmap.getHeight();
double widthRatio = targetWidth / bitmapWidth;
double targetHeight = widthRatio * bitmapHeight;
Bitmap target = Bitmap.createScaledBitmap(bitmap, (int)targetWidth, (int)targetHeight, true);
return target;
}
另外,请不要忘记尽快recycle()
不需要位图。这可以防止您遇到内存问题,例如,如果您在缩放后不再需要缩放后的位图,则可以直接在辅助方法中回收它:
public static Bitmap getBitmapScaledToFitWidth(double targetWidth, Bitmap bitmap) {
double bitmapWidth = bitmap.getWidth();
double bitmapHeight = bitmap.getHeight();
double widthRatio = targetWidth / bitmapWidth;
double targetHeight = widthRatio * bitmapHeight;
Bitmap target = Bitmap.createScaledBitmap(bitmap, (int)targetWidth, (int)targetHeight, true);
// Recycle old bitmap to free up memory.
bitmap.recycle();
return target;
}