2分 read (About 239 words)
【JavaScript】base64の画像をimgタグにセットする方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| async setImageToInput(base64Image, inputElement) { const img = document.createElement('img'); img.src = base64Image;
await new Promise((resolve) => img.onload = resolve);
const canvas = document.createElement('canvas'); canvas.width = img.width; canvas.height = img.height; const ctx = canvas.getContext('2d'); ctx.drawImage(img, 0, 0);
const blob = await new Promise((resolve) => canvas.toBlob(resolve));
const file = new File([blob], 'image.jpg', {type: blob.type});
const dataTransfer = new DataTransfer(); dataTransfer.items.add(file);
inputElement.files = dataTransfer.files;
inputElement.dispatchEvent(new Event('change')); },
const base64Image = document.getElementById(imgId).src; const inputElement = document.getElementById('item_image'); this.setImageToInput(base64Image, inputElement).then(r => );
|