-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathredimensionarImagem.html
81 lines (59 loc) · 2.02 KB
/
redimensionarImagem.html
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
73
74
75
76
77
78
79
80
81
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<input type="file" id="file" />
<div>
<h4>Original</h4>
<img id="original">
</div>
<div>
<h4>Resized</h4>
<img id="resized">
</div>
</body>
<script>
function loadImage(img, src) {
return new Promise((resolve, reject) => {
img.src = src;
img.completed ? resolve(img) : img.addEventListener('load', function() {
resolve(img)
});
img.addEventListener('error', reject);
})
}
function resizeImage(src, options) {
return loadImage(document.createElement('img'), src).then(function(image) {
var canvas = document.createElement('canvas');
if (options.width && !options.height) {
options.height = image.height * (options.width / image.width)
} else if (!options.width && options.height) {
options.width = image.width * (options.height / image.height)
}
Object.assign(canvas, options);
canvas.getContext('2d').drawImage(image, 0, 0, canvas.width, canvas.height);
return new Promise(function(resolve) {
canvas.toBlob(resolve, options.type || 'image/png', options.quality)
})
})
}
window.addEventListener('load', function() {
var file = document.querySelector('#file');
file.addEventListener('change', function() {
var image = file.files[0];
var src = URL.createObjectURL(image);
document.querySelector("#original").src = src;
resizeImage(src, {
width: 200
}).then(function(blob) {
document.querySelector("#resized").src = URL.createObjectURL(blob)
})
});
})
</script>
</html>