我有一个react应用程序,我想在客户端压缩映像(base64),然后将它们发送到服务器。它适用于以下代码,但在iPhone中它不起作用。 我尝试使用image.onload但它仍然无法正常工作
let compressedImages = [];
for (let i = 0; i < images.length; i++) {
let sourceImage = document.createElement('img');
let result_image = document.createElement('img');
imageCompressQuality = 50;
sourceImage.src = "data:image/jpeg;base64," + images[i].PhotoPath;
//PhotoPath is a base64 string
result_image.src = compress(sourceImage, imageCompressQuality, 'jpg').src;
compressedImages.push({
PhotoId: images[i].PhotoId,
PhotoPath: result_image.src.split(',').pop()
});
}
和压缩功能:
compress (source_img_obj, quality, output_format) => {
let mime_type = "image/jpeg";
if (typeof output_format !== "undefined" && output_format == "png") {
mime_type = "image/png";
}
let result_image_obj = new Image();
let cvs = document.createElement('canvas');
cvs.width = source_img_obj.naturalWidth;
cvs.height = source_img_obj.naturalHeight;
let ctx = cvs.getContext("2d").drawImage(source_img_obj, 0, 0);
let newImageData = cvs.toDataURL(mime_type, quality / 100);
result_image_obj.src = newImageData;
return result_image_obj;
};