next.js 如何在使用react-dropzone时压缩图像

8hhllhi2  于 12个月前  发布在  React
关注(0)|答案(1)|浏览(80)

我在我的Next.js应用程序中使用react dropzone包。我想自动实现图像压缩。
首先,在我得到图像后,我将blob/预览转换为文件阅读器。然后我使用compressorjs包。但在我这样做后,图像没有得到压缩?
如何压缩图像/图像在React时,图像是从dropzone传递?

const [files, setFiles] = useState([]);
onDrop: (acceptedFiles) => {

const newFiles = acceptedFiles.map((file, index) => {
        return Object.assign(file, {
          preview: URL.createObjectURL(file),
        });
      });

if (files.length < 9) {
        setFiles((prev) => [...prev, ...newFiles]);

        files.map((file) => {
          newFiles.forEach((newFile) => {
            if (newFile.name == file.name) {
              alert(newFile.name + " is a duplicate file");

              setFiles(
                files,
                files.filter((val) => val !== newFile)
              );
            }
          });
        });
      } else if (acceptedFiles.length >= 9) {
        alert("select maximum of 9 images");
      } else {
        alert("maximum images to be selected is 9");
      }
    },
  });

const removeFile = (file) => () => {
    const newFiles = [...files];
    newFiles.splice(newFiles.indexOf(file), 1);
    setFiles(newFiles);
    if (files.length == 1) {
      setText("Drag and Drop or click here to upload Images");
    }
  };
  useEffect(() => {
    // Make sure to revoke the data uris to avoid memory leaks, will run on unmount
    return () => files.forEach((file) => URL.revokeObjectURL(file.preview));
  }, []);

字符串
我使用的compressorjs代码是

acceptedFiles.map((file, index) => {
        const reader = new FileReader();

        reader.onload = function (e) {
new Compressor(e.target.result, {
    quality: 0.8,
    success: (compressedFile) => {
      setFiles((prev) => [
        ...prev,
        compressedFile
      ]);
    },
  });
          
        };
        reader.readAsDataURL(file);
        return file;
      });


请在这方面作出贡献。

7rfyedvj

7rfyedvj1#

有一些软件包可用于此。我将给予一个例子,使用browser-image-compression包。
使用以下代码创建一个helper函数:

// image compression

import imageCompression from 'browser-image-compression';

export const compressImages = async (images, options) => {
    const compressedImages = [];

    for (const image of images) {
        if (image.type.startsWith('image/')) {
            try {
                console.log(
                    `compressedFile size before->>>  ${
                        image.size / 1024 / 1024
                    } MB`,
                    image.size,
                ); // smaller than maxSizeMB

                const compressedFile = await imageCompression(image, options);

                console.log(
                    `compressedFile size after ->>> ${
                        compressedFile.size / 1024 / 1024
                    } MB`,
                ); // smaller than maxSizeMB

                compressedImages.push(compressedFile);
            } catch (error) {
                console.log(error);
                // Handle the error as needed
            }
        } else {
            compressedImages.push(image);
        }
    }

    return compressedImages;
};

字符串
让我们修改onDrop方法:

onDrop: async (acceptedFiles) => {

   //kindly check the library and change your settings from here
   const options = {
      maxSizeMB: 0.5,
      maxWidthOrHeight: 800,
      useWebWorker: true,
   };

   const newFiles = acceptedFiles.map((file, index) => {
      return Object.assign(file, {
         preview: URL.createObjectURL(file),
      });
   });

   const newCompressedImages = await compressImages(newFiles, options);

   //now do your task with the compressed image saved in newCompressedImages
};

相关问题