-1
下面的代码是从Android的开发人员采用,很少有变化:安卓:未能缩小位图对象
private 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) {
final int halfHeight = height/2;
final int halfWidth = width/2;
// Calculate the largest inSampleSize value that is a power of 2 and
// keeps both height and width larger than the requested height and
// width.
while ((halfHeight/inSampleSize) > reqHeight
&& (halfWidth/inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
public static Bitmap decodeSampledBitmap(Bitmap bitmap, int reqWidth,
int reqHeight) {
int size = bitmap.getRowBytes() * bitmap.getHeight();
InputStream is = new ByteArrayInputStream(new byte[size]);
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(is, null, options);
// I set these manually because decodeStream set them to -1
options.outHeight = bitmap.getHeight();
options.outWidth = bitmap.getWidth();
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth,
reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
// can the number of rows be wrong now?
size = bitmap.getRowBytes() * options.outHeight;
is = new ByteArrayInputStream(new byte[size]);
return BitmapFactory.decodeStream(is, null, options);
}
我有两个问题:
- 当
decodeStream
读取位图界限,选项.outHeight和options.outWidth都设置为-1,我不知道为什么 - 公共方法返回null时,从我的设备的摄像头(因此从文件读取)位图,但工作正常时位图取自图像t帽子已经存在于我的手机上(从画廊中选择)。
问题可能出在哪里?谢谢!
是你的目录包含图像? – QuokMoon
您如何期望BitmapFactory解码'is',因为它里面什么都没有? ('new byte [size]'很空...) – njzk2
使用http://developer.android.com/reference/android/graphics/Bitmap.html createScaledBitmap – njzk2