JavaScript把图像的base64压缩后返回base64String

重点参考了这篇文章:前端JS利用canvas的drawImage()对图片进行压缩  : https://www.cnblogs.com/goloving/p/8260206.html

其实是叫AI ChatGPT帮忙整理的,整理成了一个函数,方便调用,我用过觉得好用,现在记录下来:

     //把base64压缩后处理为base64
        function compressBase64Image(base64Data, maxWidth, maxHeight, callback) {
            var img = new Image();
            img.onload = function() {
                var originWidth = this.width;
                var originHeight = this.height;

                var targetWidth = originWidth;
                var targetHeight = originHeight;

                if (originWidth > maxWidth || originHeight > maxHeight) {
                    if (originWidth / originHeight > maxWidth / maxHeight) {
                        targetWidth = maxWidth;
                        targetHeight = Math.round(maxWidth * (originHeight / originWidth));
                    } else {
                        targetHeight = maxHeight;
                        targetWidth = Math.round(maxHeight * (originWidth / originHeight));
                    }
                }

                var canvas = document.createElement('canvas');
                var context = canvas.getContext('2d');
                canvas.width = targetWidth;
                canvas.height = targetHeight;
                context.clearRect(0, 0, targetWidth, targetHeight);
                context.drawImage(img, 0, 0, targetWidth, targetHeight);

                var compressedBase64Data = canvas.toDataURL('image/jpeg'); //返回结果BASE64
                callback(compressedBase64Data); //接下来要进行的数据处理
            };

            img.src = base64Data;
        }

 

 使用方法可以参考以下的示例代码片段:

            
                var array = [];
          var reader = new FileReader();
          //省略了for循环的一些代码
                    reader.readAsDataURL(file); //把上传的file转BASE64
                    console.log();
                    reader.onload = function(e) {
                        //方法:上传压缩图片
                        var base64Data = e.target.result;
                        compressBase64Image(base64Data, 1000, 1000, function(compressedBase64Data) {
                            // 在这里处理压缩后的 base64 图像数据
                            //console.log(compressedBase64Data);
                            array.push(compressedBase64Data);
                            // 如果所有图片都被处理完毕,上传到Redis
                            if (array.length === filesLen) {
                                //图片ajax上传
                                postMultiToRedis(array);
                            } 
                        });

 

 
posted @ 2023-12-11 16:20  zzgreg  阅读(128)  评论(0编辑  收藏  举报