[英]Change base64 image size and download with different extension(png, jpg, gif, etc…) by javascript in angular 6 application
I want to change my base64 image size(width/height) according to size selection and then download with different extensions like jpg, png, gif, etc....我想根据尺寸选择更改我的 base64 图像尺寸(宽度/高度),然后下载不同的扩展名,如 jpg、png、gif 等....
I am trying to download images by html5 download tags.我正在尝试通过 html5 下载标签下载图像。
I want to download in different extensions with a dynamic dimension.我想以动态维度下载不同的扩展。
First I create a click function in my html file.首先,我在我的 html 文件中创建单击 function。
<button type="submit" (click)="imgDownload()" class="btn btn-primary">Download</button>
Then I write function in my component.ts file.然后我在我的 component.ts 文件中写入 function 。
imgDownload() {
// ********************************************
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
canvas.width = 200; // target width
canvas.height = 200; // target height
const image = new Image();
image.src = jQuery('img').attr('src'); // ***get default iamge base64
ctx.drawImage(image,
0, 0, image.width, image.height,
0, 0, canvas.width, canvas.height
);
// create a new base64 encoding
const resampledImage = new Image();
resampledImage.src = canvas.toDataURL(); // ****get converted image base64 src
this.download (resampledImage.src); }
// ********************************************
download (imgLink){
if (this.imgType === 'jpeg' || this.imgType === 'png' || this.imgType === 'gif') {
// ***************************************************
const clearUrl = linkAncher => linkAncher.replace(/^data:image\/\w+;base64,/, '');
const downloadImage = (name, content, type) => {
const linkAncher = document.createElement('a');
linkAncher.style = 'position: fixed; left -10000px;';
linkAncher.href = `data:application/octet-stream;base64,${encodeURIComponent(content)}`;
linkAncher.download = /\.\w+/.test(name) ? name : `${name}.${type}`;
document.body.appendChild(linkAncher);
linkAncher.click();
document.body.removeChild(linkAncher);
};
downloadImage(this.itemName + '_QR_code', clearUrl(imgLink), this.imgType);
// ********************************************
}
}
This is a solution to my own question.这是我自己的问题的解决方案。 Thanks for seeing it.
谢谢你看到它。
Simply use this package Images
https://www.npmjs.com/package/images
supports image quality, size, extensions manipulation options, saves you time!!只需使用此 package
Images
https://www.npmjs.com/package/images
支持图像质量、大小、扩展操作选项,节省您的时间!!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.