【发布时间】:2015-03-07 01:14:17
【问题描述】:
有没有一种简单的方法可以使用BitmapFactory.decodeFile() 或BitmapFactory.decodeStream() 直接获取中心裁剪的位图,而不是先加载完整的位图,然后应用位图转换,例如Bitmap cropped = Bitmap.createBitmap(...)?我想当编码已知时,应该可以只读取创建裁剪所需的位图的相关部分。
基本上我想节省内存并防止内存不足的情况,同时加载完整的位图只是为了计算缩略图。
如果有人能指出我正确的方向并给我一些关键词,我将非常感激。
为了完整起见,这是我目前用来裁剪位图的代码,这是我在 stackoverflow 上找到的一种方法:
public Bitmap scaleCenterCrop(Bitmap source, int newHeight, int newWidth) {
int sourceWidth = source.getWidth();
int sourceHeight = source.getHeight();
// Compute the scaling factors to fit the new height and width, respectively.
// To cover the final image, the final scaling will be the bigger
// of these two.
float xScale = (float) newWidth / sourceWidth;
float yScale = (float) newHeight / sourceHeight;
float scale = Math.max(xScale, yScale);
// Now get the size of the source bitmap when scaled
float scaledWidth = scale * sourceWidth;
float scaledHeight = scale * sourceHeight;
// Let's find out the upper left coordinates if the scaled bitmap
// should be centered in the new size give by the parameters
float left = (newWidth - scaledWidth) / 2;
float top = (newHeight - scaledHeight) / 2;
// The target rectangle for the new, scaled version of the source bitmap will now
// be
RectF targetRect = new RectF(left, top, left + scaledWidth, top + scaledHeight);
// Finally, we create a new bitmap of the specified size and draw our new,
// scaled bitmap onto it.
// TODO: I think we crash here (null pointer exception) when the receiving image is an animated gif
Bitmap dest = Bitmap.createBitmap(newWidth, newHeight, source.getConfig());
Canvas canvas = new Canvas(dest);
canvas.drawBitmap(source, null, targetRect, null);
return dest;
}
【问题讨论】:
标签: android image crop bitmapfactory