这是Mojo Risin和Ofir的解决方案“结合”而成的。这会给你一个在最大宽度和最大高度边界内按比例调整大小的图像。
- 它只读取元数据以获取原始大小(options.inJustDecodeBounds)
- 它使用粗略的调整大小来节省内存(itmap.createScaledBitmap)
- 它使用基于先前创建的粗略Bitamp的精确调整大小的图像。
对我来说,它在5兆像素以下的图片上表现良好。
try
{
int inWidth = 0;
int inHeight = 0;
InputStream in = new FileInputStream(pathOfInputImage);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(in, null, options);
in.close();
in = null;
inWidth = options.outWidth;
inHeight = options.outHeight;
in = new FileInputStream(pathOfInputImage);
options = new BitmapFactory.Options();
options.inSampleSize = Math.max(inWidth/dstWidth, inHeight/dstHeight);
Bitmap roughBitmap = BitmapFactory.decodeStream(in, null, options);
Matrix m = new Matrix();
RectF inRect = new RectF(0, 0, roughBitmap.getWidth(), roughBitmap.getHeight());
RectF outRect = new RectF(0, 0, dstWidth, dstHeight);
m.setRectToRect(inRect, outRect, Matrix.ScaleToFit.CENTER);
float[] values = new float[9];
m.getValues(values);
Bitmap resizedBitmap = Bitmap.createScaledBitmap(roughBitmap, (int) (roughBitmap.getWidth() * values[0]), (int) (roughBitmap.getHeight() * values[4]), true);
try
{
FileOutputStream out = new FileOutputStream(pathOfOutputImage);
resizedBitmap.compress(Bitmap.CompressFormat.JPEG, 80, out);
}
catch (Exception e)
{
Log.e("Image", e.getMessage(), e);
}
}
catch (IOException e)
{
Log.e("Image", e.getMessage(), e);
}