Skip to content Skip to sidebar Skip to footer

Resize Image With Javascript And Save To Disk

I was trying to upload resized image done by JavaScript to server. So I tried to set file input with resized image. After that I came to know we cannot change file input unless use

Solution 1:

Finally I solved it myself and I add my solution here for future readers.

$(document).on("change", ":file", function(event)
{
    if(this.files && this.files[0])
    {
        var file_input=$(this);
        var file=this.files[0];
        var file_type=file.type;
        if(file_type && file_type.substr(0,5)=="image")
        {
            var img = document.createElement("img");
            var reader = newFileReader();
            reader.onload = function (e)
            {
                img.src = e.target.result;
                img.onload = function (imageEvent)
                {
                    varMAX_WIDTH = 800;
                    varMAX_HEIGHT = 600;
                    var width = img.naturalWidth;
                    var height = img.naturalHeight;
                    //resize the image if it higher than MAX_WIDTH or MAX_HEIGHTif((width>MAX_WIDTH)||(height>MAX_HEIGHT))
                    {
                        if((width/height)>(MAX_WIDTH/MAX_HEIGHT))
                        {
                            height *= MAX_WIDTH / width;
                            width = MAX_WIDTH;
                        }
                        else
                        {
                            width *= MAX_HEIGHT / height;
                            height = MAX_HEIGHT;
                        }
                        var canvas = document.createElement("canvas");
                        canvas.width = width;
                        canvas.height = height;
                        var ctx = canvas.getContext("2d");
                        ctx.drawImage(img, 0, 0, width, height);
                        //following two lines saves the imagevar image = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream");  
                        window.location.href=image; ////file_input.val(null);//if you want reset file input//file_input.trigger('click'); //if you want to reopen file input                           

                    }
                };

            };
            reader.readAsDataURL(file);
        }

    }
    else
    {
        console.log('no file attached');
    }
});

These two lines save the file

var image = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream");  
window.location.href=image; 

Unfortunately it does not use a good filename to save. So I used an alternative way to replace those two lines.

Download FileSaver.js from here and include it to your script. Now you can replace those two lines with these codes

canvas.toBlob(function(blob)
{
   saveAs(blob, 'image.png');
  //saveAs(blob, file.name);//or this one
});

Post a Comment for "Resize Image With Javascript And Save To Disk"