1. <tfoot id='DiMss'></tfoot>
      <legend id='DiMss'><style id='DiMss'><dir id='DiMss'><q id='DiMss'></q></dir></style></legend>
      <i id='DiMss'><tr id='DiMss'><dt id='DiMss'><q id='DiMss'><span id='DiMss'><b id='DiMss'><form id='DiMss'><ins id='DiMss'></ins><ul id='DiMss'></ul><sub id='DiMss'></sub></form><legend id='DiMss'></legend><bdo id='DiMss'><pre id='DiMss'><center id='DiMss'></center></pre></bdo></b><th id='DiMss'></th></span></q></dt></tr></i><div id='DiMss'><tfoot id='DiMss'></tfoot><dl id='DiMss'><fieldset id='DiMss'></fieldset></dl></div>

      <small id='DiMss'></small><noframes id='DiMss'>

      • <bdo id='DiMss'></bdo><ul id='DiMss'></ul>

      如何将base64图像压缩为自定义大小

      how to compress a base64 image to custom size(如何将base64图像压缩为自定义大小)

      <small id='0CKS0'></small><noframes id='0CKS0'>

        <bdo id='0CKS0'></bdo><ul id='0CKS0'></ul>
          <legend id='0CKS0'><style id='0CKS0'><dir id='0CKS0'><q id='0CKS0'></q></dir></style></legend>

              <tbody id='0CKS0'></tbody>

              <tfoot id='0CKS0'></tfoot>
            • <i id='0CKS0'><tr id='0CKS0'><dt id='0CKS0'><q id='0CKS0'><span id='0CKS0'><b id='0CKS0'><form id='0CKS0'><ins id='0CKS0'></ins><ul id='0CKS0'></ul><sub id='0CKS0'></sub></form><legend id='0CKS0'></legend><bdo id='0CKS0'><pre id='0CKS0'><center id='0CKS0'></center></pre></bdo></b><th id='0CKS0'></th></span></q></dt></tr></i><div id='0CKS0'><tfoot id='0CKS0'></tfoot><dl id='0CKS0'><fieldset id='0CKS0'></fieldset></dl></div>
                本文介绍了如何将base64图像压缩为自定义大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

                问题描述

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

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

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

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

                有可能吗?

                推荐答案

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

                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

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

                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
                }

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

                PS/warning Canvas don't do any good compression, if you paint a jpg picture on a canvas element and get the image back with no resizing, manipulation quality loss or changing the format toBlob('image/jpg', cb, 1) then you will most definitely get a larger file back since they probably already are well compressed and canvas dose none. I only change the quality & max width/height to reduce the size with the canvas api. You would need some compressor to reduce it even more without quality loss.

                • jsfiddle 用画布增加文件的演示
                • imageoptim
                • squoosh.app
                • zopfli
                • pngcrush

                这篇关于如何将base64图像压缩为自定义大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

                本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

                相关文档推荐

                Fetch multiple links inside foreach loop(在 foreach 循环中获取多个链接)
                Backbone Fetch Request is OPTIONS method(Backbone Fetch Request 是 OPTIONS 方法)
                Fetch API leaks memory in Chrome(Fetch API 在 Chrome 中泄漏内存)
                How can I download and save a file using the Fetch API? (Node.js)(如何使用 Fetch API 下载和保存文件?(Node.js))
                Send blob data to node using fetch, multer, express(使用 fetch、multer、express 将 blob 数据发送到节点)
                Sending a custom User-Agent string along with my headers (fetch)(发送自定义用户代理字符串以及我的标头(获取))

                  <small id='w5hzV'></small><noframes id='w5hzV'>

                  <i id='w5hzV'><tr id='w5hzV'><dt id='w5hzV'><q id='w5hzV'><span id='w5hzV'><b id='w5hzV'><form id='w5hzV'><ins id='w5hzV'></ins><ul id='w5hzV'></ul><sub id='w5hzV'></sub></form><legend id='w5hzV'></legend><bdo id='w5hzV'><pre id='w5hzV'><center id='w5hzV'></center></pre></bdo></b><th id='w5hzV'></th></span></q></dt></tr></i><div id='w5hzV'><tfoot id='w5hzV'></tfoot><dl id='w5hzV'><fieldset id='w5hzV'></fieldset></dl></div>
                    • <bdo id='w5hzV'></bdo><ul id='w5hzV'></ul>
                      <legend id='w5hzV'><style id='w5hzV'><dir id='w5hzV'><q id='w5hzV'></q></dir></style></legend>
                      <tfoot id='w5hzV'></tfoot>

                          <tbody id='w5hzV'></tbody>