我想某位大哥也遇到过这个问题,就是手机相册选择图片时,显示是正的(未被旋转角度的),但是上传该图片后,客户端却显示被旋转了xx度的。那这肯定是客户不想出现的问题,同样也是我们开发者不想出现bug。我想遇到问题,解决问题,也不吐槽啥是我们必修的课程。
客户在小米手机上选择相册图片上传后,在客户端头像图片显示被旋转了90度。一开始猜想不出是哪个环节导致的错误,是不是不同手机品牌定制系统导致的问题,于是把原图发到华为手机上。不管在手机自带的相册查看图片,还是app集成TakePhoto SDK查看相册图片,都是正的,但上传后,客户端头像却显示被旋转90度的图片。于是直接查看图片的详细信息,但window只提供一些基本的格式、大小之类的信息。那有没有通过代码直接获取图片角度的,如果是图片角度问题。那获取当前被旋转的角度,再旋转xx度后,校正图片角度,就迎刃而解了。(手机系统直接显示图片角度为0的图片(包括非零),其实原图可能存在角度非零的)
以下是一些比较核心代码:
(1)获取图片角度
/** * 获取图片角度 * */ public int imgDegree(String path) { if (TextUtils.isEmpty(path)) { return 0; } int degree = 0; try { ExifInterface exifInterface = new ExifInterface(path); int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL); 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; } } catch (Exception e) { //相应异常处理 } return degree; }
(2)旋转图片
/** * 旋转图片 * */ public Bitmap rotateImg(final Bitmap bitmap, final int degree) { Matrix matrix = new Matrix(); matrix.postRotate(degree); Bitmap resizeBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true); return resizeBitmap; }
(3)传入原始图片(其实角度!=0)
Bitmap picture = BitmapFactory.decodeFile(imgPath); Bitmap bitmap = rotateImg(picture, 角度); saveBitmap(bitmap, imgPath);
(4)保存Bitmap图片
/** * 保存Bitmap图片 * */ public boolean saveBitmap(final Bitmap bitmap, final String filePath) { if (bitmap == null || filePath == null) { return false; } boolean result = false; //默认结果 File file = new File(filePath); OutputStream outputStream = null; //文件输出流 try { outputStream = new FileOutputStream(file); result = bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream); //将图片压缩为JPEG格式写到文件输出流,100是最大的质量程度 } catch (Exception e) { e.printStackTrace(); } finally { if (outputStream != null) { try { outputStream.close(); //关闭输出流 } catch (IOException e) { e.printStackTrace(); } } } return result; }
上面总结的不是很到位,其实只想记录下~~~