代码之家  ›  专栏  ›  技术社区  ›  RedBlue

dom对blob进行图像调整大小

  •  0
  • RedBlue  · 技术社区  · 2 年前

    这个使用dom对在使用方法resizeBlob之前创建的blob进行图像处理的vue具有高质量,但图像太大,在传递到方法resizeBlob之后,它使blob质量较低。我一开始没有改变尺寸的原因是,这是制作高质量图像的唯一方法,但它在dom到image中的大图像。

    有没有其他方法可以在不改变质量的情况下调整blob的大小?

    
        async convertToImage() {
          const elm = document.getElementById('sample-id');
       
          let scale = 10;
    
          const styleProp = {
            transform: `scale(${scale})`,
            transformOrigin: 'top left',
            width: elm.clientWidth + 'px',
            height: elm.clientHeight + 'px'
          };
    
          try {
            const dataUrl = await domtoimage.toPng(elm, {
              width: elm.clientWidth * scale,
              height: elm.clientHeight * scale,
              style: styleProp,
            });
    
            const fileOptions = {
              suggestedName: `test.png`,
              types: [
                {
                  description: 'PNG Image',
                  accept: {
                    'image/png': ['.png'],
                  },
                },
              ],
            };
    
            const fileHandle = await window.showSaveFilePicker(fileOptions);
            const writableStream = await fileHandle.createWritable();
            const blob = await fetch(dataUrl).then((response) => response.blob());
            const resizedBlob = await this.resizeBlob(blob, 450, 500);
         //low quality
            await writableStream.write(resizedBlob);
        // high quality but big image
       // await writableStream.write(blob);
            await writableStream.close();
    
          } catch (error) {
           
          }
        },
    
        async resizeBlob(blob, newWidth, newHeight) {
          return new Promise((resolve) => {
            const img = new Image();
            const blobUrl = URL.createObjectURL(blob);
            img.src = blobUrl;
    
            img.onload = () => {
              const canvas = document.createElement('canvas');
              canvas.width = newWidth;
              canvas.height = newHeight;
              const ctx = canvas.getContext('2d');
    
    
              ctx.imageSmoothingEnabled = true;
              ctx.imageSmoothingQuality = 'high';
    
              ctx.drawImage(img, 0, 0, newWidth, newHeight);
    
         
              canvas.toBlob((resizedBlob) => {
                resolve(resizedBlob);
                URL.revokeObjectURL(blobUrl); 
              });
            };
          });
        },
    
    0 回复  |  直到 2 年前
    推荐文章