Bitmap tempBitmap = BitmapFactory.decodeFile(picPath, opts);
newBitmap = Bitmap.createScaledBitmap(tempBitmap, desiredWidth, desiredHeight, true);
tempBitmap.recycle();
如上代码所示获取newBitmap,有些情况下发现newBitmap后来变成了null,查看源码注释发现问题所在:
翻译:如果传入的dstWidth、dstHeight和source bitmap的width、height相等,则会直接返回source bitmap。
所以上面我们获取newBitmap需要加个判断,正确写法为:
Bitmap tempBitmap = BitmapFactory.decodeFile(picPath, opts);
if (tempBitmap.getWidth() == desiredWidth && tempBitmap.getHeight() == desiredHeight) {
newBitmap = tempBitmap;
} else {
newBitmap = Bitmap.createScaledBitmap(tempBitmap, desiredWidth, desiredHeight, true);
tempBitmap.recycle();
}