Skip to content

Instantly share code, notes, and snippets.

@luan0ap
Created September 14, 2022 19:06
Show Gist options
  • Save luan0ap/cdf4fe6cfd8200341f5aa4a2e654290f to your computer and use it in GitHub Desktop.
Save luan0ap/cdf4fe6cfd8200341f5aa4a2e654290f to your computer and use it in GitHub Desktop.
Image converter PNG to JPG
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