Tag: Picture is rotated to the same direction
One of the things that must be considered when using camera images in Android apps is the orientation of the image, which can be better displayed only by judging the direction of the image. This article will introduce a way to judge the orientation of a picture by Exifinterface!
On the code:
/** * * Use the picture under the given path to set ImageView * * @param imgpath phone picture file path * @param imgview need to set ImageView */public void Setimg (String IMGP Ath, ImageView imgview) {File File = new file (Imgpath), if (File.exists () && file.canread ()) {//-------1. Picture Zoom----- ---//mobile screen information displaymetrics metric = new Displaymetrics (); Getwindowmanager (). Getdefaultdisplay (). Getmetrics (Metric); int DW = Metric.widthpixels; Screen width int dh = metric.heightpixels; Screen high//load image, just to get the size bitmapfactory.options Options = new Bitmapfactory.options (); options.injustdecodebounds = true; After setting, you can obtain the dimension information bitmap bitmap = Bitmapfactory.decodefile (Imgpath, options);//calculate horizontal and vertical scaling factor int heightratio = (int) Math.ceil (Options.outheight/(float) DH); int widthRatio = (int) Math.ceil (Options.outwidth/(float) DW);//Determine which big if (Heig Htratio > 1 && widthRatio > 1) {if (HeightRatio > WidthRatio) {options.insamplesize = HeightRatio;} else {options.insamplesize = WidthRatio;}} Picture scaling options.injustdecodebounds = False;bitmap = Bitmapfactory.dEcodefile (Imgpath, options);//-------2. Judge the image toward--------try {exifinterface exif = new Exifinterface (imgpath); int degree = 0; Picture rotation angle if (exif! = null) {int orientation = Exif.getattributeint (exifinterface.tag_orientation,-1); if (orientation! =- 1) {switch (orientation) {Case ExifInterface.ORIENTATION_ROTATE_90:degree = 90;break;case Exifinterface.orientation_ Rotate_180:degree = 180;break;case ExifInterface.ORIENTATION_ROTATE_270:degree = 270;break;default:break;}}} if (degree! = 0) {//Picture needs to be rotated int width = bitmap.getwidth (); int height = bitmap.getheight (); Matrix matrix = new Matrix (); matrix.prerotate (degree); Bitmap Mrotatebitmap = Bitmap.createbitmap (Bitmap, 0, 0,width, height, matrix, true); Imgview.setimagebitmap ( MROTATEBITMAP);} else {imgview.setimagebitmap (bitmap);}} catch (IOException e) {}}}
This code contains two main functions:
1. Image scaling: The original picture is generally larger, after shrinking to use;
2. Picture rotation: The resulting photo may need to be rotated due to the different angle of the phone when the user takes photos.
Android to determine camera image orientation