I know that data:URL can provide images not bigger than 2MB and moreover it increases a size of image by 33%. So I need to compress an uploaded image before preview. Please, tell me - how can I do it?
Use URL.createObjectURL
instead, making sure to revokeObjectURL
when you don’t need the image anymore:
'use strict';
var fileInput = document.getElementById('file');
var preview = document.getElementById('preview');
fileInput.addEventListener('change', function () {
if (this.files.length === 0) {
return;
}
preview.src = URL.createObjectURL(this.files[0]);
});
<input id="file" type="file" accept="image/*" />
<img id="preview" style="display: block; margin: 1em 0; max-width: calc(100% - 2em);" />