I'm working on a swipe-able wine image viewer for NapaWapa.com and I've got it working pretty well: http://www.tonyjacobson.com/napawapa/gallery/index.html
I'm using a jquery plugin to read the exif data of the images in the gallery. However, the plugin seems to only work when the src attribute is hard coded — not when the images are loaded via AJAX. Can any of you experts out there take a peek at the JS (http://www.tonyjacobson.com/napawapa/gallery/js/jquery.exif.js) to see if you could recommend a change to the plugin code to recommend a fix?
Here's the specific part of the plugin code where it deals with reading the EXIF data:
// HTML IMG EXAMPLE
<img class="lazyOwl" data-src="images/03.jpg" exif="true" />
// JAVASCRIPT CLICK TO TEST IMG EXIF DATA
$("img").on('click', function(event){
$(this).exifLoad();
console.log( "HIT: " + $(this).exif('Make') );
});
// JQUERY PLUGIN CODE EXCERPT
function loadAllImages()
{
var aImages = document.getElementsByTagName("img");
for (var i=0;i<aImages.length;i++) {
if (aImages[i].getAttribute("exif") == "true") {
if (!aImages[i].complete) {
addEvent(aImages[i], "load",
function() {
EXIF.getData(this);
}
);
} else {
EXIF.getData(aImages[i]);
}
}
}
}
// automatically load exif data for all images with exif=true when doc is ready
jQuery(document).ready(loadAllImages);
// load data for images manually
jQuery.fn.exifLoad = function(fncCallback) {
return this.each(function() {
EXIF.getData(this, fncCallback)
});
}
I was searching for a similar question, and found assistance from this thread. Try modifying your Javascript (not the plugin) to include this code:
$("img").load(function() {
$(this).exifLoad(function() {
// exif data should now be ready...
});
});
Related
Bit of a long shot, but is there a javascript function/process which allows automatically takes a screenshot of a specified area, and outputs a picture to a folder on my computer. Ideally, it would be able to put within a loop so that it takes a picture for each loop iteration.
Is this at all remotely possible?
If you have a web server with PHP installed, you can simulate this using wkhtmltoimage. To generate a new file every 5 seconds, your JS would be:
$(document).ready(function() {
function takeImage() {
$.post(
'htmltoimage.php',
{ currentUrl : window.location + "?stopTimer=1" }, // data that your script might need
function(data) {
if (data.url !== undefined) {
console.log("The URL where you can download your image is " + data.url);
}
},
'json' // use JSON for expected return type
);
}
var startTimer = <?php echo (isset($_POST['stopTimer']) ? "false" : "true"); ?>
if (startTimer) { setTimeout(takeImage, 5000); }
});
Your PHP file would simply use wkhtmltoimage to go to your URL. In its most simple form:
<?php
function() {
$outputLocation = "/images/output_" . strtotime(date()) . ".png";
// assuming wkhtmltoimage is in your PATH (otherwise specify full path to executable below)
`wkhtmltoimage $_POST['currentUrl'] $outputLocation`;
return array('url' => $outputLocation);
}
?>
You can then crop it at the positions you desire using ImageMagick or a similar PHP image processing library.
This can also be achieved using Adobe AIR, or really any program that uses WebKit.
Yes, you can. There is a useful library for that. You might want to take a look:
http://phantomjs.org/screen-capture.html
Since PhantomJS is using WebKit, a real layout and rendering engine,
it can capture a web page as a screenshot. Because PhantomJS can
render anything on the web page, it can be used to convert contents
not only in HTML and CSS, but also SVG and Canvas.
Hope it helps.
I am in the current situation:
I am developing a site for publishing my photos. I am using twitter bootstrap, jquery and Galleria.io
Now i want to show some exif data from the photos i made. Therefore i want to use this jquery plugin: http://blog.nihilogic.dk/2008/05/jquery-exif-data-plugin.html
I have already tested the examples give on the side. They work.
The code below doesn't. It returns an empty alert, everytime the image is loaded.
So at least this works.
These are my first steps in javascript, so i am glad for every help.
The exif data should be updated everytime I change the image. All images are located on the same server.
Galleria.ready(function(options) {
// this = the gallery instance
// options = the gallery options
this.bind('image', function(e) {
imgHandle = $(e.imageTarget)
imgHandle.load(function() {
$(this).exifLoad(function() {
alert($(this).exifPretty());
});
});
});
});
$("#img2").load(function() {
$(this).exifLoad(function() {
alert($(this).exifPretty());
});
});
I hope you can help me.
Okay i figured it out with a friend:
My code now looks like this:
Galleria.ready(function(options) {
// this = the gallery instance
// options = the gallery options
// will be called after the image is loaded
this.bind('image', function(e) {
imgHandle = e.imageTarget;
alert('Image loaded');
//will be called if on same server
$(imgHandle).exifLoad(function() {
alert('Exif loaded');
alert($(imgHandle).exifPretty());
//do something here....
});
});
});
});
And it works only with images on the server but not on remote servers.
So, I know how to use JS or jQuery, etc., to display a "Loading" message while content is loading. I have created a fairly large webapp with a number of JS dependencies and I want to display a "loading" message while all the scripts are loading.
My head tag has a number of <script src=…> tags in it and I want to display a loading message instantly when the user visits the page, and then remove it when all the scripts are loaded.
What's the best way to do this?
Then use $ajax function of jquery to download this javascript files and the add script element in head tag after downloading completes.
like this:
// display loading message here
$ajax("javascriptfile.js",function(file){
// attach downloaded file to head tag now
});
You probably need to lazy loading of the script. The last example from this Lazy Loading show to load .js via YUI. The code from that example is included below for your reference:
var HelloWorld = {
is_loaded: false,
lazyLoad: function(callback) {
var loader = new YAHOO.util.YUILoader();
loader.addModule({
name: "helloworld",
type: "js",
fullpath: "yui_ex/helloworld.js"
});
loader.require("helloworld");
if (callback) {
loader.onSuccess = callback;
}
loader.insert();
},
sayIt: function() {
var args = arguments;
HelloWorld.lazyLoad(function() { HelloWorld.sayIt.apply(HelloWorld, args); });
}
};
Note that you could possibly load the loading image initially and remove it in the callback function. Reading SO Question JQuery to load Javascript file dynamically, you could also use $.getScript() to do the same thing.
You could also find another example in this link
I want to load external images on my page asynchronously using jQuery and I have tried the following:
$.ajax({
url: "http://somedomain.com/image.jpg",
timeout:5000,
success: function() {
},
error: function(r,x) {
}
});
But it always returns error, is it even possible to load image like this?
I tried to use .load method and it works but I have no idea how I can set timeout if the image is not available (404). How can I do this?
No need for ajax. You can create a new image element, set its source attribute and place it somewhere in the document once it has finished loading:
var img = $("<img />").attr('src', 'http://somedomain.com/image.jpg')
.on('load', function() {
if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) {
alert('broken image!');
} else {
$("#something").append(img);
}
});
IF YOU REALLY NEED TO USE AJAX...
I came accross usecases where the onload handlers were not the right choice. In my case when printing via javascript. So there are actually two options to use AJAX style for this:
Solution 1
Use Base64 image data and a REST image service. If you have your own webservice, you can add a JSP/PHP REST script that offers images in Base64 encoding. Now how is that useful? I came across a cool new syntax for image encoding:
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhE..."/>
So you can load the Image Base64 data using Ajax and then on completion you build the Base64 data string to the image! Great fun :). I recommend to use this site http://www.freeformatter.com/base64-encoder.html for image encoding.
$.ajax({
url : 'BASE64_IMAGE_REST_URL',
processData : false,
}).always(function(b64data){
$("#IMAGE_ID").attr("src", "data:image/png;base64,"+b64data);
});
Solution2:
Trick the browser to use its cache. This gives you a nice fadeIn() when the resource is in the browsers cache:
var url = 'IMAGE_URL';
$.ajax({
url : url,
cache: true,
processData : false,
}).always(function(){
$("#IMAGE_ID").attr("src", url).fadeIn();
});
However, both methods have its drawbacks: The first one only works on modern browsers. The second one has performance glitches and relies on assumption how the cache will be used.
cheers,
will
Using jQuery you may simply change the "src" attribute to "data-src". The image won't be loaded. But the location is stored with the tag. Which I like.
<img class="loadlater" data-src="path/to/image.ext"/>
A Simple piece of jQuery copies data-src to src, which will start loading the image when you need it. In my case when the page has finished loading.
$(document).ready(function(){
$(".loadlater").each(function(index, element){
$(element).attr("src", $(element).attr("data-src"));
});
});
I bet the jQuery code could be abbreviated, but it is understandable this way.
$(<img />).attr('src','http://somedomain.com/image.jpg');
Should be better than ajax because if its a gallery and you are looping through a list of pics, if the image is already in cache, it wont send another request to server. It will request in the case of jQuery/ajax and return a HTTP 304 (Not modified) and then use original image from cache if its already there. The above method reduces an empty request to server after the first loop of images in the gallery.
You can use a Deferred objects for ASYNC loading.
function load_img_async(source) {
return $.Deferred (function (task) {
var image = new Image();
image.onload = function () {task.resolve(image);}
image.onerror = function () {task.reject();}
image.src=source;
}).promise();
}
$.when(load_img_async(IMAGE_URL)).done(function (image) {
$(#id).empty().append(image);
});
Please pay attention: image.onload must be before image.src to prevent problems with cache.
If you just want to set the source of the image you can use this.
$("img").attr('src','http://somedomain.com/image.jpg');
This works too ..
var image = new Image();
image.src = 'image url';
image.onload = function(e){
// functionalities on load
}
$("#img-container").append(image);
AFAIK you would have to do a .load() function here as apposed to the .ajax(), but you could use jQuery setTimeout to keep it live (ish)
<script>
$(document).ready(function() {
$.ajaxSetup({
cache: false
});
$("#placeholder").load("PATH TO IMAGE");
var refreshId = setInterval(function() {
$("#placeholder").load("PATH TO IMAGE");
}, 500);
});
</script>
use .load to load your image. to test if you get an error ( let's say 404 ) you can do the following:
$("#img_id").error(function(){
//$(this).hide();
//alert("img not loaded");
//some action you whant here
});
careful - .error() event will not trigger when the src attribute is empty for an image.
//Puedes optar por esta solución:
var img = document.createElement('img');
img.setAttribute('src', element.source)
img.addEventListener('load', function(){
if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) {
alert('broken image!');
} else {
$("#imagenesHub").append(img);
}
});
$(function () {
if ($('#hdnFromGLMS')[0].value == 'MB9262') {
$('.clr').append('<img src="~/Images/CDAB_london.jpg">');
}
else
{
$('.clr').css("display", "none");
$('#imgIreland').css("display", "block");
$('.clrIrland').append('<img src="~/Images/Ireland-v1.jpg">');
}
});
Short version question :
Is there navigator.mozIsLocallyAvailable equivalent function that works on all browsers, or an alternative?
Long version :)
Hi,
Here is my situation :
I want to implement an HtmlHelper extension for asp.net MVC that handle image post-loading easily (using jQuery).
So i render the page with empty image sources with the source specified in the "alt" attribute.
I insert image sources after the "window.onload" event, and it works great.
I did something like this :
$(window).bind('load', function() {
var plImages = $(".postLoad");
plImages.each(function() {
$(this).attr("src", $(this).attr("alt"));
});
});
The problem is : After the first loading, post-loaded images are cached. But if the page takes 10 seconds to load, the cached post-loaded images will be displayed after this 10 seconds.
So i think to specify image sources on the "document.ready" event if the image is cached to display them immediatly.
I found this function : navigator.mozIsLocallyAvailable to check if an image is in the cache. Here is what I've done with jquery :
//specify cached image sources on dom ready
$(document).ready(function() {
var plImages = $(".postLoad");
plImages.each(function() {
var source = $(this).attr("alt")
var disponible = navigator.mozIsLocallyAvailable(source, true);
if (disponible)
$(this).attr("src", source);
});
});
//specify uncached image sources after page loading
$(window).bind('load', function() {
var plImages = $(".postLoad");
plImages.each(function() {
if ($(this).attr("src") == "")
$(this).attr("src", $(this).attr("alt"));
});
});
It works on Mozilla's DOM but it doesn't works on any other one. I tried navigator.isLocallyAvailable : same result.
Is there any alternative?
after some reseach, I found a solution :
The idea is to log the cached images, binding a log function on the images 'load' event.
I first thought to store sources in a cookie, but it's not reliable if the cache is cleared without the cookie. Moreover, it adds one more cookie to HTTP requests...
Then i met the magic : window.localStorage (details)
The localStorage attribute provides
persistent storage areas for domains
Exactly what i wanted :). This attribute is standardized in HTML5, and it's already works on nearly all recent browsers (FF, Opera, Safari, IE8, Chrome).
Here is the code (without handling window.localStorage non-compatible browsers):
var storage = window.localStorage;
if (!storage.cachedElements) {
storage.cachedElements = "";
}
function logCache(source) {
if (storage.cachedElements.indexOf(source, 0) < 0) {
if (storage.cachedElements != "")
storage.cachedElements += ";";
storage.cachedElements += source;
}
}
function cached(source) {
return (storage.cachedElements.indexOf(source, 0) >= 0);
}
var plImages;
//On DOM Ready
$(document).ready(function() {
plImages = $(".postLoad");
//log cached images
plImages.bind('load', function() {
logCache($(this).attr("src"));
});
//display cached images
plImages.each(function() {
var source = $(this).attr("alt")
if (cached(source))
$(this).attr("src", source);
});
});
//After page loading
$(window).bind('load', function() {
//display uncached images
plImages.each(function() {
if ($(this).attr("src") == "")
$(this).attr("src", $(this).attr("alt"));
});
});
The most efficient, simple, and widely supported way to check if an image has already been cached is to do the following...
Create an image object
Set the src property to the desired url
Check the completed attribute immediately to see if the image is already cached
Set the src attribute back to "" (empty string), so that the image is not unnecessarily loaded (unless of coarse you want to load it at this time)
Like so...
function isCached(src) {
const img = new Image();
img.src = src;
const complete = img.complete;
img.src = "";
return complete;
}
In your case, it could be implemented like so...
const lazyImages = document.querySelectorAll(".postLoad");
for (const img of lazyImages) {
if ((!img.src || !isCached(img.src)) && img.getAttribute("alt")) {
img.src = img.getAttribute("alt");
}
}
That being said, I'd advise against using the alt attribute for this purpose, you should use something like data-src instead.
An ajax request for the image would return almost immediately if it is cached. Then use setTimeout to determine if its not ready and cancel the request so you can requeue it for later.
Update:
var lqueue = [];
$(function() {
var t,ac=0;
(t = $("img")).each(
function(i,e)
{
var rq = $.ajax(
{
cache: true,
type: "GET",
async:true,
url:e.alt,
success: function() { var rq3=rq; if (rq3.readyState==4) { e.src=e.alt; } },
error: function() { e.src=e.alt; }
});
setTimeout(function()
{
var k=i,e2=e,r2=rq;
if (r2.readyState != 4)
{
r2.abort();
lqueue.push(e2);
}
if (t.length==(++ac)) loadRequeue();
}, 0);
}
);
});
function loadRequeue()
{
for(var j = 0; j < lqueue.length; j++) lqueue[j].src=lqueue[j].alt;
}
I have a remark about your empty image sources. You wrote:
So i render the page with empty image sources with the source specified in the "alt" attribute. I insert image sources after the "window.onload" event, and it works great.
I've ran into problems with this in the past, because in some browsers empty src attributes cause extra requests. Here's what they do (copied from Yahoo! performance rules, there's also a blog post on that issue with more detail):
Internet Explorer makes a request to the directory in which the page is located.
Safari and Chrome make a request to the actual page itself.
Firefox 3 and earlier versions behave the same as Safari and Chrome, but version 3.5 addressed this issue[bug 444931] and no longer sends a request.
Opera does not do anything when an empty image src is encountered.
We also use a lot of jQuery on our site, and it has not always been possible to avoid empty image tags. I've chosen to use a 1x1 px transparent gif like so: src="t.gif" for images that I only insert after pageload. It is very small and gets cached by the browser. This has worked very well for us.
Cheers, Oliver
Just in case others may come across the same issue. some of the solutions provided here (namely storing the cache info in a local browser data storage) could break for two reasons. Firstly if cache of the image expires and secondly if the cache is cleared by the user. Another approach would be to set the source of image to an placeholder. Then changing the source to the image path/name. This way it becomes the responsibility of the browser to check its own cache. Should work with most browsers regardless of their API.
In 2017, Resource Timing API can help you check this using PerformanceResourceTiming.transferSize property. This property shall return non-zero transfer size when it is downloaded from server (not cached) and returns zero if fetched from a local cache.
Reference : https://developer.mozilla.org/en-US/docs/Web/API/PerformanceResourceTiming/transferSize
For anyone who might be trying to solve this problem with React I used the complete image property to solve it in React this way:
import React, { useState, useEffect, useRef } from 'react'
const Component= () => {
const [isLoadedImage, setLoadedImage] = useState(false)
const imageRef = useRef(null)
useEffect(() => {
const imgEl = imageRef.current
if (imgEl && imgEl.complete && !isLoadedImage) setLoadedImage(true)
})
return (
<img
onLoad={() => (!isLoadedImage ? setLoadedImage(true) : null)}
ref={imageRef}
/>
)
}