在项目过程中,需要计算本地图片或者网络图片原来的旋转角度。这部分代码是从Glide的DownSampler类的,这里做一下记录。
Glide的类ImageHeaderParser中负责解析Image的头部信息,Glide分成两种情况:
- DefaultImageHeaderParser 默认的头部,是Glide自定义的头部解析器
- ExifInterfaceImageHeaderParser 利用了ExifInterface
一种是Android 7.0以上利用ExifInterface计算,另外一种低版本的Glide自定义的来解析头部信息获取旋转角度
我只是用了ExifInterfaceImageHeaderParser 的部分代码来获取角度,为了兼容低版本,还需要引入
implementation ‘com.android.support:exifinterface:28.0.0’
public class DownSampler {
private static final int MARK_POSITION = 10 * 1024 * 1024;
public static Size getDimensions(BufferedInputStream is, BitmapFactory.Options options) {
options.inJustDecodeBounds = true;
decodeStream(is, options);
options.inJustDecodeBounds = false;
return new Size(options.outWidth, options.outHeight);
}
public static boolean isScaling(BitmapFactory.Options options) {
return options.inTargetDensity > 0 && options.inDensity > 0
&& options.inTargetDensity != options.inDensity;
}
public static Bitmap decodeStream(BufferedInputStream is, BitmapFactory.Options options) {
if (options.inJustDecodeBounds) {
is.mark(MARK_POSITION);
}
final Bitmap result = BitmapFactory.decodeStream(is, null, options);
if (options.inJustDecodeBounds) {
try {
is.reset();
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
public static int getRotate(BufferedInputStream is) {
try {
int orientation = getOrientation(is);
return getExifOrientationDegrees(orientation);
} catch (IOException e) {
e.printStackTrace();
}
return 0;
}
public static int getOrientation(BufferedInputStream is) throws IOException {
ExifInterface exifInterface = null;
is.mark(MARK_POSITION);
exifInterface = new ExifInterface(is);
int result = exifInterface.getAttributeInt(
ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
try {
is.reset();
} catch (IOException e) {
e.printStackTrace();
}
if (result == ExifInterface.ORIENTATION_UNDEFINED) {
return 0;
}
return result;
}
public static int getExifOrientationDegrees(int exifOrientation) {
final int degreesToRotate;
switch (exifOrientation) {
case ExifInterface.ORIENTATION_TRANSPOSE:
case ExifInterface.ORIENTATION_ROTATE_90:
degreesToRotate = 90;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
case ExifInterface.ORIENTATION_FLIP_VERTICAL:
degreesToRotate = 180;
break;
case ExifInterface.ORIENTATION_TRANSVERSE:
case ExifInterface.ORIENTATION_ROTATE_270:
degreesToRotate = 270;
break;
default:
degreesToRotate = 0;
break;
}
return degreesToRotate;
}
}
原创文章,作者:奋斗,如若转载,请注明出处:https://blog.ytso.com/6268.html