Virus721
Virus721

Reputation: 8315

Uploading DOM image with Ajax - Convert Image to File?

I need to make an image upload. Before the image is uploaded, i take it from the file input, resize it using a canvas, and save the result as an image element in the DOM. How can i turn my Image object to a file Object so i can upload it using ajax ?

EDIT:

Here is what i did :

$.fitIn = function( size, bbox ) {

    var r = size.w / size.h;

    if( r > bbox.w / bbox.h ) {
        var newW = bbox.w,
            newH = newW / r;

    } else {
        var newH = bbox.h,
            newW = newH * r;
    }

    return { w: newW, h: newH };
};

$.resizeImage = function( image, newW, newH, outputFormat ) {

    if( null == outputFormat ) {
        var temp = image.src.split( '.' );
        outputFormat = temp[temp.length - 1];
    }

    var canvas = document.createElement( 'canvas' );
    canvas.width = newW;
    canvas.height = newH;

    var context = canvas.getContext( '2d' );
    context.drawImage( image, 0, 0, newW, newH );

    var newImage = document.createElement( 'img' );
    newImage.src = canvas.toDataURL( 'image/' + outputFormat );

    return newImage;
};

$.createThumb = function( image ) {

    var newSize = $.fitIn(
        { w: image.width, h: image.height },
        { w: THUMB_W, h: THUMB_H }
    );

    return $.resizeImage( image, newSize.w, newSize.h, THUMB_FORMAT );
};

And then :

var originalImage = document.getElementById('testImage');
var newImage = lwf.resizeImage(originalImage, 480, 270);

($ isn't jquery)

Thanks for your help :)

Upvotes: 3

Views: 1281

Answers (1)

lucassp
lucassp

Reputation: 4167

You can use canvas.toDataURL() to get a base64 encoded string out if it. Send that to the server, decode it and save it as a file.

Upvotes: 2

Related Questions