Created
September 14, 2022 19:06
-
-
Save luan0ap/cdf4fe6cfd8200341f5aa4a2e654290f to your computer and use it in GitHub Desktop.
Image converter PNG to JPG
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const createElement = (HTMLElementName, { ...HTMLAttributes } = {}) => { | |
const $el = document.createElement(HTMLElementName) | |
for (const key in HTMLAttributes) { | |
$el.setAttribute(key, HTMLAttributes[key]) | |
} | |
return $el | |
} | |
function png2jpg (imageSrc) { | |
const generateCanvas = ({ width = 0, height = 0} = {}) => { | |
const $canvas = createElement('canvas', { width, height }) | |
const context = $canvas.getContext('2d'); | |
context.fillStyle = '#000'; /// set white fill style | |
context.fillRect(0, 0, width, height); | |
context.drawImage($image, 0, 0) | |
return $canvas | |
} | |
const $image = createElement('img', { src: imageSrc }) | |
return new Promise((resolve, reject) => { | |
$image.onload = () => { | |
const $canvas = generateCanvas({ width: $image.width, height: $image.height }) | |
return resolve($canvas.toDataURL()) | |
} | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment