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

jvidinwx  于 2022-12-10  发布在  Java
关注(0)|答案(4)|浏览(291)

我正在寻找最好的解决方案来压缩图像,我收到,并需要存储在我的数据库中。
实际上,我将图像转换为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 })
}

然后将当前图像发送到服务器。但对于低质量的图像,这是好的,但当我试图上传一个中高质量的图像时,我不能将其保存在服务器上,我需要一个方法来压缩图像。
你有什么办法实现这一点吗?你能给我举个例子吗?

esbemjvw

esbemjvw1#

最好的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;

欲了解更多详情,请访问NPM

pinkon5k

pinkon5k2#

我以前在React/Redux应用中使用图像库做过这件事,最终生成一个压缩的JPG文件--如果这对你有用的话,那么使用类似Jimp的东西是一个选择。它是为节点设计的,但我安装它是为了在browser中使用,并这样使用它:

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
});

你可以做一些调整,以找出什么样的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);
}
c3frrgcw

c3frrgcw3#

您可以使用react-image-file-resizer库来压缩图像,

import Resizer from 'react-image-file-resizer';

Resizer.imageFileResizer(
    file, //is the file of the new image that can now be uploaded...
    maxWidth, // is the maxWidth of the  new image
    maxHeight, // is the maxHeight of the  new image
    compressFormat, // is the compressFormat of the  new image
    quality, // is the quality of the  new image
    rotation, // is the rotatoion of the  new image
    responseUriFunc,  // is the callBack function of the new image URI
    outputType  // is the output type of the new image
    );

例如:

import React, { Component } from 'react';
import Resizer from 'react-image-file-resizer';

class App extends Component {
    constructor(props) {
        super(props);
        this.fileChangedHandler = this.fileChangedHandler.bind(this);
    }

    fileChangedHandler(event) {
        var fileInput = false
        if(event.target.files[0]) {
            fileInput = true
        }
        if(fileInput) {
            Resizer.imageFileResizer(
                event.target.files[0],
                300,
                300,
                'JPEG',
                100,
                0,
                uri => {
                    console.log(uri)
                },
                'base64'
            );
        }
    }

    render() {
        return (
            <div className="App">
                <input type="file" onChange={this.fileChangedHandler}/>
            </div>
        );
    }
}

export default App;

For Details you can read this documentation

uqzxnwby

uqzxnwby4#

import React from "react";
import imageCompression from "browser-image-compression";

  function imageOrientation(image) {
    var img = new Image();
    img.src = image;
    return { width: img.naturalWidth, height: img.naturalHeight };
  }

  const imageCompressionFile = async (image) => {
    const options = {
      maxSizeMB: 5,
      maxWidthOrHeight: 1080,
      useWebWorker: true,
    };

    let { width, height } = imageOrientation(URL.createObjectURL(image));
    let compress_file;

    if (width > height) {
      if (width > 400) {
        // landscape
        let compressedFile = await imageCompression(image, options);
        compress_file = await compressedFile;
      } else {
        // No landscape
        compress_file = await image;
      }
    } else if (width < height) {
      // portrait
      if (height > 400) {
        let compressedFile = await imageCompression(image, options);
        compress_file = await compressedFile;
      } else {
        // No portrait
        compress_file = await image;
      }
    } else {
      const compressedFile = await imageCompression(image, options);
      compress_file = await compressedFile;
    }
    return await compress_file;
  };

function APP() {
  async function handleImageUpload(event) {
    const image = event.target.files[0];
            let fileData = await imageCompressionFile(image);
  }

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

export default APP;

相关问题