在android上将大位图文件调整为缩放输出文件我在一个文件中有一个大位图(比如3888x2592)。现在,我希望将该位图调整为800x533,并将其保存到另一个文件中。我通常会通过调用Bitmap.createBitmap方法,但它需要一个源位图作为第一个参数,但我无法提供这个参数,因为将原始图像加载到Bitmap对象中当然会超出内存(请参见这里例如)。我也不能读位图,例如,BitmapFactory.decodeFile(file, options),提供BitmapFactory.Options.inSampleSize,因为我想把它调整到精确的宽度和高度。使用inSampleSize将位图调整为972x648(如果我使用inSampleSize=4)或至778x518(如果我使用inSampleSize=5,这甚至不是一种力量。我还想避免使用inSampleSize读取图像,例如,在第一步中使用972x648,然后在第二步将其调整到精确的800x533,因为与原始图像的直接调整相比,质量会很差。总结我的问题:是否有一种方法可以读取10 MP或更多的大型图像文件,并将其保存到新的图像文件中,调整到特定的新宽度和高度,而无需获得OutOfMemory异常?我也试过BitmapFactory.decodeFile(file, options)并手动将Options.outHight和Options.outWidth值设置为800和533,但它不是这样工作的。
3 回答
HUH函数
TA贡献1836条经验 获得超4个赞
没有。
计算最大可能 inSampleSize它仍然产生一个比你的目标大的图像。 使用 BitmapFactory.decodeFile(file, options),将SampleSize作为选项传递。 使用 Bitmap.createScaledBitmap().
慕容708150
TA贡献1831条经验 获得超4个赞
private Bitmap getBitmap(String path) {Uri uri = getImageUri(path);InputStream in = null;try {
final int IMAGE_MAX_SIZE = 1200000; // 1.2MP
in = mContentResolver.openInputStream(uri);
// Decode image size
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(in, null, options);
in.close();
int scale = 1;
while ((options.outWidth * options.outHeight) * (1 / Math.pow(scale, 2)) >
IMAGE_MAX_SIZE) {
scale++;
}
Log.d(TAG, "scale = " + scale + ", orig-width: " + options.outWidth + ",
orig-height: " + options.outHeight);
Bitmap resultBitmap = null;
in = mContentResolver.openInputStream(uri);
if (scale > 1) {
scale--;
// scale to max possible inSampleSize that still yields an image
// larger than target
options = new BitmapFactory.Options();
options.inSampleSize = scale;
resultBitmap = BitmapFactory.decodeStream(in, null, options);
// resize to desired dimensions
int height = resultBitmap.getHeight();
int width = resultBitmap.getWidth();
Log.d(TAG, "1th scale operation dimenions - width: " + width + ",
height: " + height);
double y = Math.sqrt(IMAGE_MAX_SIZE / (((double) width) / height));
double x = (y / height) * width;
Bitmap scaledBitmap = Bitmap.createScaledBitmap(resultBitmap, (int) x,
(int) y, true);
resultBitmap.recycle();
resultBitmap = scaledBitmap;
System.gc();
} else {
resultBitmap = BitmapFactory.decodeStream(in);
}
in.close();
Log.d(TAG, "bitmap size - width: " +resultBitmap.getWidth() + ", height: " +
resultBitmap.getHeight());
return resultBitmap;} catch (IOException e) {
Log.e(TAG, e.getMessage(),e);
return null;}- 3 回答
- 0 关注
- 414 浏览
添加回答
举报
0/150
提交
取消
