I'm working on an AJAX function that receives image URLs. However, I won't be using a node append to insert it. I'm using innerHTML, which makes it difficult to get the file dimensions.
At the moment, I'm using a function which is returning somewhat mixed results. Sometimes it gets the actual dimensions, other times it returns "0" as the image dimensions.
This is my function:
var url = "http://placekitten.com.s3.amazonaws.com/homepage-samples/408/287.jpg";
var width = getDimensions(url)[0];
var height = getDimensions(url)[1];
var insert = '<img src="'+url+'" width="'+width+'" height="'+height+'" />';
function getDimensions(path) {
var img = new Image();
img.src = path;
return [img.width, img.height];
}
Not sure why it's acting inconsistently though. Does anyone have any suggestions?
I was thinking it might be something to do with the AJAX inserting the image before it loads the dimensions, although not really sure.
Here's a fiddle, which seems to work as expected, but like I said, it's inconsistent.
http://jsfiddle.net/aH5re/1/
EDIT
Here is a second fiddle with a much larger image. I noticed it's a lot more inconsistent than a smaller image file
http://jsfiddle.net/aH5re/2/
You'll have to wait for the image to finish loading before you can get the dimensions properly and reliably. What's currently happening is that it's returning the dimensions before the image is potentially fully loaded. If you have it already cached you may be getting correct dimensions but on a large image uncached you're not going to get reliable results.
Have a look at this demo about how you could perhaps achieve that.
http://jsfiddle.net/robschmuecker/aH5re/5/
Javascript:
var url = "http://www.hdwallpapers.in/download/transformers_4_age_of_extinction-2560x1440.jpg";
var div = document.querySelector('div');
alert('loading image now');
var button = document.querySelector('.test');
getDimensions(url);
button.addEventListener('click', function () {
div.innerHTML = insert;
});
function getDimensions(path) {
var img = new Image();
img.src = path;
img.onload = function () {
alert('loaded');
var width = img.width;
var height = img.height;
insert = '<img src="' + url + '" width="' + width + '" height="' + height + '" />';
button.disabled = false
};
}
Related
I need to save an image after using CSS filters on the client-side (without using a backend). What I have so far:
Use CSS filters
Convert to canvas
Save with var data = myCanvas.toDataURL("image/png");
Crying. Image was saved without effects.
Index.html
<div class="large-7 left">
<img id="image1" src="./img/lusy-portret-ochki-makiyazh.jpg"/><br>
<canvas id="myCanvas"></canvas>
</div>
Photo.js
var buttonSave = function() {
var myCanvas = document.getElementById("myCanvas");
var img = document.getElementById('image1');
var ctx = myCanvas.getContext ? myCanvas.getContext('2d') : null;
ctx.drawImage(img, 0, 0, myCanvas.width, myCanvas.height);
var grayValue = localStorage.getItem('grayValue');
var blurValue = localStorage.getItem('blurValue');
var brightnessValue = localStorage.getItem('brightnessValue');
var saturateValue = localStorage.getItem('saturateValue');
var contrastValue = localStorage.getItem('contrastValue');
var sepiaValue = localStorage.getItem('sepiaValue');
filterVal = "grayscale("+ grayValue +"%)" + " " + "blur("+ blurValue +"px)" + " " + "brightness("+brightnessValue+"%)" + " " + "saturate(" + saturateValue +"%)" + " " + "contrast(" + contrastValue + "%)" + " " + "sepia(" + sepiaValue + "%)" ;
$('#myCanvas')
.css('filter',filterVal)
.css('webkitFilter',filterVal)
.css('mozFilter',filterVal)
.css('oFilter',filterVal)
.css('msFilter',filterVal);
var data = myCanvas.toDataURL("image/png");
localStorage.setItem("elephant", data);
if (!window.open(data)) {
document.location.href = data;
}
}
However, this produces an image without any filters.
There is a little known property on the context object, conveniently named filter.
This can take a CSS filter as argument and apply it to the bitmap. However, this is not part of the official standard and it only works in Firefox so there is the limitation.. This has since this answer was originally written become a part of the official standard.
You can check for the existence of this property and use CSS filters if it does, or use a fallback to manually apply the filters to the image if not. The only advantage is really performance when available.
CSS and DOM is a separate world from the bitmaps that are used for images and canvas. The bitmaps themselves are not affected by CSS, only the elements which acts as a looking-glass to the bitmap. The only way is to work with at pixel levels (when context's filter property is not available).
How to calculate the various filters can be found in the Filter Effects Module Level 1. Also see SVG Filters and Color Matrix.
Example
This will apply a filter on the context it self. If the filter property does not exist a fallback must be supplied (not shown here). It then extracts the image with applied filter as an image (version to the right). The filter must be set before next draw operation.
var img = new Image();
img.crossOrigin = "";
img.onload = draw; img.src = "//i.imgur.com/WblO1jx.jpg";
function draw() {
var canvas = document.querySelector("canvas"),
ctx = canvas.getContext("2d");
canvas.width = this.width;
canvas.height = this.height;
// filter
if (typeof ctx.filter !== "undefined") {
ctx.filter = "sepia(0.8)";
ctx.drawImage(this, 0, 0);
}
else {
ctx.drawImage(this, 0, 0);
// TODO: manually apply filter here.
}
document.querySelector("img").src = canvas.toDataURL();
}
canvas, img {width:300px;height:auto}
<canvas></canvas><img>
CSS filters applied to the canvas will not be applied to the image that is produced. You either need to replicate the filters in canvas or rather re apply the same filters to the generated image.
Try putting the generated image data into the source of an img tag & apply the same filters.
Your CSS properties are not actually applied to the canvas data. Think of the CSS as being another layer placed over the canvas element. You can implement your own image filters by using context.getImageData to get an array of raw RGBA values, then do your filter work and then write it back with context.putImageData. However, I think you really just want to save the output of the CSS filters. You may be able to do this using a tool like rasterizeHTML
Note, if src of img is not located at same origin calling var data = myCanvas.toDataURL("image/png") , may cause error
Uncaught SecurityError: Failed to execute 'toDataURL' on 'HTMLCanvasElement': tainted canvases may not be exported.
Note also that image at html at Question appear to be type jpg , not png
<img id="image1" src="./img/lusy-portret-ochki-makiyazh.jpg"/>
A possible "workaround" could be to set img src as a data URI of image ; calling
var data = myCanvas.toDataURL("image/jpg")
Though as noted , at Answers above , would not appear to preserve css filter set at img element.
Note, "workaround" ; "save image" here , would be "save html" ; as the "download" would be an objectURL of the DOM html img element.
Note also , img src within saved html file will still be original local or external src of image ; if not converted to data URI before loading.
Approach is to set window.location.href as an objectURL reference to DOM img element outerHTML , which should preserve style attribute set at .css("[vendorPrefix]-filter", filterVal)
Try utilizing URL.createObjectURL , URL.revokeObjectURL ; setting css filter at img , instead of canvas element ; creating Blob of img outerHTML , type:text/html ; create reference to URL.createObjectURL: objURL ; set window.location.href to objURL ;
call URL.revokeObjectURL on objectURL reference objURL
var buttonSave = function() {
var img = document.getElementById("image1");
// filters
var grayValue = "0.2";
var blurValue = "1px";
var brightnessValue = "150%";
var saturateValue = "0.2";
var contrastValue = "0.2";
var sepiaValue = "0.2";
// `filterVal`
var filterVal = "grayscale(" + grayValue + ") "
+ "blur(" + blurValue + ") "
+ "brightness(" + brightnessValue + ") "
+ "saturate(" + saturateValue + ") "
+ "contrast(" + contrastValue + ") "
+ "sepia(" + sepiaValue + ")";
// set `img` `filter` to `filterVal`
$(img)
.css({
"webkit-filter": filterVal,
"moz-filter": filterVal,
"ms-filter": filterVal,
"o-filter": filterVal
});
// create `blob` of `img` `outerHTML` ,
// `type`:`text/html`
var blob = new Blob([img.outerHTML], {
"type": "text/html"
});
// create `objectURL` of `blob`
var objURL = window.URL.createObjectURL(blob);
console.log(objURL);
// download `filtered` `img` as `html`
var download = $("<a />", {
"download": "image-" + $.now(),
"href": objURL,
// notify file is type `html` , not image
"title":"click to download image as `html` file"
}).appendTo("body");
$(img).appendTo("a");
$("a").on("click", function() {
// set `location.href` to `objURL`
window.location.href = objURL;
$(window).one("focus", function() {
// revoke `objURL` when `window` regains `focus`
// after "Save as" dialog
window.URL.revokeObjectURL(objURL);
});
});
}
window.onload = buttonSave;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<div class="large-7 left">
<img id="image1" src="http://lorempixel.com/200/200/cats" />
</div>
How can I check an image width and height if I only have the URL of the image, and not the image itself?
i.e. Url might be something like
http://www.myadvertiserprovider.com/images/myuserid/ad_image.png
What I am trying to do is to skip inserting an ad into my page if the image dimensions are not exactly what I am expecting. I don't want to resize the image, I require the image to be the exact dimensions that I am expecting.
You will have to load the image. You can try something like
var img = new Image();
img.onload = function () {
alert("height: " + img.height + " width:" + img.width);
};
img.src = "https://www.gravatar.com/avatar/d17c95dfa5820a212d979da58bc3435c?s=128&d=identicon&r=PG";
DEMO
This cannot be done client-side without loading the image, unless the you request that the size of the image is written in the URI, something like image200x350.jpg.
If you want to load the image and check the image before placing it into your document:
var image = new Image();
image.onload = function() {
console.log("Height: " + image.height + ", Width: " + image.width);
}
image.src = "http://tes.jpl.nasa.gov/css/homeWelcome.png";
I want to add an image by Javascript, then calculating the html element width as
window.onload=function(){
document.getElementById('x').addEventListener('click', function(e){
var el = document.getElementById('xx');
el.innerHTML = '<img src="img.jpg" />';
var width = el.offsetWidth;
.....
}, false);
}
but since JavaScript conduct all processes simultaneously, I will get the width of the element before loading the image. How can I make sure that the image has been loaded into the content; then calculating the element width?
UPDATE: Thanks for the answers, but I think there is a misunderstanding. img src="img.jpg" /> does not exist in the DOM document. It will be added later by Javascript. Then, when trying to catch the element by Id, it is not there probably.
You can give the img an ID and do the following :-
var heavyImage = document.getElementById("my-img");//assuming your img ID is my-img
heavyImage.onload = function(){
//your code after image is fully loaded
}
window.onload=function(){
document.getElementById('x').addEventListener('click', function(e){
var el = document.getElementById('xx');
var img = new Image();//dynamically create image
img.src = "img.jpg";//set the src
img.alt = "alt";
el.appendChild(img);//append the image to the el
img.onload = function(){
var width = el.offsetWidth;
}
}, false);
}
This is untested, but if you add the image to the DOM, set an onload/load event-handler and then assign the src of the image, the event-handling should fire (once it's loaded) and allow you to find the width.
This is imperfect, though, since if the image is loaded from the browser's cache the onload/load event may not fire at all (particularly in Chromium/Chrome, I believe, though this is from memory of a bug that may, or may not, have since been fixed).
For the chrome bug you can use the following:-
var BLANK = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==';//create a blank source
var tImg = document.getElementById("my-img");//get the image
var origSrc = tImg.src;//get the original src
tImg.src = BLANK;//change the img src to blank.
tImg.src = origSrc;//Change it back to original src. This will lead the chrome to load the image again.
tImg.onload= function(){
//your code after the image load
}
You can use a library called PreloadJS or you can try something like this:
//Somewhere in your document loading:
loadImage(yourImage, callbackOnComplete);
function loadImage(image, callbackOnComplete){
var self = this;
if(!image.complete)
window.content.setTimeout(
function() { self.loadImage(image, callbackOnComplete)}
,1000);
else callbackOnComplete();
}
I did this when I worked with images base64 which delay on loading.
Im sure this has got to be something simple that I am overlooking, but I can't seem to get my canvas to display an jpg stored on the server.
<img id="test_img" alt="test" src="/media/tmp/a4c1117e-c310-4b39-98cc-43e1feb64216.jpg"/>
<canvas id="user_photo" style="position:relative;"></canvas>
<script type="text/javascript">
var image = new Image();
image.src = "/media/tmp/a4c1117e-c310-4b39-98cc-43e1feb64216.jpg";
var pic = document.getElementById("user_photo");
pic.getContext('2d').drawImage(image, 0, 0);
</script>
the <img> displays as expected, however the canvas is blank, though it does seem to have the correct dimensions. Any one see what I'm doing wrong?
My tired eyes will appreciate any help.
Thanks
you may want to use the following approach
image.onload = function() {
pic.getContext('2d').drawImage(image, 0,0);
}
so you ensure that the image is loaded when trying to draw it.
var initialFloorplanWidth = 0;
var initialFloorplanHeight = 0;
var canvasImage = new Image();
documentReady = function () {
preloadFloorplan();
}
preloadFloorplan = function () {
onLoad = function () {
initialFloorplanHeight = canvasImage.height;
initialFloorplanWidth = canvasImage.width;
var canvasHtml = '<canvas id="MainCanvas" width="' + initialFloorplanWidth + '" height="' + initialFloorplanHeight + '">Canevas non supportés</canvas>';
$("#MainContainer").append(canvasHtml);
var canvas = $("#MainCanvas")[0];
var canvasContext = canvas.getContext("2d");
canvasContext.drawImage(canvasImage, 0, 0);
}
canvasImage.onload = onLoad;
canvasImage.src = initialFloorplan;
}
This code works well.
Try doing that when the document is loaded. I have a feeling your code is running before the image is available. You can also detect when the img itself is loaded. See this.
Maybe it's something to do with the rest of your code. Is "user_photo" identified in the code?
I need to get the width & height of a CSS background image and inject it into document.ready javascript. Something like:
$(document).ready(function(){
img = new Image();
img.src = "images/tester.jpg";
$('body').css('background', 'url(' + img.src + ')');
$('body').css('background-size', img.width + 'px' + img.height + 'px');
});
The problem is, the image width and height aren't loaded in at the time of document.ready, so the values are blank. (They're accessible from console, but not before).
img.onload = function() { ... } retrieves the width and height, but DOM $(element) calls aren't accessible from within img.onload.
In short, I'm a little rusty on my javascript, and can't figure out how to sync image params into the DOM. Any help appreciated
EDIT: jQuery version is 1.4.4, cannot be updated.
You could use $.holdReady() to prevent jQuery's ready method from firing until all of your images have loaded. At that point, their width's and height's would be immediately available.
Star by calling $.holdReady(true). Within the onload method of each image, check to see how many images have been loaded all together, and if that matches the number of expected images, you can $.holdReady(false) to fire the ready event.
If you don't have access to $.holdReady(), you could simply wait to spit out your HTML until all of the images have loaded by still calling a function:
var images = { 'loaded': 0,
'images': [
"http://placekitten.com/500/500",
"http://placekitten.com/450/450",
"http://placekitten.com/400/400",
"http://placekitten.com/350/340",
"http://placekitten.com/300/300",
"http://placekitten.com/250/250",
"http://placekitten.com/200/200",
"http://placekitten.com/150/150",
"http://placekitten.com/100/100"
]};
function outputMarkup() {
if ( ++images.loaded === images.images.length ) {
/* Draw HTML with Image Widths */
}
}
for ( var i = 0; i < images.images.length; i++ ) {
var img = new Image();
img.onload = function(){
outputMarkup();
};
img.src = images.images[i];
}