Getting an image width and height from Phonegap before upload - javascript

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.

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.")
})
})
}

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!

I think you can use target width and height of getPicture() to limit the maximum dimension.
If you need to send them to server, I think server code would help to get those dimension.
If you really need to get those dimension by js, you can
var img = new Image;
img.onload = function(){
myCanvasContext.drawImage(img,0,0);
};
img.src = "data:YOUR_BASE64_DATA";
And you can do it with img

1.Phonegap supply a way to specific the size of the image you choose
Click here to see the options
2.If you need to know the original size and do not want to specific, you may try the code below:
function got_image(image_uri) {
window.resolveLocalFileSystemURI(image_uri, function(fileEntry) {
fileEntry.file(function (fileObj) {
var fileName = fileObj.fullPath;
var originalLogo = new Image();
originalLogo.src =fileName;
//get the size by: originalLogo.width,originalLogo.height
});
})
}

one way you can do this is by using the MediaFile from the Capture API.
var mediaFile = new MediaFile("myfile.jpg", "/path/to/myfile.jpg");
mediaFile.getFormatData(function(data) {
console.log("width: " data.width);
console.log("height: " data.height);
});
Should be a lot less code than the current accepted solution.

Related

Jquery-fileupload get original file size before resizing

I am using blueimp/jQuery-File-Upload plugin to upload and resize the images on client side on my website.
I need a way to get origonal uploaded image dimensions before it is resized to my provided values in imageMaxWidth and imageMaxHeight options.
Any help or guidance will be great, or i can edit the library and add this hook if it is not already there to return original file data.
Thanks in advance.
Just discovered something without adding custom hooks:
Just override add method and calculate image dimensions from file object as such:
add: function(e, data) {
var img = new Image;
var _URL = window.URL || window.webkitURL;
img.onload = function() {
sizes =
width: this.width
height: this.height
};
img.src = _URL.createObjectURL(data.files[0]);
//below code is to let the library further process file e.g resize etc
var $this = $(this);
return data.process(function() {
return $this.fileupload('process', data);
}).done(function() {
return data.submit();
});
}
And here you have it, in the sizes hash.
Cheers!

How to generate "screenshot" of html div with external images?

I have a HTML div with external images. (The following is an example, but in the actual case I am using Amazon S3, so downloading and storing the image on the same server is not an option) Currently I am using html2canvas to convert the div to image. However, the external image is always replaced by a blank space.
The code I use to capture the image:
$(function() {
$("#btnSave").click(function() {
html2canvas($("#widget"), {
onrendered: function(canvas) {
theCanvas = canvas;
document.body.appendChild(canvas);
// Convert and download as image
Canvas2Image.saveAsPNG(canvas);
$("#img-out").append(canvas);
}
});
});
});
Edited: jsfiddle: https://jsfiddle.net/0y2zxxL8/3/
I may use other library. I may also do that in backend. (I am using PHP + laravel 5 for backend) Is there a way I can generate a "screenshot" of the HTML div with external images?
Update The current answer are working after editing. Yet, for my actual use, there will be multiple image with their position set by the user by drag and drop. I can still get the position, but it would be better for me if it is possible to not set the position specifically.
Your JSFiddle given ReferenceError: Canvas2Image is not defined while hit on 'Save PNG' button. So check your code(not fiddle) for same error.
UPDATE
See this JSFiddle example as reference. May this one will help you.
UPDATE 2
I place some code into your one, check it out. Hope this will be your solution..!
Working result with FF v44 and its working. Taken snap with JSFiddle code
$(function() {
$("#btnSave").click(function() {
html2canvas($("#widget"), {
onrendered: function(canvas) {
var context=canvas.getContext("2d"); // returns the 2d context object
var img=new Image() //creates a variable for a new image
img.src= "http://lorempixel.com/400/200/"; // specifies the location of the image
context.drawImage(img,0,50); // draws the image at the specified x and y location
// Convert and download as image
theCanvas = canvas;
document.body.appendChild(canvas);
// Convert and download as image
Canvas2Image.saveAsPNG(canvas);
$("#img-out").append(canvas);
}
});
});
});
UPDATE 3 (12/29/2016) JSFiddle
After research, found that the problem is because we are only assigning the image source which is only pass message to the browser to retrieve the data.
Further image element is may be not really accessible with the browser when click to draw canvas from it. We are just tell code to load it and it's done.
Change code to solve OP's facing chrome issue like below:
img.onload = function() {
context.drawImage(img, 0, 50);// draws the image at the specified x and y location
}
UPDATE 4 JSFiddle
Make image position dynamic based on OP requirement.
onrendered is no longer working..
i solved this problem by adding "allowTaint" option
{ allowTaint: true }
2018 solution:
html2canvas(document.getElementById('result'), { allowTaint: true }).then(function (canvas) {
document.body.appendChild(canvas);
});
You may try to scan the image source for external urls and change them to your website and load them with php.
Something like
$(function() {
var imageproxy = "http://example.com/imageproxy.php"; //Change this
var mydomain = new RegExp(location.host);
$("#btnSave").click(function() {
$("#widget").find('img').each(function(){
var img_src = $(this).attr('src');
if(!mydomain.test(img_src)){
$(this).attr('src', imageproxy + "?url=" + encodeURIComponent(img_src));
}
});
html2canvas($("#widget"), {
onrendered: function(canvas) {
var link = $('<a target="_blank">Download</a>');
link.attr('download', 'test.png');
link.attr('href', canvas.toDataURL());
$("#btnSave").after(link);
}
});
});
});
imageproxy.php
<?php
if(!empty($_GET['url'])){
$url = urldecode($_GET['url']);
$img_type = "image/jpeg";
$chunks = explode('.', $url);
if(is_array($chunks) && count($chunks) > 1){
$ext = end($chunks);
switch ($ext){
case 'jpg':
case 'jpeg':
$img_type = "image/jpeg";
break;
case 'png':
$img_type = "image/png";
break;
case 'gif':
$img_type = "image/gif";
break;
}
}
$img = file_get_contents($url);
header ("Content-Type: $img_type");
echo $img;
}
note: php script is very simple, image detection is not working 100%, this is just ti give you an idea. If you use some php image libs to load and get image type you can do this just with few lines of code. you may also try with "php readfile".

