【问题标题】:how to compress a base64 image to custom size如何将base64图像压缩为自定义大小
【发布时间】:2021-11-24 12:00:02
【问题描述】:

我使用 base64 发送/接收我的图像。 我有一个 base64 字符串,我想将它压缩到我的大小。

例如,我想将照片大小减小到 100kb。

有可能吗?

【问题讨论】:

标签: javascript react-native base64


【解决方案1】:

这是一个有趣的挑战,因为它涉及到二进制搜索,直到找到合适的大小。我不会建议你用 base64 而不是 blob 来解决这个问题,因为你应该将它作为二进制 (blob) 处理,否则它会占用大约 33% 的 base64 数据

此代码包括调整大小,您可以设置最大宽度/高度,并且仍然能够保持纵横比和自动质量查找,直到找到与 MAX_SIZE 匹配的正确质量

console.log('Downloading lorem ipsum image to simulate a file from user input')

fetch('https://picsum.photos/1920/1080/?random')
.then(res => res.blob())
.then(blob => {
  const img = new Image()
  img.src = URL.createObjectURL(blob)

  console.log(`Original image size (at 1920x1080) is: ${blob.size} bytes`)
  console.log('URL to original image:', img.src)
  
  img.onload = () => resize(img, 'jpeg').then(blob => {
    console.log('Final blob size', blob.size)
    console.log('Final blob url:', URL.createObjectURL(blob))

    console.log('\nNow with webp\n')

    resize(img, 'webp').then(blob => {
      console.log('Final blob size', blob.size)
      console.log('Final blob url:', URL.createObjectURL(blob))
    })
  })
}) 


const MAX_WIDTH = 1280
const MAX_HEIGHT = 720
const MAX_SIZE = 100000 // 100kb

async function resize(img, type = 'jpeg') {
  const canvas = document.createElement('canvas')
  const ctx = canvas.getContext('2d')
  
  ctx.drawImage(img, 0, 0)
  
  let width = img.width
  let height = img.height
  let start = 0
  let end = 1
  let last, accepted, blob
  
  // keep portration
  if (width > height) {
    if (width > MAX_WIDTH) {
      height *= MAX_WIDTH / width
      width = MAX_WIDTH
    }
  } else {
    if (height > MAX_HEIGHT) {
      width *= MAX_HEIGHT / height
      height = MAX_HEIGHT
    }
  }
  canvas.width = width
  canvas.height = height
  console.log('Scaling image down to max 1280x720 while keeping aspect ratio')
  ctx.drawImage(img, 0, 0, width, height)
  
  accepted = blob = await new Promise(rs => canvas.toBlob(rs, 'image/'+type, 1))
  
  if (blob.size < MAX_SIZE) {
    console.log('No quality change needed')
    return blob
  } else {
    console.log(`Image size after scaling ${blob.size} bytes`)
    console.log('Image sample after resizeing with losseless compression:', URL.createObjectURL(blob))
  }
  
  // Binary search for the right size
  while (true) {
    const mid = Math.round( ((start + end) / 2) * 100 ) / 100
    if (mid === last) break
    last = mid
    blob = await new Promise(rs => canvas.toBlob(rs, 'image/'+type, mid))
        console.log(`Quality set to ${mid} gave a Blob size of ${blob.size} bytes`)
    if (blob.size > MAX_SIZE) { end = mid }
    if (blob.size < MAX_SIZE) { start = mid; accepted = blob }
  }

  return accepted
}

PS/警告 如果您在画布元素上绘制 jpg 图片并在没有调整大小、操作质量损失或更改格式的情况下恢复图像,则画布不会进行任何良好的压缩@987654327 @ 那么你肯定会得到一个更大的文件,因为它们可能已经被很好地压缩并且画布没有剂量。我只更改质量和最大宽度/高度以使用画布 api 减小大小。您将需要一些压缩器来进一步减少它而不会造成质量损失。

【讨论】:

  • ps,如果你改成image/webp,你会得到更低的质量损失
  • 感谢您的精彩回答。如果您能够附上一个工作示例,那就太好了!
  • 在while循环中没有生成blob。它是空的
  • 很快就完成了!正是我试图弄清楚几个星期。顺便说一句,我只是忽略了“webp”部分,它给了我 170Kb 而不是 900 的大小!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-29
  • 2013-09-03
  • 2015-05-09
  • 2016-10-24
  • 1970-01-01
相关资源
最近更新 更多