【2021】How to resize an image from the web and send it to Cloud Storage for Firebase

# 【2021】How to resize an image from the web and send it to Cloud Storage for Firebase

I have implemented a process to resize a logo image and send it to Cloud Storage for Firebase.
I struggled a bit with the conversion to base64, blob, etc., so I'll share it so that new implementers can realize the process they want to do as quickly as possible.

```index.html
<!-- Optional image file button (This is implemented in my case because the file selection button is an image instead of the default button, but the normal file function is also acceptable. -->
<label>
<!-- Show part -->
<span class="filelabel" title="Select a file">
<img src="images/camera.png"" width="32" height="26" alt="Image">
<!-- Selsect -->
</span>
<!-- Hide the original selection form. -->
<input type="file" name="datafile" id="logo-img-input" onChange="imgPreView(event)">
</label>

<div id="preview"></div>
<canvas id="for-resize-canvas" style="display: none;"></canvas>
<button id="send" class="btn btn-primary">SEND</button>

```

`style="display: none;`
As for the canvas, I hide it because without it, another image view would be created.
The resizing process can be done without displaying it.

```index.js
//===Preview Image
function imgPreView(event) {
    let file = event.target.files[0];
    let reader = new FileReader();
    let preview = document.getElementById("preview");
    let previewImage = document.getElementById("previewImage");
    
    if(previewImage != null) {
        preview.removeChild(previewImage);
    }
    
    reader.onload = function(event) {
        let img = document.createElement("img");
        img.setAttribute("src", reader.result);
        /// Size of the image to be displayed in the preview (Warning : not the size to be resized)
        img.width = 200; 
        img.height = 200;
        img.setAttribute("id", "previewImage");
        preview.appendChild(img);
    };
    reader.readAsDataURL(file);
}

///When the "SEND" button is pressed
document.getElementById("send").onclick = function() {
    let files = document.getElementById('logo-img-input').files;
    ///=== register/update to DB
    /// If a file is selected
    if (files.length == 1) {
        ///===Resize the image -> Drawto the canvas -> Conversion process to blobe format (get and use previewImage image instead of file)
        let orgImage = document.getElementById('previewImage');
        let orgWidth  = orgImage.width;  // Save the original width
        let orgHeight = orgImage.height; // Save the original height

        let targetImg = new Image();
        targetImg.src = $("#previewImage").attr('src');

        ///Specify the horizontal length as width, and calculate the reduced height while maintaining the aspect ratio.
        let width = 300;
        let ratio = width / targetImg.width;
        let height = targetImg.height * ratio;
                    
        ///Draw to the canvas
        let canvas = $("#canvas");
        let ctx = canvas[0].getContext('2d');
        $("#canvas").attr("width", width);
        $("#canvas").attr("height", height);
        ctx.drawImage(targetImg, 0, 0, width, height);    

        /// Get the image from canvas as base64
        let base64 = canvas.get(0).toDataURL('image/jpeg');
        /// Uncomment this section if you want to see the base64 values displayed.
        /// console.log("base64 : " , base64);

        /// Creating image data from base64
        let barr, bin, i, len;
        bin = atob(base64.split('base64,')[1]);
        len = bin.length;
        barr = new Uint8Array(len);
        i = 0;
        while (i < len) {
          barr[i] = bin.charCodeAt(i);
          i++;
        }
        blob = new Blob([barr], {type: 'image/jpeg'});
        /// Uncomment this section if you want to see the blob values displayed.
        // console.log("blob : " , blob);

        let file_path =  "/anyPathOf/" + "/outputImg.jpg";

        let logImgRef = firebase.storage().ref().child(file_path);
        logImgRef.put(blob).then(function(snapshot) {
          /// If you want to know the URL where the image is saved
          logImgRef.getDownloadURL().then(img_url => {
              console.log("savedImgUrl : ", img_url);
              /// Once the URL of the image is obtained, it is registered in the DB.
              /// [Any Codes]
          });
        });
    }
    //If no file is selected
    else {
        /// [Any Codes]
    }
}
```

I'm hoping this article will help some of you out!

---
Please be nice to me on Twitter!
https://twitter.com/funny_man_daa