js base64png 怎么转换成base64jpg
时间: 2024-05-28 21:07:39 浏览: 184
将base64png转换为base64jpg需要经过以下几个步骤:
1. 将base64png转换为二进制数据;
2. 将二进制数据转换为图像对象;
3. 将图像对象转换为canvas对象;
4. 将canvas对象转换为base64jpg。
具体的实现可以参考以下代码:
```
// 将base64png转换为二进制数据
const base64ToBlob = function(base64) {
const bytes = window.atob(base64.split(','));
const array = new Uint8Array(bytes.length);
for (let i = 0; i < bytes.length; i++) {
array[i] = bytes.charCodeAt(i);
}
return new Blob([array], {type: 'image/png'});
};
// 将二进制数据转换为图像对象
const blobToImage = function(blob) {
return new Promise((resolve, reject) => {
const img = new Image();
img.onload = function() {
resolve(img);
};
img.onerror = function() {
reject();
};
img.src = URL.createObjectURL(blob);
});
};
// 将图像对象转换为canvas对象
const imageToCanvas = function(image) {
const canvas = document.createElement('canvas');
canvas.width = image.width;
canvas.height = image.height;
const context = canvas.getContext('2d');
context.drawImage(image, 0, 0, image.width, image.height);
return canvas;
};
// 将canvas对象转换为base64jpg
const canvasToBase64 = function(canvas) {
return canvas.toDataURL('image/jpeg', 1);
};
// 示例
const base64png = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAAFElEQVR4AWPw2v7Wfe0f+gYGBgYGBoYBQABJzAU4AAAAASUVORK5CYII=';
const blob = base64ToBlob(base64png);
blobToImage(blob)
.then(imageToCanvas)
.then(canvasToBase64)
.then(function(base64jpg) {
console.log(base64jpg);
});
```
阅读全文