Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting an image width and height from Phonegap before upload

This should be easy but I can't find the answer. I need to get the width and height of an image, grabbed via a fileURI in Phonegap, before uploading it to our server. Certainly there's got to be some html5 / Phonegap magic that will do this before uploading. Here is some really reduced code to show where I'm at:

function got_image(image_uri) {
    // Great, we've got the URI
    window.resolveLocalFileSystemURI(image_uri, function(fileEntry) {
        // Great, now we have a fileEntry object.
        // How do we get the image width and height?
    })
}

// Get the image URI using Phonegap
navigator.camera.getPicture(got_image, fail_function, some_settings)

Any idea what the missing piece is? I wish I had Simon MacDonald or Shazron on speed dial, but I do not.

like image 510
Ryan Martin Avatar asked Feb 28 '13 02:02

Ryan Martin


2 Answers

Here is a proper solution.

Pass this function an imageURI. URIs are returned from both of PhoneGap's getPicture() methods.

Like this: get_image_size_from_URI(imageURI)

function get_image_size_from_URI(imageURI) {
    // This function is called once an imageURI is rerturned from PhoneGap's camera or gallery function
    window.resolveLocalFileSystemURI(imageURI, function(fileEntry) {
        fileEntry.file(function(fileObject){
            // Create a reader to read the file
            var reader = new FileReader()

            // Create a function to process the file once it's read
            reader.onloadend = function(evt) {
                // Create an image element that we will load the data into
                var image = new Image()
                image.onload = function(evt) {
                    // The image has been loaded and the data is ready
                    var image_width = this.width
                    var image_height = this.height
                    console.log("IMAGE HEIGHT: " + image_height)
                    console.log("IMAGE WIDTH: " + image_width)
                    // We don't need the image element anymore. Get rid of it.
                    image = null
                }
                // Load the read data into the image source. It's base64 data
                image.src = evt.target.result
            }
            // Read from disk the data as base64
            reader.readAsDataURL(fileObject)
        }, function(){
            console.log("There was an error reading or processing this file.")
        })
    })
}
like image 192
Ryan Martin Avatar answered Oct 14 '22 06:10

Ryan Martin


The following code solves the same problem for me today (tested on iOS):

function got_image(image_uri)
{       
    $('<img src="'+image_uri+'"/>').on('load',function(){
        alert(this.naturalWidth +" "+ this.naturalHeight);
    });
}

Hope it helps!

like image 28
conca Avatar answered Oct 14 '22 08:10

conca