前端 pdfbase64转图片base64
时间: 2023-12-01 22:43:21 浏览: 108
linux下图片批量转base64
5星 · 资源好评率100%
在前端将pdfbase64转换为图片base64的过程中,可以使用canvas来实现。具体步骤如下:
1. 将pdfbase64转换为blob对象。
```javascript
function base64ToBlob(base64) {
var arr = base64.split(',');
var mime = arr[0].match(/:(.*?);/)[1];
var bstr = atob(arr[1]);
var n = bstr.length;
var u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new Blob([u8arr], {type: mime});
}
var pdfBlob = base64ToBlob(pdfBase64);
```
2. 将blob对象转换为URL。
```javascript
var pdfUrl = URL.createObjectURL(pdfBlob);
```
3. 创建canvas对象并绘制图片。
```javascript
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
var img = new Image();
img.onload = function() {
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img, 0, 0);
var imgBase64 = canvas.toDataURL();
// do something with imgBase64
};
img.src = pdfUrl;
```
4. 将图片base64返回给后端。
完整代码如下:
```javascript
function pdfToImgBase64(pdfBase64) {
function base64ToBlob(base64) {
var arr = base64.split(',');
var mime = arr[0].match(/:(.*?);/)[1];
var bstr = atob(arr[1]);
var n = bstr.length;
var u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new Blob([u8arr], {type: mime});
}
var pdfBlob = base64ToBlob(pdfBase64);
var pdfUrl = URL.createObjectURL(pdfBlob);
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
var img = new Image();
img.onload = function() {
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img, 0, 0);
var imgBase64 = canvas.toDataURL();
// do something with imgBase64
};
img.src = pdfUrl;
}
```
阅读全文