网页前端/node端实现图片旋转功能

网页前端方式

// 图片旋转
rotateImg(url, degree) {
  return new Promise((resolve, reject) => {
    const suffix = url.match(/[^\.]+$/)[0]
    const name = url.replace(/(.*\/)*([^.]+).*/ig, '$2').replace(/-\S+/, '')
    const fileName = `${name}.${suffix}`
    const img = new Image()
    img.src = url // 网络路径
    // img.src = await this.getFileData(file) // 本地上传File对象
    img.onload = () => {
      let cvs = document.createElement('canvas')
      cvs.width = img.height
      cvs.height = img.width
      let ctx = cvs.getContext('2d')
      if (degree == 90) {
        ctx.rotate(Math.PI / 180 * 90)
        ctx.drawImage(img, 0, 0, img.width, img.height, 0, -img.height, img.width, img.height)
      } else if (degree == -90) {
        ctx.rotate(Math.PI / 180 * -90)
        ctx.drawImage(img, 0, 0, img.width, img.height, -img.width, 0, img.width, img.height)
      } else {}
      const imgBase64 = cvs.toDataURL()
      const file = this.dataURLtoFile(imgBase64.replace(/-/g, '+').replace(/_/g, '/').replace(/^data:image\/(png|jpeg|jpg);base64,/, ''), fileName, 'image/png')
      resolve(file)
    }
  })
},
// 将图片base64对象转File对象
dataURLtoFile(base64, fileName, type = 'image/png') {
  let bstr = window.atob(base64)
  let n = bstr.length
  let u8arr = new Uint8Array(n)
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n)
  }
  return new File([u8arr], fileName, { type })
},
// 读取File对象内容
getFileData(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = e => {
      resolve(e.target.result)
    }
  })
}

补充

// 将网络图片地址转换为File对象
async imageUrlToFile(url, fileName) {
  const response = await axios.get(url, { responseType: 'arraybuffer' })
  const imageData = response.data
  const blob = new Blob([imageData], {
    type: response.headers['content-type']
  })
  return new File([blob], fileName, { type: blob.type })
}

 

node端方式

npm install sharp
const sharp = require('sharp');

// 旋转图像并保存
sharp('path/to/input/image.jpg')
  .rotate(90)
  .toFile('path/to/output/image.jpg', (err, info) => {
    if (err) {
      console.error(err);
    } else {
      console.log('图像旋转并保存成功');
    }
  });

其他工具包:jimp

posted @ 2024-11-18 16:34  _senjer  阅读(108)  评论(0)    收藏  举报