关于h5上传图片旋转问题

文本格式调整不过来,代码格式请看

关于h5上传图片适配旋转问题 - 简书

```

image.onload = function() {

        // 获取图片旋转角度

        var orientation = 1

        EXIF.getData(image, function() {

          orientation = EXIF.getTag(this, 'Orientation')

        })

        // alert('orientation-' + orientation)

        var width = image.width

        var height = image.height

        var scale = Math.max(width / options.maxWidth, height / options.maxHeight)

        //宽度或高度计算

        // if (scale > 1) {

        var w = Math.round(width / scale)

        var h = Math.round(height / scale)

        //生成canvas

        var canvas = document.createElement('canvas')

        var ctx = (window.ctx = canvas.getContext('2d'))

        ctx.save()

        switch (orientation) {

          case 3: //镜头方向朝右 需要顺时针(向左)180度旋转

            console.log('需要顺时针(向左)180度旋转')

            canvas.width = h

            canvas.height = w

            ctx.translate(canvas.width / 2, canvas.height / 2)

            ctx.rotate((180 * Math.PI) / 180)

            ctx.drawImage(this, -w / 2, -h / 2, w, h)

            break

          case 6: //镜头正拍  需要顺时针(向右)90度旋转

            console.log('需要顺时针(向左)90度旋转')

            canvas.width = h

            canvas.height = w

            ctx.translate(canvas.width / 2, canvas.height / 2)

            ctx.rotate((90 * Math.PI) / 180)

            ctx.drawImage(this, -w / 2, -h / 2, w, h)

            break

          case 8: //镜头朝下  需要逆时针(向左)90度旋转"

            console.log('需要逆时针(向右)90度旋转')

            canvas.width = h

            canvas.height = w

            ctx.translate(canvas.width / 2, canvas.height / 2)

            ctx.rotate((-90 * Math.PI) / 180)

            ctx.drawImage(this, -w / 2, -h / 2, w, h)

            break

          default:

            //有的机型无论是什么方向统一返回 0 1  //镜头方向朝左

            canvas.width = w

            canvas.height = h

            ctx.drawImage(this, 0, 0, w, h)

            break

        }

        ctx.restore()

        imageData = canvas.toDataURL('image/jpeg', 0.8)

        // }

        callback && callback(imageData, 0)

      }

```

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。