Convert a File object to an Image object in JavaScript

So, I have a website (using AngularJS) that allows users to upload files via a tag

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

When I handle the loading in the controller, the image becomes stored as a File object. This is my method, which saves the file and also sets variables for previewing 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'm trying to compress the image using the JIC library found here: https://github.com/brunobar79/JIC/blob/master/src/JIC.js

But this library takes an image object as its parameter and returns it as a compressed image object. I can't seem to find a way to convert the $ scope.image File object to an Image object. How can i do this?

, Azure.

+4
1

Image src URL- . JIC:

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

canvas , URL- Image, src URL- . , , src atob, , base64, Blob. Blob , File, , 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
+5

Source: https://habr.com/ru/post/1648655/


All Articles