rni-l
3/30/2018 - 3:07 AM

handle image transform question

hanlde image transform question

// 依赖 exifjs
import exif from 'exif-js'

// 解决图片旋转问题
function cacheImg(url) {
  const img = new Image()
  img.src = url
  img.crossOrigin = 'Anonymous'
  return new Promise((resolve) => {
    img.onload = () => {
      resolve(img)
    }
  }).catch(err => {
    console.log('image error:', err)
  })
}

function getImageExifData(image) {
  return new Promise((resolve) => {
    // 获取图片的元数据
    exif.getData(image, function() {
      resolve(exif.getAllTags(this))
    })
  })
}

// 计算图片的宽高
function computeWidthAndHeight({ img_drawWidth, img_drawHeight, Orientation }) {
  let drawWidth = img_drawWidth
  let drawHeight = img_drawHeight
  let degree = 0
  // let maxSide = Math.max(drawWidth, drawHeight)

  // 使用离屏canvas修正图片的方向
  const canvas = document.createElement('canvas')
  const width = drawWidth
  const height = drawHeight
  canvas.width = width
  canvas.height = height

  const context = canvas.getContext('2d')
  // 判断图片方向,重置canvas大小,确定旋转角度,iphone默认的是home键在右方的横屏拍摄方式
  switch (Orientation) {
  // iphone横屏拍摄,此时home键在左侧
  case 3:
    degree = 180
    drawWidth = -width
    drawHeight = -height
    break
    // iphone竖屏拍摄,此时home键在下方(正常拿手机的方向)
  case 6:
    canvas.width = height
    canvas.height = width
    degree = 90
    drawWidth = width
    drawHeight = -height
    break
    // iphone竖屏拍摄,此时home键在上方
  case 8:
    canvas.width = height
    canvas.height = width
    degree = 270
    drawWidth = -width
    drawHeight = height
    break
  }
  return { degree, drawWidth, drawHeight, context, canvas }
}

// 获取处理好的图片数据
async function getImgData({ image, exifData }) {
  // 以下改变一下图片大小
  // 获取宽高中,最大的值
  const { degree, drawHeight, drawWidth, context, canvas } = computeWidthAndHeight({
    img_drawWidth: exifData.PixelXDimension || image.naturalWidth,
    img_drawHeight: exifData.PixelYDimension || image.naturalHeight,
    Orientation: exifData.Orientation
  })
  // 使用canvas旋转校正
  context.rotate(degree * Math.PI / 180)
  // 渲染新的图片
  context.drawImage(image, 0, 0, drawWidth, drawHeight)
  // 返回新的 base64
  return canvas.toDataURL('image/jpge', 0.7)
}

function handleImageTransformQuestion(imgUrl) {
  return new Promise(async(resolve) => {
    const image = await cacheImg(imgUrl)
    const exifData = await getImageExifData(image)
    console.log('exifdata:', exifData)
    const base64 = await getImgData({
      exifData,
      image
    })
    resolve(base64)
  })
}

export default handleImageTransformQuestion

// how to use
// const base64 = await handleImageTransformQuestion(imgUrl)
// // or
// handleImageTransformQuestion(imgUrl).then(base64 => {
//   // ...
// })