Posted By

themilossh on 09/12/18


Tagged

javascript resize image preview upload Browse crop vanillajs


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

themilossh


JavaScript image preview before upload


 / Published in: JavaScript
 

URL: https://www.musingmick.com/javascript-image-preview-snippet/

Simple JavaScript image upload preview script. Let's you show your users preview the image before upload.

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title>JavaScript image preview before upload</title>
  5. <script type="text/javascript">
  6. var e = document.getElementById('cover');
  7. e.onchange = function getPreview() {
  8. var file = this.files[0];
  9. resizeImage(file).then(function(cover) {
  10. var cpreview = document.getElementById("preview-image");
  11. cpreview.setAttribute('style', 'background-image: url(\'' + cover + '\'); background-size: contain;');
  12. });
  13. }
  14.  
  15. function resizeImage(file) {
  16. return new Promise(function(a) {
  17. // Create an image
  18. var img = document.createElement("img");
  19.  
  20. // Create a file reader
  21. var reader = new FileReader();
  22. // Set the image once loaded into file reader
  23.  
  24. var ready = false;
  25.  
  26. reader.onload = function(e) {
  27. img.src = e.target.result;
  28. img.onload = function() {
  29.  
  30. var canvas = document.createElement("canvas");
  31. var ctx = canvas.getContext("2d");
  32.  
  33. ctx.drawImage(img, 0, 0);
  34.  
  35. var width = img.width;
  36. var height = img.height;
  37.  
  38. var canvasRatio = 0.75;
  39. var ratio = img.height / img.width;
  40.  
  41. if (ratio < canvasRatio) {
  42. img.width = width * 600 / height;
  43. img.height = 600;
  44. } else {
  45. img.height = height * 800 / width;
  46. img.width = 800;
  47. }
  48.  
  49. canvas.width = 800;
  50. canvas.height = 600;
  51.  
  52. ctx.drawImage(img,
  53. 400 - img.width / 2,
  54. 300 - img.height / 2,
  55. img.width,
  56. img.height
  57. );
  58.  
  59. var dataurl = canvas.toDataURL('image/jpeg', 1.0);
  60. ready = true;
  61. a(dataurl);
  62. }
  63. }
  64.  
  65. reader.readAsDataURL(file);
  66. })
  67. }
  68.  
  69. </script>
  70. </head>
  71. <body>
  72. <label for="cover">
  73. <span>Upload game cover…</span>
  74. <input type="file" id="cover" name="cover">
  75. </label>
  76. <div id="preview-image"></div>
  77. </body>
  78. </html>

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: themilossh on September 12, 2018

Live preview at https://jsfiddle.net/themilossh/pgqysjnc/

You need to login to post a comment.