Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to create HTML 5 File from image (<img>) already loaded?

Hi I have a page where I show user's profile image that is loaded like this:

$("#imgProfile").attr('src', 'http://myserver/user.png')

Now I need to submit this image using HTML 5 File API, but to do this I need to first convert my image to File API. All the samples that I saw at internet work together with input type="file", but I already have that image, I'm not choosing the image from local computer.

All the examples like this one https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications use File API from input type="file" element

like image 805
Gustavo Lira Avatar asked May 20 '15 21:05

Gustavo Lira


1 Answers

The file is already on your server. You can use it, as Yair Nevet's answer says.

If you really want to make it a File object, maybe you can use this(I don't know if it works).

var getFilelikeBlobFromImageElement = (function closure() {
        var canvasElement = document.createElement("canvas");

        return function(imageElement) {
                canvasElement.width = imageElement.width;
                canvasElement.height = imageElement.height;
                var canvasContext = canvasElement.getContext("2d");
                canvasContext.drawImage(imageElement, 0, 0);

                var imageData = canvasContext.getImageData(0, 0, imageElement.width, imageElement.height).data;
                var buffer = new Uint8Array(imageData.length);
                for(var index = 0; index < imageData.length; index++)
                    buffer[index] = imageData[index];

                var imageBlob = new Blob(buffer);
                imageBlob.lastModifiedDate = new Date();
                imageBlob.name = /\/([^\/]+)$/.exec(imageElement.src)[1];

                return imageBlob; // A `File`-like `Blob` object.
            };
    })();

Usage:

getFilelikeBlobFromImageElement(document.getElementById("imgProfile"));

To get the Blob from a <canvas>

To make a Blob File-like

like image 149
Константин Ван Avatar answered Oct 04 '22 19:10

Константин Ван