FE.B-移动端图片上传压缩旋转兼容问题与解决方案

背景 不同的浏览器对图像exif旋转信息的渲染处理不同。例如:从 iPhone 以纵向模式拍摄图像并将图像上传到我的应用程序时,它旋转显示。但是,我检查了我每台设备的 EXIF 元信息图像,发现两个图像在方向属性中具有相同的值

机型 现象
IOS 13.3.1 版本(旧) FE.B-移动端图片上传压缩旋转兼容问题与解决方案
文章图片
IOS 13.4.1(新) FE.B-移动端图片上传压缩旋转兼容问题与解决方案
文章图片
问题根源 Webkit 浏览器会在您根据 EXIF 数据上传图像之前旋转图像,只有新版 Chrome (81) 和 IOS 13.4.1 Mobile Safari 支持。导致如果应用程序自己再根据exif信息去旋转时多转一次渲染就会有问题。
相关bug链接 https://bugs.chromium.org/p/c...
解决办法 【FE.B-移动端图片上传压缩旋转兼容问题与解决方案】创建一个宽高2x3的图片,使用img标签渲染,检查是否被旋转,再交由canvas手动旋转处理。
相关代码关键部分
// Code adapted from // https://github.com/blueimp/JavaScript-Load-Image/blob/24eda0f970b69f681dd76f4ed04e3e041a9bc1fa/js/load-image-orientation.js#L67-L103function imageOrientationTest($, cb) { // black+white 3x2 JPEG, with the following meta information set: // - EXIF Orientation: 6 (Rotated 90° CCW) // Image data layout (B=black, F=white): // BFF // BBB var testImageURL = 'data:image/jpeg; base64,/9j/4QAiRXhpZgAATU0AKgAAAAgAAQESAAMAAAABAAYAAAA' + 'AAAD/2wCEAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBA' + 'QEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE' + 'BAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAf/AABEIAAIAAwMBEQACEQEDEQH/x' + 'ABRAAEAAAAAAAAAAAAAAAAAAAAKEAEBAQADAQEAAAAAAAAAAAAGBQQDCAkCBwEBAAAAAAA' + 'AAAAAAAAAAAAAABEBAAAAAAAAAAAAAAAAAAAAAP/aAAwDAQACEQMRAD8AG8T9NfSMEVMhQ' + 'voP3fFiRZ+MTHDifa/95OFSZU5OzRzxkyejv8ciEfhSceSXGjS8eSdLnZc2HDm4M3BxcXw' + 'H/9k=' var img = document.createElement('img') img.onload = function () { // Check if the browser supports automatic image orientation: $.orientation = img.width === 2 && img.height === 3 if ($.orientation) { var canvas = document.createElement('canvas') canvas.width = canvas.height = 1 var ctx = canvas.getContext('2d') ctx.drawImage(img, 1, 1, 1, 1, 0, 0, 1, 1) // Check if the source image coordinates (sX, sY, sWidth, sHeight) are // correctly applied to the auto-orientated image, which should result // in a white opaque pixel (e.g. in Safari). // Browsers that show a transparent pixel (e.g. Chromium) fail to crop // auto-oriented images correctly and require a workaround, e.g. // drawing the complete source image to an intermediate canvas first. // See https://bugs.chromium.org/p/chromium/issues/detail?id=1074354 $.orientationCropBug = ctx.getImageData(0, 0, 1, 1).data.toString() !== '255,255,255,255' } if (cb) cb($, img, canvas) } img.src = https://www.it610.com/article/testImageURL }

相关修复代码来源
https://github.com/blueimp/Ja...

    推荐阅读