压缩图像的最佳方法 Javascript React Web App

Cof*_*ser 8 javascript image reactjs

我正在寻找压缩我收到并需要存储在我的数据库中的图像的最佳解决方案。

实际上,我将图像转换为 base64,然后将其发送到服务器。

handleImage = e => {
    e.preventDefault();
    let reader = new FileReader();
    let file = e.target.files[0];

    reader.onloadend = () => {           
        this.setState({
            file: file,
            image: reader.result
        });
    }

    this.setState({ imgchange: true })
}
Run Code Online (Sandbox Code Playgroud)

然后将当前状态的图像发送到服务器。但是对于低质量的图像,这很好,但是当我尝试上传中等质量的图像时,我无法将其保存在服务器上,我需要一种压缩图像的方法。

你有什么想法来实现这一目标吗?你能给我举个例子吗?

Mah*_*rus 10

可用于图像压缩的最佳 npm 包是browser-image-compression. 在 React 和 Redux 中测试。

  • 安装 npm install browser-image-compression --save

异步等待语法:

import React from "react";
import imageCompression from 'browser-image-compression';
function photoUpload() {
    async function handleImageUpload(event) {

        const imageFile = event.target.files[0];
        console.log('originalFile instanceof Blob', imageFile instanceof Blob); // true
        console.log(`originalFile size ${imageFile.size / 1024 / 1024} MB`);

        const options = {
          maxSizeMB: 1,
          maxWidthOrHeight: 1920,
          useWebWorker: true
        }
        try {
          const compressedFile = await imageCompression(imageFile, options);
          console.log('compressedFile instanceof Blob', compressedFile instanceof Blob); // true
          console.log(`compressedFile size ${compressedFile.size / 1024 / 1024} MB`); // smaller than maxSizeMB

          await uploadToServer(compressedFile); // write your own logic
        } catch (error) {
          console.log(error);
        }

      }
  return (
    <>
     <div>
     <input type="file" accept="image/*" onChange={event => handleImageUpload(event)}/>
     </div>
    </>
  );
}

export default photoUpload;
Run Code Online (Sandbox Code Playgroud)

有关更多详细信息,请查看NPM


els*_*syr 3

我之前已经在 React/Redux 应用程序中使用图像库完成了此操作,最终生成压缩的 JPG 文件 - 如果这对您有用,那么使用Jimp之类的东西是一种选择。它是为节点制作的,但我安装它是为了在浏览器中使用,并像这样使用它:

Jimp.read('image.jpg').then((image) => {
  if (image.bitmap.data.length > MAX_IMAGE_SIZE) {
    image.quality(80); // some value of 'quality'
  }
  // do something else with the image
});
Run Code Online (Sandbox Code Playgroud)

您可以做一些调整来确定 JPG 的正确质量适合您的应用程序,并进行相应的调整。

当我使用这个时,我组合了一个onDrop像你一样处理图像的函数 - 我不能保证这段代码是超级干净或超级高效 - 它来自一次性原型 - 但它应该让你开始正确的道路:

handleFileDrop(e) {
      e.stopPropagation();
      e.preventDefault();

      var file = e.dataTransfer.files[0];

      var reader = new FileReader();
      reader.onload = (function(inputFile) {
        return function(e) {
            var imageBlob = new Blob([e.target.result], {type: inputFile.type});
            var src = URL.createObjectURL(imageBlob)
            Jimp.read(src, (err, image) => {
                // do stuff here
            });
      })(file);

      reader.readAsArrayBuffer(file);
}
Run Code Online (Sandbox Code Playgroud)