JSFiddle - React, Tailwind, and code Playground
HTML
<section class="jpg-convertor">
<div class="form-control">
<label>Pick jpg Image to convert</label>
<input type="file" name="image" />
</div>
</section>
CSS
body {
margin: 0;
padding: 0;
height: 100%;
text-align: center;
}
.form-control {
margin-top: 20px;
}
JavaScript
(function(window) {
const JpgToPngConvertor = (() => {
function convertor(imageFileBlob, options) {
options = options || {};
const defaults = {
downloadLinkSelector: '.js-download-png'
};
const settings = extend(defaults, options);
const canvas = document.createElement('canvas');
const ctx = canvas.getContext("2d");
const imageEl = createImage();
const downloadLink = settings.downloadEl || createDownloadLink();
function createImage(options) {
options = options || {};
const img = (Image) ? new Image() : document.createElement('img');
const parent = options.parentEl || document.body;
img.style.width = (options.width) ? options.width + 'px' : 'auto';
img.style.height = (options.height) ? options.height + 'px' : 'auto';
return img;
}
function extend(target, source) {
for (let propName in source) {
if (source.hasOwnProperty(propName)) {
target[propName] = source[propName];
}
}
return target;
}
function createDownloadLink() {
return document.createElement('a');
}
function isFirefox() {
return navigator.userAgent.indexOf("Firefox") > -1;
}
function download() {
// Add download link to DOM in case it is not there and on the firefox
if (!document.contains(downloadLink) && isFirefox()) {
downloadLink.style.display = 'none';
document.body.appendChild(downloadLink);
}
if ('click' in downloadLink) {
downloadLink.click();
} else {
downloadLink.dispatchEvent(createClickEvent());
}
}
function updateDownloadLink(jpgFileName, pngBlob) {
const linkEl = downloadLink;
const pngFileName = jpgFileName.replace(/jpe?g/i, 'png');
linkEl.setAttribute('download', pngFileName);
...