簡體   English   中英

通過 angular 6 應用程序中的 javascript 更改 base64 圖像大小並下載不同擴展名(png、jpg、gif 等)

[英]Change base64 image size and download with different extension(png, jpg, gif, etc…) by javascript in angular 6 application

我想根據尺寸選擇更改我的 base64 圖像尺寸(寬度/高度),然后下載不同的擴展名,如 jpg、png、gif 等....

我正在嘗試通過 html5 下載標簽下載圖像。

我想以動態維度下載不同的擴展。

首先,我在我的 html 文件中創建單擊 function。

<button type="submit" (click)="imgDownload()" class="btn btn-primary">Download</button>

然后我在我的 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);
  // ********************************************
}
}

這是我自己的問題的解決方案。 謝謝你看到它。

只需使用此 package Images https://www.npmjs.com/package/images支持圖像質量、大小、擴展操作選項,節省您的時間!!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM