从相册中选择图片发现图片旋转了 有的选择90° 有的旋转270° 旋转度数不定。
之前在相机拍照是也有遇到过拍摄的图片与预览的相比旋转了90°,
不过相机那个旋转度数的固定的,当时只是将每张拍摄所得的图片都旋转90° 解决了问题,
然而这个问题旋转度数不定,该如何解决呢?
其实也很简单
1:判断旋转度数
//获取图片的旋转度数 public static int getExifOrientation(String filepath) { int degree = 0; ExifInterface exif = null; try { exif = new ExifInterface(filepath); } catch (IOException ex) { Log.e(TAG, "cannot read exif", ex); } 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; } } } return degree; }
2:旋转回正常图片。
public static Bitmap rotate(Bitmap b, int degrees) { Bitmap b2 = null; if (degrees != 0 && b != null) { Matrix m = new Matrix(); m.postRotate(degrees); try { b2 = Bitmap.createBitmap(b, 0, 0, b.getWidth(), b.getHeight(), m, true); } catch (Exception ex) { b2 = b; Log.i(TAG,"图片选择错误"+ex.getMessage()); } } return b2; }3:因为图片的处理比较耗时 所以在工作线程中执行 防止造成卡顿现象
public void handleImage(String outpath,String temppath,String localpath,CallBack callback){ Thread thread = new Thread(new Runnable() { @Override public void run() { try{ int orientation = BitmapUtil.readPictureDegree(localpath); Log.i(TAG,"图片选择角度:" + orientation); if(orientation!=0){ BitmapUtil.compressAndGenImage(localpath, temppath,400,false);//压缩 Bitmap bitmap = BitmapUtil.rotate(BitmapUtil.getBitmap(temppath),orientation);//旋转 BitmapUtil.storeImage(bitmap,outpath);//存储 }else{ BitmapUtil.compressAndGenImage(localpath, outpath,400,false);//压缩 } callback.call(outpath);//将得到的路径回调 }catch (Exception e){ Log.i(TAG,e.getMessage()); } } }); thread.start(); }
4:注意我这里是先进行质量压缩 在进行旋转操作 但是在判断旋转角度的时候 一定要使用相册中选择的地址(localpath),如果使用 我们压缩后的存储地址(outpath)我们得到的旋转角度将会一直的0.