TheRogerLAB Codes

Resize an image before send it to the server

  July, 2021

Introduction

When we want to upload an image to our server we often have to decide when to resize it, whether before or after uploading it, not only because of dimensions but also because of the file size. Many websites or apps resize the image before sending it to the server and thus control the dimensions, reduce the file size, increase the uploadind speed, and do not bother the user asking him to reduce the size of image file.

Step 1: Define a file input type in HTML

Select a file: 
<input type="file" id="uploader">
<button onclick='resize()'>Resize</button>
<img id="image">

Step 2: Define a function to resize the image in javascript

function resize(){
  //define the width to resize e.g 600px
  var resize_width = 600;//without px

  //get the image selected
  var item = document.querySelector('#uploader').files[0];

  //create a FileReader
  var reader = new FileReader();

  //image turned to base64-encoded Data URI.
  reader.readAsDataURL(item);
  reader.name = item.name;//get the image's name
  reader.size = item.size//get the image's size
  reader.onload = function(event) {
    var img = new Image();//create a image
    img.src = event.target.result;//result is base64-encoded Data URI
    img.name = event.target.name;//set name (optional)
    img.size = event.target.size;//set size (optional)
    img.onload = function(el) {
      var elem = document.createElement('canvas');//create a canvas

      //scale the image to 600 (width) and keep aspect ratio
      var scaleFactor = resize_width / el.target.width;
      elem.width = resize_width;
      elem.height = el.target.height * scaleFactor;

      //draw in canvas
      var ctx = elem.getContext('2d');
      ctx.drawImage(el.target00, elem.width, elem.height);

      //get the base64-encoded Data URI from the resize image
      var srcEncoded = ctx.canvas.toDataURL('image/png'1);

      //assign it to thumb src
      document.querySelector('#image').src = srcEncoded;

      /*Now you can send "srcEncoded" to the server and
      convert it to a png o jpg. Also can send
      "el.target.name" that is the file's name.*/


    }
  }
}

Step 3: Sending the resized image to the server

//get the resized image from src
var resized = document.querySelector('#image').src;

//note: remember that the image is now base64-encoded Data URI

//sendind the image to the server (php)
var fd = new FormData();
fd.append("image", resized);

//sending data to the server
var xhr = new XMLHttpRequest();

xhr.onreadystatechange = function(){
  //everything is ok
  if (xhr.readyState==4 && xhr.status==200){
    var response = JSON.parse(xhr.responseText);
    if(response.success == true){
      alert('The image was uploaded');
    }
  }
}
xhr.open("POST""upload.php");
xhr.send(fd);

Step 4: Get the data PHP

<?php
//this file is upload.php

//directory
$target_dir = "images/";

//catch the image sent from client
$image = $_POST['image'];

//replacing some characters from the base64
$image = str_replace('data:image/png;base64,''', $image);
$image = str_replace(' ''+', $image);

//decoding the base64
$data = base64_decode($image);

//generating and unique name (or write manually one name)
$unique = uniqid();

//setting the path
$file = $target_dir.$unique.'.png';

//putting all the content into a file
$success = file_put_contents($file, $data);

//if everything was ok send back an json response
if($success != false)
  echo '{"success": true}';

?> 

Check a working demo for this component:

SEE DEMO WATCH VIDEO DOWNLOAD RATE THIS ARTICLE
4.5
10
TheRogerLAB Codes
Powered by TheRogerLAB Sandbox

info@therogerlab.com