Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
414 views
in Technique[技术] by (71.8m points)

javascript - how to compress a base64 image to custom size

I send/receive my image by using base64. I have a base64 string and I want to compress it to my size.

for example I want to reduce photo size to 100kb.

Is it possible?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This was a fun challenge cuz it involved a binary search until it finds the right size. I'm not going to advice you to solve this with base64 instead of blob cuz you should really handle it as binary (blob) otherwise it takes up ~33% more data as base64

This code includes resizing that you can set a max width/hight and still be able to keep the aspect ratio and auto quality lookup until it finds the correct quality to match the 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('
Now with webp
')

    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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...