按比例调整位图的大小
问题描述:
我有一个位图...如果位图的高度大于maxHeight,或者宽度大于maxWidth,我想按比例调整图像的大小,使其适合maxWidth X最大高度。这里就是我想:按比例调整位图的大小
BitmapDrawable bmp = new BitmapDrawable(getResources(), PHOTO_PATH);
int width = bmp.getIntrinsicWidth();
int height = bmp.getIntrinsicHeight();
float ratio = (float)width/(float)height;
float scaleWidth = width;
float scaleHeight = height;
if((float)mMaxWidth/(float)mMaxHeight > ratio) {
scaleWidth = (float)mMaxHeight * ratio;
}
else {
scaleHeight = (float)mMaxWidth/ratio;
}
Matrix matrix = new Matrix();
matrix.postScale(scaleWidth, scaleHeight);
Bitmap out = Bitmap.createBitmap(bmp.getBitmap(),
0, 0, width, height, matrix, true);
try {
out.compress(Bitmap.CompressFormat.JPEG, 100,
new FileOutputStream(PHOTO_PATH));
}
catch(FileNotFoundException fnfe) {
fnfe.printStackTrace();
}
我得到以下异常:
java.lang.IllegalArgumentException: bitmap size exceeds 32bits
什么我错在这里做什么?
答
您的scaleWidth和scaleHeight应该是比例因子(所以不是很大的数字),但是您的代码似乎通过了您要查找的实际宽度和高度。所以你最终会大幅增加你的位图的大小。
我认为还有其他的代码来衍生scaleWidth和scaleHeight的问题。一方面,你的代码总是有scaleWidth = width或scaleHeight =高度,并且只改变其中的一个,所以你将会扭曲图像的高宽比。如果你只是想调整图像大小,那么你应该只有一个scaleFactor。
此外,为什么您的if语句有效地检查了最大比率?你不应该检查宽度> maxWidth或高度> maxHeight?
答
这是因为scaleWidth
或scaleHeight
的值过大,scaleWidth
或scaleHeight
是意味着放大或缩小的比率,而不是width
或height
,过大的速率导致bitmap
大小超过32位
matrix.postScale(scaleWidth, scaleHeight);
答
这就是我是如何做到的:
public Bitmap decodeAbtoBm(byte[] b){
Bitmap bm; // prepare object to return
// clear system and runtime of rubbish
System.gc();
Runtime.getRuntime().gc();
//Decode image size only
BitmapFactory.Options oo = new BitmapFactory.Options();
// only decodes size, not the whole image
// See Android documentation for more info.
oo.inJustDecodeBounds = true;
BitmapFactory.decodeByteArray(b, 0, b.length ,oo);
//The new size we want to scale to
final int REQUIRED_SIZE=200;
// Important function to resize proportionally.
//Find the correct scale value. It should be the power of 2.
int scale=1;
while(oo.outWidth/scale/2>=REQUIRED_SIZE
&& oo.outHeight/scale/2>=REQUIRED_SIZE)
scale*=2; // Actual scaler
//Decode Options: byte array image with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize=scale; // set scaler
o2.inPurgeable = true; // for effeciency
o2.inInputShareable = true;
// Do actual decoding, this takes up resources and could crash
// your app if you do not do it properly
bm = BitmapFactory.decodeByteArray(b, 0, b.length,o2);
// Just to be safe, clear system and runtime of rubbish again!
System.gc();
Runtime.getRuntime().gc();
return bm; // return Bitmap to the method that called it
}
你能在这里通过更正的代码吗?我得到同样的例外 – Mahesh 2012-12-12 07:07:45