-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