[JS] Generate thumbnails of pictures on the web side, realized by pure js function

Realize image generation thumbnails on the web side, pure js function to achieve
insert image description here

The main function generateThumbnails, a File object is passed in, and the generated thumbnail returns a base64.
Use code

generateThumbnails(file).then(imageThumbnail => {
           console.log(imageThumbnail )
 })

function code

export function generateThumbnails(imageFile) {
  return new Promise((resolve, reject) => {
    createImageBitmap(imageFile).then(imageBitmap => {
      const canvas = document.createElement('canvas')
      canvas.width = imageBitmap.height > 1000 ? (imageBitmap.height / 4) : (imageBitmap.height / 2)
      canvas.height = imageBitmap.width > 1000 ? (imageBitmap.width / 4) : (imageBitmap.width / 2)
      const ctx = canvas.getContext('2d')
      ctx.drawImage(imageBitmap, 0, 0, canvas.width, canvas.height)
      const url = canvas.toDataURL('image/jpeg')
      console.log('缩略图')
      console.log('%c  ', 'background:url(' + url + ') no-repeat ;line-height:' + canvas.height + 'px;font-size:' + canvas.height + 'px')
      if (url.length > 80 * 1024) {
        generateThumbnails(convertBase64UrlToBlob(url)).then(res => {
          resolve(res)
        })
      } else {
        resolve(url)
      }
    }).catch((err) => {
      reject('缩略图生成失败:' + err)
    })
  })
}

/**
 * 将以base64的图片url数据转换为Blob
 * @param base64 用url方式表示的base64图片数据
 */
function convertBase64UrlToBlob(base64) {
  const arr = base64.split(',')
  const mime = arr[0].match(/:(.*?);/)[1]
  const str = atob(arr[1])
  let n = str.length
  const u8arr = new Uint8Array(n)
  while (n--) {
    u8arr[n] = str.charCodeAt(n)
  }
  return new Blob([u8arr], { type: mime })
}

Guess you like

Origin blog.csdn.net/sky529063865/article/details/130261981