Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript

Jorge Guzman
PLUS
Jorge Guzman
Courses Plus Student 21,390 Points

How to create an image file from a dataURL? - JavaScript

I am trying to upload pictures to Parse.com, I do not have the files, but the dataURL's (because I resized the images), but need an image file to upload.

Any tip is welcome.

Here is the code for further details:

// First want to resize the image, where the result is a dataURL
var dataURL;
function resizePicture(file) {    // This file is the original image
    var reader = new FileReader();
    reader.onloadend = function() {
        var tempImg = new Image();
        tempImg.src = reader.result;
        tempImg.onload = function() {
            var MAX_WIDTH = 100;
            var MAX_HEIGHT = 150;
            var tempW = tempImg.width;
            var tempH = tempImg.height;
            if (tempW > tempH) {
                if (tempW > MAX_WIDTH) {
                    tempH *= MAX_WIDTH / tempW;
                    tempW = MAX_WIDTH;
                }
            } else {
                if (tempH > MAX_HEIGHT) {
                    tempW *= MAX_HEIGHT / tempH;
                    tempH = MAX_HEIGHT;
                }
            }
            var canvas = document.createElement('canvas');
            canvas.width = tempW;
            canvas.height = tempH;
            var ctx = canvas.getContext("2d");
            ctx.drawImage(this, 0, 0, tempW, tempH);
            dataURL = canvas.toDataURL("image/jpeg"); // How can I convert this dataURL to an image file?
        }
    }
    reader.readAsDataURL(file);
}

// Then,  want to upload the image to Parse.com. 
function savePicture() {
    var name = "productPicture.jpg";
    var parseFile = new Parse.File(name, dataURL); // Here instead of dataURL, I need an image file.
    parseFile.save().then(function() {
            // successful save
        }, function(error) {
            alert("The file either could not be read, or could not be saved to Parse.");
    });
}