How can I get the width and height of an image before completely loaded with JavaScript? [duplicate]

This question already has answers here:
Get image dimensions with Javascript before image has fully loaded
(3 answers)
Closed 6 years ago.
I tried to get the actual size of images before they are displayed on HTML, and I do use this in most cases:
var imgae = new Image();
image.src = img.src;
image.onload = function() {
// Do something with image.width and image.height
// and insert an <img> into <body>
}
However when the image is too large so that it may take seconds to download, users have to wait until it completes before seeing the image. Is there any way where I can get the information before Image.onload is triggered (and of cause after the meta data of image is loaded), so that I can show part of it on the page?
If you are using jQuery and you are requesting image sizes you have to wait until they load or you will only get zeroes.
$(document).ready(function() {
$("img").load(function() {
alert($(this).height());
alert($(this).width());
});
});
If you are using jQuery 3.0 remember that load method was removed, use
$('img').on('load', function() {})
var _URL = window.URL || window.webkitURL;
function displayPreview(files) {
var file = files[0]
var img = new Image();
var sizeKB = file.size / 1024;
img.onload = function() {
$('#preview').append(img);
alert("Size: " + sizeKB + "KB\nWidth: " + img.width + "\nHeight: " + img.height);
}
img.src = _URL.createObjectURL(file);
}
You can make your function asynchronous with simply using an appropriate callback:
function loadImages(imgsrc, callback) {
var image = new Image();
image.onload = callback;
image.src = imgsrc;
}
and then you can call this function easily like this
loadImages('you image src', function() {
// whatever code to be executed
});
Hope if works for you.

Javascript image onload not firing when loading from local file

I'm trying to give the user a preview of how an image will look when combined with another image before they upload the image (think gun shooting a bullet). I can get the image to load into an image element, but then the onload event doesn't fire (tested in chrome and firefox). I've tried using setTimeout as a dirty hack, but unfortunately bullet.image.height does not appear to be set within a relatively short space of time.
Here is an example of what I'm trying to do:
if (input.target.files && input.target.files[0]) {
var file = new FileReader();
file.onload = function (event) {
// this part works fine
var bullet = {};
bullet.id = 0;
bullet.image = new Image();
bullet.image.onload = function () {
// This never fires
bullet.offset_y = bullet.image.height / 2;
$('#modal-weapons-field-bullet').append('<option value="0">' + bullet.title + '</option>');
$('#modal-weapons-field-bullet').val(0);
};
bullet.src = event.target.result;
bullet.offset_x = 0;
bullet.title = input.target.files[0].name;
}
file.readAsDataURL(input.target.files[0]);
}
bullet.src should be bullet.image.src

Checking if an image is missing from folder in javascript

I am making a small slide show application to show images inside an html.
The name of images are something like:
"MOD01_001.jpg"
"MOD01_002.jpg"
"MOD01_004.jpg" and so for...
Sometimes one or more images is missing and the previous images still is in the cache, so I can't check if the new image was loaded checking for the width/height properties.
What can I do to check if an images are missing from the list (I know I can't access the file info from inside client browser).
TIA
This loads them all in, so it could be really terrible:
var images = ['MOD01_001.jpg','MOD01_002.jpg','MOD01_003.jpg'];
for (i in images) {
checkIfImageExists(images[i]);
}
function checkIfImageExists(image_path) {
var img = new Image();
img.onerror = function(){
console.log('Could not load image: ' + img.src);
}
img.onload = function(){
console.log('Loaded image: ' + img.src);
}
img.src = image_path;
}

Categories

Resources