我正在开发一个应用程序,它使用相机拍照后旋转和缩放图片。因为相机返回的图像是错误旋转的,所以我需要旋转图像,并缩小图像以减小其大小。 我首先将相机返回的原始图像保存在临时目录中,然后读取它并进行修改,将新图像保存到新文件中。 我尝试使用矩阵来旋转和缩放图片,但它会失去质量。 然后我尝试先使用Bitmap.createScaledBitmap缩放图片,然后再使用矩阵旋转图片,但结果比仅使用矩阵更难看。 然后我尝试先旋转图像,然后再使用Bitmap.createScaledBitmap调整大小。图像不会失去质量,但由于在旋转后缩放,宽度和高度被反转。我也尝试根据所做的旋转反转高度和宽度,但它再次失去了质量。 这是我最近编写的代码:
in= new FileInputStream(tempDir+"/"+photo1_path);
out = new FileOutputStream(file+"/picture.png");
Bitmap src = BitmapFactory.decodeStream(in);
int iwidth = src.getWidth();
int iheight = src.getHeight();
int newWidth = 0;
int newHeight = 0;
newWidth = 800;
newHeight = 600;
// calculate the scale - in this case = 0.4f
float scaleWidth = ((float) newWidth) / iwidth;
float scaleHeight = ((float) newHeight) / iheight;
// createa matrix for the manipulation
Matrix matrix = new Matrix();
// resize the bit map
//matrix.postScale(scaleWidth, scaleHeight);
int orientation = getOrientation(MyActivity.this,Uri.parse(tempDir+"/"+photo1_path));
switch(orientation) {
case 3:
orientation = 180;
break;
case 6:
orientation = 90;
break;
case 8:
orientation = 270;
break;
}
int rotate = 0;
switch(orientation) {
case 90:
rotate=90;
break;
case 180:
rotate=180;
break;
case 270:
rotate=270;
break;
}
// rotate the Bitmap
matrix.postRotate(rotate);
src =Bitmap.createScaledBitmap(src , newWidth, newHeight, false);
// recreate the new Bitmap
Bitmap new_bit = Bitmap.createBitmap(src, 0, 0,
src.getWidth(), src.getHeight(), matrix, true);
new_bit.compress(Bitmap.CompressFormat.PNG, 100, out);
有什么建议吗?
编辑:如果我只旋转或只缩放图像,它不会失去质量。只有当我两者都做时,图像才会失去质量。此外,如果我在调整大小和缩放后将图像放入ImageView中,它不会失去质量,只有在保存到文件时才会失去质量。
Bitmap.CompressFormat.PNG
的问题在于每次旋转后文件大小会变得更大。 - Yoann Hercouet