-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
72 lines (57 loc) · 2.06 KB
/
script.js
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
//! A IIFE function to convert the JPG file to PNG
const JPG_to_PNG_converter = (() => {
function converter(imageFileBlob, options) {
options = options || {}
//* Creating a canvas element and then putting the image (jpg) there
const canvas = document.createElement("canvas")
const context = canvas.getContext("2d")
const imageElement = createImage()
const downloadLink = document.createElement("a")
//* Here we create our image blob
function createImage(options) {
options = options || {}
const img = document.createElement("img")
img.style.width = options.width ? `${options.width}px` : "auto"
img.style.height = options.height ? `${options.height}px` : "auto"
return img
}
function updateDownloadLink(jpgFileName, pngBlob) {
const linkElement = downloadLink
const pngFileName = jpgFileName.replace(/jpe?g/i, "png")
linkElement.setAttribute("download", pngFileName)
linkElement.href = URL.createObjectURL(pngBlob)
downloadLink.click()
}
function process() {
const imageUrl = URL.createObjectURL(imageFileBlob)
imageElement.addEventListener("load", e => {
canvas.width = e.target.width
canvas.height = e.target.height
context.drawImage(e.target, 0, 0, e.target.width, e.target.height)
canvas.toBlob(
updateDownloadLink.bind(window, imageFileBlob.name),
"image/png"
)
})
imageElement.src = imageUrl
}
return {
process: process,
}
}
return converter
})()
//HTML image file field
const imageFileElement = document.querySelector(".jpg-upload-input")
//Add file change event handler
imageFileElement.addEventListener("change", event => {
const jpgImageFileBlob = event.currentTarget.files[0]
//Validating if the file's type is JPG or different
if (jpgImageFileBlob.type.match(/image\/jpe?g/i) !== null) {
JPG_to_PNG_converter(jpgImageFileBlob).process()
} else {
alert(
`Invalid JPG image file! Got an image with type ${jpgImageFileBlob.type}`
)
}
})