我有两个主要问题。我正在尝试根据
中的答案调整base64图像的大小JavaScript reduce the size and quality of image with based64 encoded code
这看起来很简单,除了我需要从该函数中只获取base64字符串而没有data:image ... header。
我试图像这样修改函数:
function resizeBase64Img(base64, width, height) {
var canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
var context = canvas.getContext("2d");
var deferred = $.Deferred();
$("<img/>").attr("src", "data:image/gif;base64," + base64).load(function () {
context.scale(width / this.width, height / this.height);
context.drawImage(this, 0, 0);
deferred.resolve($("<img/>").attr("src", canvas.toDataURL()));
});
var result = canvas.toDataURL();
return result.substr(result.indexOf(",") + 1)
}
返回base64字符串。此字符串已损坏,并且永远无法正确显示。为什么会发生这种情况?我该如何解决?
另一个问题是,有没有办法根据百分比调整图像大小而不是像素大小?
由于
答案 0 :(得分:0)
我最终根据我找到的另一个canvas函数重写了该函数。此函数获取base64 img的src,修改大小并将base64中的结果分配给另一个元素:
function resizeBase64Img(url, width, height) {
var img = new Image();
img.setAttribute('crossOrigin', 'anonymous');
img.onload = function () {
var canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
var ctx = canvas.getContext("2d");
ctx.scale(width/this.width, height/this.height);
ctx.drawImage(this, 0, 0);
result=canvas.toDataURL();
$('#ASSIGNEDELEMENT').val(result.substr(result.indexOf(",") + 1));
};
img.src = url;
}
它应该像这样调用:
resizeBase64Img($('#image').attr('src'),300,300);