如何判断图片横竖屏方向?相机/图库图片适配问题问询
嘿,我太懂你这种抓耳挠腮的感觉了——明明是个看似基础的需求,偏偏在图库选图的方向判断上卡壳!我之前做项目时也碰过一模一样的问题,给你整理几个亲测有效的解决思路:
统一判断图片横竖屏的靠谱方案
1. 优先拿图片实际绘制宽高,别死磕Exif的Orientation值
相机返回的Orientation值(6对应竖屏、1对应横屏)看似规律,但图库选的图片大概率会翻车——比如有些图片被压缩工具改过Exif信息,或者图库APP保存时直接旋转了图片却没更新Exif,导致Orientation和实际方向不符。
最稳妥的办法是直接获取图片加载后的真实宽高,再做判断:
- Android端:可以用
BitmapFactory.Options先读取宽高(不用把整张图加载进内存,避免OOM):BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; // 只解码尺寸,不加载像素 BitmapFactory.decodeFile(imageFilePath, options); int actualWidth = options.outWidth; int actualHeight = options.outHeight; // 核心判断:宽大于高就是横屏,反之竖屏 boolean isLandscape = actualWidth > actualHeight; - iOS端:
UIImage会自动根据Exif信息修正尺寸,直接拿size属性比较就行:if let targetImage = UIImage(contentsOfFile: imageFilePath) { let isLandscape = targetImage.size.width > targetImage.size.height }
2. 非要用Exif的话,得统一处理所有Orientation取值
如果业务必须依赖Exif的Orientation值,得先明确所有可能取值对应的实际方向,再写统一的判断逻辑(Android和iOS的Exif取值规则基本一致):
常见Orientation值对应方向:
- 1:正常状态(横屏,宽>高)
- 6:顺时针旋转90°(实际为竖屏,旋转后原高度变宽度)
- 3:旋转180°(横屏)
- 8:逆时针旋转90°(竖屏)
举个Android的实现例子:
ExifInterface exif = new ExifInterface(imageFilePath); int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL); boolean isLandscape; switch(orientation) { case ExifInterface.ORIENTATION_ROTATE_90: // 对应值6 case ExifInterface.ORIENTATION_ROTATE_270: // 对应值8 isLandscape = false; // 竖屏 break; default: isLandscape = true; // 横屏 }
3. 处理图库选图的Uri特殊情况
如果图库返回的是Content Uri而非直接文件路径,别慌,直接通过Uri查询宽高就行:
- Android端用
ContentResolver查询媒体库:Cursor cursor = getContentResolver().query( imageUri, new String[]{MediaStore.Images.Media.WIDTH, MediaStore.Images.Media.HEIGHT}, null, null, null ); if (cursor != null && cursor.moveToFirst()) { int imgWidth = cursor.getInt(cursor.getColumnIndex(MediaStore.Images.Media.WIDTH)); int imgHeight = cursor.getInt(cursor.getColumnIndex(MediaStore.Images.Media.HEIGHT)); boolean isLandscape = imgWidth > imgHeight; cursor.close(); }
内容的提问来源于stack exchange,提问作者Narendra Jadon




