Jquery-fileupload get original file size before resizing - javascript

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!

Related

Image source not changing with JavaScript

Please answer this question, as I am struggling a lot with it.
I am trying to change image source on mouse over. I am able to do it, but image is not displaying on page.
I am trying to change image source to cross domain URL. I can see that in DOM image source is changing but on page its not.
I have tried all solutions mentioned in LINK, but none of them is working.
Please let me solution to problem.
NOTE:
I can see in network tab image is taking some time to download (about 1 sec).
It is an intermediate issue, sometime image is loading and sometimes its not
CODE:
document.getElementsByTagName('img')[0].addEventListener('mouseover', function()
{
document.getElementsByTagName('img')[0].setAttribute('src', 'url/of/the/image');
});
have you tried loading images before everything else?
function initImages(){
var imC = 0;
var imN = 0;
for ( var i in Images ) imN++;
for(var i in Images){
var t=Images[i];
Images[i]=new Image();
Images[i].src=t;
Images[i].onload = function (){
imC++;
if(imC == imN){
console.log("Load Completed");
preloaded = 1;
}
}
}
}
and
var Images = {
one image: "path/to/1.png",
....
}
then
if( preloaded == 1 ){
start_your_page();
}
Here the code that will remove the img tag and replace it with a new one:
document.getElementsByTagName('img')[0].addEventListener('mouseover', function() {
var parent = document.getElementsByTagName('img')[0].parentElement;
parent.removeChild(document.getElementsByTagName('img')[0]);
var new_img = document.createElement("img");
new_img.src = "https://upload.wikimedia.org/wikipedia/commons/6/69/600x400_kastra.jpg";
parent.appendChild(new_img);
});
<img src="https://www.w3schools.com/w3images/fjords.jpg">
I resolved the issue using code:
function displayImage() {
let image = new image();
image.src="source/of/image/returned/from/service";
image.addEventListener('load', function () {
document.getElementsByTagName('img')[0].src = image.src;
},false);
}
Here in code, I am attaching load event to image, source of image will be changed after image is loaded.

Issue with image load recursive chain on slow network/mobile

So basically I have a page with a few sections. Each sections contains 5-30 image icons that are fairly small in size but large enough that I want to manipulate the load order of them.
I'm using a library called collagePlus which allows me to give it a list of elements which it will collage into a nice image grid. The idea here is to start at the first section of images, load the images, display the grid, then move on to the next section of images all the way to the end. Once we reach the end I pass a callback which initializes a gallery library I am using called fancybox which simply makes all the images interactive when clicked(but does not modify the icons state/styles).
var fancyCollage = new function() { /* A mixed usage of fancybox.js and collagePlus.js */
var collageOpts = {
'targetHeight': 200,
'fadeSpeed': 2000,
'allowPartialLastRow': true
};
// This is just for the case that the browser window is resized
var resizeTimer = null;
$(window).bind('resize', function() {
resetCollage(); // resize all collages
});
// Here we apply the actual CollagePlus plugin
var collage = function(elems) {
if (!elems)
elems = $('.Collage');
elems.removeWhitespace().collagePlus(collageOpts);
};
var resetCollage = function(elems) {
// hide all the images until we resize them
$('.Collage .Image_Wrapper').css("opacity", 0);
// set a timer to re-apply the plugin
if (resizeTimer) clearTimeout(resizeTimer);
resizeTimer = setTimeout(function() {
collage(elems);
}, 200);
};
var setFancyBox = function() {
$(".covers").fancybox({/*options*/});
};
this.init = function(opts) {
if (opts != null) {
if (opts.height) {
collageOpts.targetHeight = opts.height;
}
}
$(document).ready(function() {
// some recursive functional funk
// basically goes through each section then each image in each section and loads the image and recurses onto the next image or section
function loadImage(images, imgIndex, sections, sectIndex, callback) {
if (sectIndex == sections.length) {
return callback();
}
if (imgIndex == images.length) {
var c = sections.eq(sectIndex);
collage(c);
images = sections.eq(sectIndex + 1).find("img.preload");
return loadImage(images, 0, sections, sectIndex + 1, callback);
}
var src = images.eq(imgIndex).data("src");
var img = new Image();
img.onload = img.onerror = function() {
images[imgIndex].src = src; // once the image is loaded set the UI element's source
loadImage(images, imgIndex + 1, sections, sectIndex, callback)
};
img.src = src; // load the image in the background
}
var firstImgList = $(".Collage").eq(0).find("img.preload");
loadImage(firstImgList, 0, $(".Collage"), 0, setFancyBox);
});
}
}
From my galleries I then call the init function.
It seems like my recursive chain being triggered by img.onload or img.onerror is not working properly if the images take a while to load(on slow networks or mobile). I'm not sure what I'm missing here so if anyone can chip in that would be great!
If it isn't clear what is going wrong from the code I posted you can see a live example here: https://www.yuvalboss.com/albums/olympic-traverse-august-2017
It works quite well on my desktop, but on my Nexus 5x it does not work and seems like the finally few collage calls are not happening. I've spent too long on this now so opening this up to see if I can get some help. Thanks everyone!
Whooooo I figured it out!
Was getting this issue which I'm still unsure about what it means
[Violation] Forced reflow while executing JavaScript took 43ms
Moved this into the callback that happens only once all images are loaded
$(window).bind('resize', function() {
resetCollage(); // resize all collages
});
For some reason it was getting called early even if the browser never resized causing collage to get called when no elements existed yet.
If anyone has any informative input as to why I was getting this js violation would be great to know so I can make a better fix but for now this works :):):)

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

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.
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.

JS wait for CSS background image to load

It's easy to keep javascript waiting for some images to load if those are classic HTML images.
But I can't figure how to do the same if the image is loaded as a CSS backuground-image!
Is it possible?
The jQuery .load() method doesn't seem to apply.. and I'm short of ideas
It looks for elements with src attribute or backgroundImage css property and calls an action function when theirs images loaded.
/**
* Load and wait for loading images.
*/
function loadImages(images, action){
var loaded_images = 0;
var bad_tags = 0;
$(images).each(function() {
//alert($(this).get(0).tagName+" "+$(this).attr("id")+" "+$(this).css("display"));
var image = new Image();
var src = $(this).attr("src");
var backgroundImage = $(this).css("backgroundImage");
// Search for css background style
if(src == undefined && backgroundImage != "none"){
var pattern = /url\("{0,1}([^"]*)"{0,1}\)/;
src = pattern.exec(backgroundImage)[1];
}else{
bad_tags++;
}
// Load images
$(image).load(function() {
loaded_images++;
if(loaded_images == ($(images).length - bad_tags))
action();
})
.attr("src", src);
});
}
One alternate approach would be to fetch the image data via AJAX as a base64 encoded png and apply it to the element's background-image property.
For example:
$.get('/getmyimage', function(data) {
// data contains base64 encoded image
// for ex: data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==
$('#yourElement').css('background-image', 'url("' + data + '")');
});
You will also need a server side script that reads the image, converts it into base64 encoded png (and cache it maybe) and return the same.
Try this one...
Its a jQuery-Plugin which gives you control to wait for images to be loaded
Project-Home
Thread # SO
Official way to ask jQuery wait for all images to load before executing something
Answer # SO
(ShortLink)
this is untested code but try this:
$(document).ready(
function()
{
var imgSrc = $('theTargerElement').css('background-image');
var imgTag = $('<img>').attr('src',imgSrc).appendTo( 'body' );
}
);
$(document)
.load(
function()
{
// do stuff
}
);

Categories

Resources