Preview an image before it is uploaded (HTML + JS)
Simple web Image Viewer : Display the image in browser immediately after the image has been selected. also fatch some information about that image like File Name, File Size (in MB), file width and height.
<!DOCTYPE html>
<html>
<body>
Upload image:
<input id="image-file" type="file" name="file" />
<input type="submit" value="Upload" />
<script type="text/javascript">
document.getElementById('image-file').addEventListener('change', function() {
compressImage(this) ;
document.getElementById('fsize').innerHTML = this.files[0].size/1024/1024 + " MB";
document.getElementById('fname').innerHTML = this.files[0].name;
});
</script>
<script>
function compressImage(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
var imgWidth,imgHeight ;
reader.onload = function(e) {
var resizeCanvas = document.getElementById("compressImageCanvas");
var ctx = resizeCanvas.getContext("2d");
var img = new Image;
// var ratio = 2/25;
var ratio = document.getElementById('zoomLevel').value/100;
img.onload = function(){
imgWidth = this.width;
imgHeight = this.height;
resizeW = imgWidth * ratio;
resizeH = imgHeight * ratio;
document.getElementById('fw').innerHTML = imgWidth;
document.getElementById('fh').innerHTML = imgHeight;
ctx.canvas.width = resizeW;
ctx.canvas.height = resizeH;
ctx.drawImage(img,0,0, imgWidth, imgHeight, 0, 0, imgWidth * ratio, imgHeight * ratio );
};
img.src = reader.result;
}
reader.readAsDataURL(input.files[0]);
}
}
</script>
<script>
function updateZoom(val) {
document.getElementById('Zoom').innerHTML=val+"%";
}
</script>
<div style="width: fit-content; text-align: center;">
<div style="align:center"><input type="range" id="zoomLevel" name="zoom" value="8" min="0" max="100" onchange="updateZoom(this.value);"></div>
<canvas id="compressImageCanvas" width="200" height="100" style="border:2px solid #d3d3d3; padding:10px;margin:10px;"></canvas>
</div>
<div id="imageDetails" style="padding:20px;">
<div style="color:#757575"> zoom: <span id="Zoom" >8%</span></div>
</br>
File Name: <span id="fname"></span></br>
File Size: <span id="fsize"></span></br>
Width: <span id="fw"></span></br>
Height: <span id="fh"></span></br>
</div>
</body>
</html>
See the Pen Preview an image before it is uploaded (HTML + JS) by abonzer (@abonzer) on CodePen.
No comments: