Converting File object to Image object in JavaScript

18,143

You just need to create an Image instance, and set it's src to your data url. Then pass it to JIC:

var img = new Image();
img.src = $scope.image_source;
jic.compress(img,...)

It then just uses a canvas element to manipulate the image, generate a new data url, and creates a new Image instance, setting its src to the data url. So when you get the compressed image back just take the src and use atob to decode the base64 encoded data back into binary and create a Blob. You can use Blob in most places that you would use File, for instance like uploading through ajax.

var newImg = jic.compress(oldImg,...);
//replace 'image/png' with the proper image mime type
var base64data = newImg.src.replace("data:image/png;base64,","");
var bs = atob(base64data);
var buffer = new ArrayBuffer(bs.length);
var ba = new Uint8Array(buffer);
for (var i = 0; i < bs.length; i++) {
    ba[i] = bs.charCodeAt(i);
}
var blob = new Blob([ba],{type:"image/png"});
//now use blob like you would any other File object
Share:
18,143
Evan
Author by

Evan

Updated on August 01, 2022

Comments

  • Evan
    Evan almost 2 years

    So I have a website (using AngularJS) that lets users upload files via tag

    <input type="file" ng-model="image" id="trigger" onchange="angular.element(this).scope().setFile(this)" accept="image/*">
    

    When I handle the upload in the controller the image gets stored as a File object. This is my method that saves the file and also sets variables to preview the image

    $scope.setFile = function (element) {
        $scope.image = element.files[0]; // This is my image as a File
        var reader = new FileReader();
    
        //This is for previewing the image
        reader.onload = function (event) {
            $scope.image_source = event.target.result;
            $scope.$apply();
    
        }
        reader.readAsDataURL(element.files[0]);
    }
    

    Now I am trying to compress the image using J-I-C library found here: https://github.com/brunobar79/J-I-C/blob/master/src/JIC.js

    But this library accepts an image object as its parameter and returns it as a compressed image object. I can't seem to find a way to convert my $scope.image File object into an Image object. How would I go about doing this?

    I would also need to convert the compressed image object back into a File so I can upload it to my Azure storage.

  • Evan
    Evan almost 8 years
    Thank you so much exactly what I needed.
  • Isengo
    Isengo almost 8 years
    Having a similar issue: jic.js:22 Uncaught InvalidCharacterError: Failed to execute 'atob' on 'Window': The string to be decoded is not correctly encoded. var preview = document.querySelector('#preview_image'+x); var file = document.querySelector('#images'+x).files[0]; var reader = new FileReader(); var img = new Image(); img.src = file.src; img.src = jic.compress(img,70,'jpg').src; Any Ideas?