简体   繁体   English

压缩/调整jpeg大小并使用Javascript获取Base64

[英]Compress/Resize jpeg and get the Base64 in Javascript

How to reduce the size of a base64 String for a Jpeg Image? 如何减少Jpeg图像的base64字符串的大小? I have the base64 of a 2000x1000px photo. 我有一张2000x1000px照片的base64。 How to get the 500x250px base64 compressed photo? 如何获得500x250px base64压缩的照片? Someone can help me? 有人可以帮我吗?

put the base64 in an image tag 将base64放在图片标签中

var img = document.createElement("img");
img.src = "data:image/gif;base64," + yourBase64;

draw it to a scaled canvas 绘制到缩放画布上

var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext("2d");
ctx.scale(0.25, 0.25);
ctx.drawImage(img);

get the base64 得到base64

var base64 = canvas.toDataURL("image/jpeg");

I didn't actually test this so the resizing part might be wrong, but it would be something like this. 我实际上没有对此进行测试,因此调整大小部分可能是错误的,但这将是这样的。

try searching how to resize images using the canvas tag. 尝试搜索如何使用canvas标签调整图像大小。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM