上传前图像文件压缩

时间:2019-02-22 14:46:08

标签: javascript typescript filereader

以下方法被用作另一个变量的参数。但是这里的问题是压缩后它没有返回文件。

async CompressImage(imageFile: File): Promise<File> {
    return new Promise<File>((resolve, reject) => {
        const cReader = new FileReader();
        const image = new Image();
        cReader.onload = () => {
            image.src = cReader.result.toString();
            image.onload = () => {
                const canvas = document.createElement("canvas");
                const context = canvas.getContext("2d");
                context.drawImage(image, 0, 0);

                //width & height initialization

                canvas.width = width;
                canvas.height = height;
                var ctx = canvas.getContext("2d");
                ctx.drawImage(image, 0, 0, width, height);

                const convertedFile = canvas.toBlob((blob) => {
                    const scaledDown = new File([blob], imageFile.name);
                });

                resolve(convertedFile);
            }
        };

        cReader.readAsDataURL(mediaFile);
    });
}

0 个答案:

没有答案