When you use ImageView to display images in Android, you find that the picture is not showing, the direction is skewed or upside down.
To solve this problem, it is natural to think of two steps to go:
1. Automatic recognition of Image direction and calculation of rotation angle;
2, the image is rotated and displayed.
first, identify the direction of the image
First of all, here is a concept exif (exchangeable image file Format, interchangeable images files), specifically explained in the wiki.
In short, EXIF is a standard for electronic cameras (also including mobile phones, scanners, etc.) to standardize pictures, sounds, video screens, and some of their auxiliary tag formats.
The format for EXIF support is as follows:
Image
Compressed image files: JPEG, DCT
Non-compressed image file: TIFF
Not supported: JPEG 2000, PNG, GIF
Audio
RIFF, WAV
Android provides support for JPEG image EXIF interface, can read JPEG file metadata information, see Exifinterface.
The metadata information is generally divided into three categories: date time, spatial information (latitude and longitude, altitude), camera information (aperture, focal length, rotation angle, exposure amount, etc.).
second, the image rotation
Android provides a matrix rotation operation for bitmap, see the static CreateBitmap method provided by bitmap.
public static Bitmap CreateBitmap (Bitmap source, int x, int y, int width, int height, Matrix m, Boolean filter)
IllegalArgumentException if the x, y, width, height values are outside of the dimensions of the source bitmap.
To these two problems theoretically are resolved, start the actual operation of the bar, reference to the following code.
Copy Code code as follows:
public class Iohelper {
......
/** loading pictures from a given path
public static Bitmap LoadBitmap (String imgpath) {
Return Bitmapfactory.decodefile (Imgpath);
}
/** loads the picture from the given path and specifies whether to rotate the direction automatically.
public static Bitmap LoadBitmap (String imgpath, Boolean adjustoritation) {
if (!adjustoritation) {
Return LoadBitmap (Imgpath);
} else {
Bitmap BM = LoadBitmap (Imgpath);
int digree = 0;
Exifinterface exif = null;
try {
EXIF = new Exifinterface (Imgpath);
catch (IOException e) {
E.printstacktrace ();
EXIF = null;
}
if (EXIF!= null) {
Reading camera direction information in a picture
int ori = Exif.getattributeint (exifinterface.tag_orientation,
exifinterface.orientation_undefined);
Calculate Rotation angle
Switch (ORI) {
Case EXIFINTERFACE.ORIENTATION_ROTATE_90:
Digree = 90;
Break
Case EXIFINTERFACE.ORIENTATION_ROTATE_180:
Digree = 180;
Break
Case EXIFINTERFACE.ORIENTATION_ROTATE_270:
Digree = 270;
Break
Default
Digree = 0;
Break
}
}
if (digree!= 0) {
Rotate picture
Matrix M = new Matrix ();
M.postrotate (Digree);
BM = BITMAP.CREATEBITMAP (BM, 0, 0, bm.getwidth (),
Bm.getheight (), M, true);
}
return BM;
}
}
......
}