图像压缩器未导入nextjs

xurqigkl  于 2023-10-18  发布在  其他
关注(0)|答案(1)|浏览(162)

我试图压缩图像,但当我尝试导入图像压缩正常像这样:

import ImageCompressor from "image-compressor.js";

它给出错误:

Uncaught ReferenceError: window is not defined

这是我的代码:

const handleImage = async (e) => {
                const selectedFile = e.target.files[0];
                if (selectedFile) {
                    try {
                        const compressedDataURL = await compressImage(selectedFile);

                        console.log("Compressed dataURL: ", compressedDataURL);

                        setImage(compressedDataURL);
                    } catch (error) {
                        console.error("Error compressing image:", error);
                    }
                }
            };
            //Compressing images function
            const compressImage = async (file) => {
                return new Promise((resolve, reject) => {
                    new ImageCompressor(file, {
                        quality: 0.5, // Adjust the quality as needed
                        success(result) {
                            const reader = new FileReader();
                            reader.onload = (e) => {
                                const imageData = e.target.result;
                                resolve(`data:image/jpeg;base64,${btoa(imageData)}`);
                            };
                            reader.readAsBinaryString(result);
                        },
                        error(e) {
                            reject(e);
                        },
                    });
                });
            };

我尝试的另一种方法是在压缩函数中导入图像压缩器:

const compressImage = async (file) => {
try {
    // Import the ImageCompressor class from the library
    const { ImageCompressor } = await import("image-compressor.js");

    return new Promise((resolve, reject) => {
        new ImageCompressor(file, {
            quality: 0.5, // Adjust the quality as needed
            success(result) {
                const reader = new FileReader();
                reader.onload = (e) => {
                    const imageData = e.target.result;
                    resolve(`data:image/jpeg;base64,${btoa(imageData)}`);
                };
                reader.readAsBinaryString(result);
            },
            error(e) {
                reject(e);
            },
        });
    });
} catch (error) {
    console.error("Error importing ImageCompressor:", error);
   }
  };

但它只是给出了错误,它不能是一个状态变量

tquggr8v

tquggr8v1#

使用useEffect导入图像压缩器,如下所示:

useEffect(() => {
            // Dynamically load ImageCompressor if needed (e.g., in the browser)
            if (typeof window !== "undefined") {
             import("image-compressor.js").then((module) => {
                 // Store it in the window object for later use
                window.ImageCompressor = module.default || module;
            });
        }
       }, []);

相关问题