Android上传图片到Firebase后部分图片出现-90度旋转问题咨询
问题原因
三星手机拍摄的照片会将拍摄角度参数存储在EXIF信息中,你当前使用的MediaStore.Images.Media.getBitmap方法仅会读取图片的原始像素数据,不会自动适配EXIF中的旋转参数。你在压缩导出JPEG时没有保留原文件的EXIF信息,导致上传到Firebase的图片丢失了旋转标记,加载时就会显示为原始的未旋转状态,也就是你看到的-90度旋转异常。
仅当你横屏拍摄时,照片的EXIF旋转参数为0,因此不会出现显示异常,这就是仅部分图片存在旋转问题的原因。
解决方案
方案1:上传前修正旋转(推荐,一劳永逸)
在压缩图片前先读取原图片的EXIF旋转角度,将Bitmap调整为正确角度后再压缩上传,后续任意场景加载都不会出现旋转问题。
你可以新增两个工具方法处理旋转:
// 获取图片的EXIF旋转角度 private int getImageRotationAngle(Uri imageUri) throws IOException { ExifInterface exif = new ExifInterface(getContentResolver().openInputStream(imageUri)); int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL); switch (orientation) { case ExifInterface.ORIENTATION_ROTATE_90: return 90; case ExifInterface.ORIENTATION_ROTATE_180: return 180; case ExifInterface.ORIENTATION_ROTATE_270: return 270; default: return 0; } } // 旋转Bitmap到指定角度 private Bitmap rotateBitmap(Bitmap originBitmap, int angle) { if (angle == 0) return originBitmap; Matrix matrix = new Matrix(); matrix.postRotate(angle); return Bitmap.createBitmap(originBitmap, 0, 0, originBitmap.getWidth(), originBitmap.getHeight(), matrix, true); }
修改你原有的压缩逻辑,新增旋转处理步骤:
//Compress Images Bitmap bmp = null; try { bmp = MediaStore.Images.Media.getBitmap(getContentResolver(), IndividualImage); // 新增:修正图片旋转角度 int rotationAngle = getImageRotationAngle(IndividualImage); bmp = rotateBitmap(bmp, rotationAngle); } catch (IOException e) { e.printStackTrace(); } ByteArrayOutputStream baos = new ByteArrayOutputStream(); assert bmp != null; bmp.compress(Bitmap.CompressFormat.JPEG, 25, baos); byte[] data = baos.toByteArray(); //End of compressing
方案2:加载图片时修正旋转
如果你不需要修改上传逻辑,也可以在加载阶段处理旋转:
- 如果你使用Glide、Picasso等通用图片加载框架,框架默认会自动识别EXIF旋转参数并调整显示角度,直接传入Firebase的图片url加载即可,无需额外配置。
- 如果你是自行解码Bitmap加载,可复用方案1中的EXIF角度读取和Bitmap旋转逻辑,在显示前调整为正确角度即可。
内容的提问来源于stack exchange,提问作者MiniDev99
相关产品推荐
相关产品推荐

