旋转位图时遇到了很多麻烦。 下面的代码有效,但它比Galaxy Note 2手机附带的Gallery应用程序慢4-6倍。
代码:
File DirectoryFile = new File(Image_Path);
Bitmap bitmap = BitmapFactory.decodeFile(DirectoryFile.getAbsolutePath());
String imagePATH = FileLocation + "test.jpg";
final File newfile = new File(imagePATH);
FileOutputStream mFileOutputStream = null;
try {
mFileOutputStream = new FileOutputStream(newfile);
} catch (FileNotFoundException e1) { }
try {
Bitmap RotatedBitmap = RotateImage(imagePATH, bitmap);
RotatedBitmap.compress(Bitmap.CompressFormat.JPEG, 100, mFileOutputStream);
bitmap.recycle();
RotatedBitmap.recycle();
mFileOutputStream.flush();
mFileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
private Bitmap RotateImage(String filePath, Bitmap bitmap) throws IOException {
ExifInterface exif = new ExifInterface(filePath);
int exifOrientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
int rotate = 0;
switch (exifOrientation) {
case ExifInterface.ORIENTATION_NORMAL: rotate = 0; break;
case ExifInterface.ORIENTATION_UNDEFINED: rotate = 90; break;
case ExifInterface.ORIENTATION_ROTATE_90: rotate = 90; break;
case ExifInterface.ORIENTATION_ROTATE_180: rotate = 180; break;
case ExifInterface.ORIENTATION_ROTATE_270: rotate = 270; break;
}
Matrix matrix = new Matrix();
matrix.postRotate(rotate);
//matrix.setRotate(rotate); is no difference ???
return bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, false);
}
请有人请指导我吗?
如何让它像Gallery应用程序一样工作?
答案 0 :(得分:0)
Picasso库是处理位图或图像旋转的最佳工具。 在build.gradle中添加此依赖项'com.squareup.picasso:picasso:2.5.2'
请参阅以下代码段以供参考
Picasso.with(context)
.load(new File(path))
.resize(width, height) // optional
.rotate(getAngleOfRotation(path)) // optional
.into(imageview);
private float getAngleOfRotation(String path) {
ExifInterface exif = null;
try {
exif = new ExifInterface(path);
} catch (IOException e) {
e.printStackTrace();
}
try {
switch (exif
.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1)) {
case ExifInterface.ORIENTATION_ROTATE_180:
return 180;
case ExifInterface.ORIENTATION_ROTATE_90:
return 90;
case ExifInterface.ORIENTATION_ROTATE_270:
return 270;
case ExifInterface.ORIENTATION_NORMAL:
return 0;
default:
return 0;
}
} catch (NullPointerException e) {
e.printStackTrace();
}
return 0;
}