图片压缩 base64与图片文件相互转换

//图片文件转base64
getImageBase64Data = function (imgSrc) {
    function getBase64(img) {
        var canvas = document.createElement("canvas");
        var width = img.width;
        var height = img.height;
        if (width > height) {
            if (width > 500) {
                height = Math.round(height *= 500 / width);
                width = 500;
            }
        } else {
            if (height > 500) {
                width = Math.round(width *= 500 / height);
                height = 500;
            }
        }
        canvas.width = width; /*设置新的图片的宽度*/
        canvas.height = height; /*设置新的图片的长度*/
        var ctx = canvas.getContext("2d");
        ctx.drawImage(img, 0, 0, width, height); /*绘图*/
        var dataURL = canvas.toDataURL("image/jpeg");
        return dataURL
    }

    var p = new Promise(function (resolve, reject) {
        var image = new Image();
        image.crossOrigin = 'Anonymous';
        image.src = imgSrc;

        image.onload = function () {
            var imageBase64Data = getBase64(image);
            resolve(imageBase64Data);
        }
    });
    return p;
};

//base64转图片
function dataURLtoFile(dataurl) {
    var bitmap = new plus.nativeObj.Bitmap();
    var result = new Date().getTime();
    var filename = result + "_picture" + ".jpeg";
    bitmap.loadBase64Data(dataurl);
    bitmap.save(
        "_doc/" + filename, {
            overwrite: true
        },
        function (i) {
            //保存到系统相册
            plus.gallery.save(
                i.target,
                function (d) {
                    //销毁Bitmap图片
                    bitmap.clear();
                    //console.log("保存图片到相册成功");
                },
                function () {
                    //console.log("保存保存失败");
                }
            );
        },
        function () {
            bitmap.clear();
        }
    );
    var path = "file://" + plus.io.convertLocalFileSystemURL("_doc/" + filename);
    return path
}

你可能感兴趣的:(图片压缩 base64与图片文件相互转换)