关于javascript:FEB移动端图片上传压缩旋转兼容问题与解决方案

4次阅读

共计 2070 个字符,预计需要花费 6 分钟才能阅读完成。

背景

不同的浏览器对图像 exif 旋转信息的渲染解决不同。例如:从 iPhone 以纵向模式拍摄图像并将图像上传到我的应用程序时,它旋转显示。然而,我查看了我每台设施的 EXIF 元信息图像,发现两个图像在方向属性中具备雷同的值

机型 景象
IOS 13.3.1 版本(旧)
IOS 13.4.1(新)

问题本源

Webkit 浏览器会在您依据 EXIF 数据上传图像之前旋转图像,只有新版 Chrome (81) 和 IOS 13.4.1 Mobile Safari 反对。导致如果应用程序本人再依据 exif 信息去旋转时多转一次渲染就会有问题。

相干 bug 链接 https://bugs.chromium.org/p/c…

解决办法

创立一个宽高 2 ×3 的图片,应用 img 标签渲染,查看是否被旋转,再交由 canvas 手动旋转解决。

相干代码要害局部

// Code adapted from
  // https://github.com/blueimp/JavaScript-Load-Image/blob/24eda0f970b69f681dd76f4ed04e3e041a9bc1fa/js/load-image-orientation.js#L67-L103

  function 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 = testImageURL
  } 

相干修复代码起源
https://github.com/blueimp/Ja…

正文完
 0