I am confused about the best way to discover the image dimensions, or the naturalWidth of images, given the url to the image, most often found in the src attribute of an <img> tag.
My goal is take as input a url to a news article and use machine learning to find the top 5 biggest pictures (.jpg, .png, etc) files in the document. The problem with using the front-end to do this, is that I don't know of a way to use AJAX to http GET html from some random page of some random server, because of CORS related issues.
However, using Node.js, or some server technology, I can make requests to get the HTML from other servers (as one would expect) but I don't know a way of getting the image sizes without downloading the images first. The problem is that, I want the downloaded images on the front-end, not the back-end, and therefore downloading images with Node.js is wasted effort, if it's just to check the image dimensions.
Has anyone experienced this exact problem before? Not sure how to proceed. As I said, my goals are to download images on the front-end, and keep the ones that are bigger than say 300px in width.
Both ways are ok, depends greatly on exactly what you need to achieve in terms of performance:
To me seems that, the simplest way for you would be on client side, then you only need a few lines of JavaScript to do it:
var img = new Image();
img.onload = function() {
console.log(this.width + 'x' + this.height);
}
img.src = 'http://www.google.com/intl/en_ALL/images/logo.gif';
On server side is also possible but you will need to install GraphicsMagick or ImageMagick. I'd go with GraphicsMagick as it is faster.
Once you have installed both the program and it's module (npm install gm) you would do something like this to get the width and height.
gm = require('gm');
// obtain the size of an image
gm('test.jpg')
.size(function (err, size) {
if (!err) {
console.log(size.width + 'x' + size.height);
}
});
Also, this other module looks good, I haven't used it but it looks promsing https://github.com/netroy/image-size
To get the img urls from the html string
You can load your html string using a simple http request, then you need to use a regexp capture group to extract the urls, and if you're wanting to match globally g, i.e. more than once, when using capture groups, you need to use exec in a loop (match ignores capture groups when matching globally).
This way you'll have all the sources in an array.
For example:
var m;
var urls = [];
var rex = /<img[^>]+src="?([^"\s]+)"?\s*\/>/g;
// this is you html string
var str = '<img src="http://example.com/one.jpg />\n <img src="http://example.com/two.jpg />';
while ( m = rex.exec( str ) ) {
urls.push( m[1] );
}
console.log( urls );
// [ "http://example.com/one.jpg", "http://example.com/two.jpg" ]
Hope it helps.
Related
I have a site that displays a lot of external images and thumbnails etc, easily up to 100 on a single page. I crawl and index the urls to the images and save them in mysql and display them with this code inside simple loops from queries.
<img src="<?php echo $row['img_url']; ?>" onerror="this.onerror=null;this.src='http://example.com/image.jpg';" width="150" height="150">
I use that particular code to replace any broken image urls with a default image.
My question is, is it possible to use javascripts onerror or something else to capture the image url that is broken when a broken url is found so that I can pass the url back to php and be able to automatically delete the urls from my database?
I am not very good with javascript and after searching I can't seem to find anything similar to what I am looking for, I mostly just find lots of posts on how to replace the broken image.
I am open to any ideas really, the original image urls come from $row['img_url'] as you can see in the code but I know I need javascript or something to catch the errors and then somehow get the urls passed back to php so that I can automate the deletion process instead of just replacing images with default images like my currnt code.
you can use file_exists to check like so:
if(file_exists($row['img_url'])){
echo '<img src="'.$row['img_url'].'" onerror="this.onerror=null;this.src="http://example.com/image.jpg";" width="150" height="150">';
}
You are almost there. Simply replace this:
this.src='http://example.com/image.jpg'
with:
this.src='http://example.com/image-missing.php?url={$row['primaryKey']}&w=150&h=150'
Now, "image-missing.php" receives the URL of the missing file and the intended size of the missing image. What it needs to do is clean the database (after checking that the call is legitimate (1) and that the referred row exists(2)), and output a replacement image in the proper size.
(1) otherwise you have just handed the possibility of deleting your whole image database to the first guy with time on his hands.
(2) someone else might have loaded the same page, and called the same script one millisecond ago.
You should try something like this (example uses vanilla JS, no jquery or any 3rd party library):
var allImages = document.querySelectorAll('img');
for (var i = 0; i < deleteLink.length; i++) {
document.querySelector('img').addEventListener('error', function(e) {
// Delete a user
var url = "<DELETION_URL>";
var xhr = new XMLHttpRequest();
xhr.open("DELETE", url+'?resource=' + e.target.src, true);
});
}
<DELETION-URL> should point to a PHP script that accepts DELETE (or at least POST) requests and read the resource parameter. It will then remove the image provided that resource is truly missing.
An HTML page handed off to me which originally have a image path which look something like this...
<img src="img/foo.jpg"
simply need to be changed to a new path.
I have a loop which goes through the collection of images:
container_images = container.getElementsByTagName('img');
imgSrc = /img\//gi,
for (var i = 0; i < container_images.length; i++) {
var images = container_images[i];
if (images.src.indexOf('img') !== -1) {
images.src = images.src.replace(imgSrc, 'new/path/here/');
}
}
Now this works perfectly locally however when I run this on my company's QAF server, it appears the server is adding a dev path:
<img src="http://ryelxusecqcm1.rye.com:8080/us-home/tools/img/foo.gif">
So is there a method other than .replace which can explicitly wipe out and the old path and put my new path? i.e. 'new/path/here/'
The problem may be because you are using a "relative" path in your code (i.e. a path that does not begin with "/"):
images.src = images.src.replace(imgSrc, 'new/path/here/');
Because you are using a relative path, your browser is prepending your path with the server's URL.
Try this and see if it helps.:
images.src = images.src.replace(imgSrc, '/new/path/here/');
(Note the leading "/" in '/new/path/here/')
I found such a simple but elegant solution. Instead of testing for a string with indexOf (which would've worked if I didn't have two different environments), I went for a solution which is more direct.
images.src = '/dam/avon-us/landing-pages/rep-news/' + images.src.split('/').pop();
This first coverts the image path/string to a collection of items in an array, delineated by the forward slash. ['current', 'path', 'foo.jpg'] Then using the pop method return just the last item in the array, which is the file name & extension. foo.jpg and then we simply prepend the path we want the image to have!
Want to say thanks for all the folks who tried to help me!
I am developing a browser game using MVC4 and have been able to deploy to my website for the first time tonight. I'm sloshing through the differences between running the site off of localhost and running it from the website.
Right now the first thing I do is load all of the static content on the page--navigation bars, icons, the world map, and some basic javascript to interact with it. Then, I call four AJAX functions that return information about various elements on my 2d map, such as cities and their x,y coordinate, name, and a small flag icon.
Upon completing the AJAX function I begin to parse the JSON returned. For each item in the JSON, I add a new 20x20 pixel class using code like this:
function loadSuccessCityTiles(data) {
var cityTiles = jQuery.parseJSON(data);
var cityTileCount = cityTiles.length;
$(".CityTile").remove();
for (var i = 0; i < cityTiles.length; i++) {
var imgName = "../Images/City_Tiles/Small/" + cityTiles[i].Type + "";
$("#scrollWindow").append("<div class = 'CityTile' style = 'left: " + Math.floor(cityTiles[i].X)*tileSize + "px; top: " + Math.floor(cityTiles[i].Y)*tileSize + "px; background-image: url(" + imgName + ");'></div>") ;
}
}
As you can see, I append a new class using that has its background-image set to the appropriate image url (that is what Type means). This works great on localhost, but when I run it on the website I discover that the images don't load.
I'm not quite sure how to proceed here. I have a lot of small image elements (each in separate files) and there is no guarantee that all will be used, so it is wasteful to load them all. What would be a good solution in this case? One thought I have had is to return JSON data on which image files will be used and then preload those images via javascript all before creating the classes that will use them.
Why does this happen on the server but not localhost? Clearing my cache before reloading on localhost does not recreate this problem. Is it because there is no need for a download as all the files are already on your hard drive?
Does anyone have a suggestion on a better way to do this all together?
A better option could be to use a single image sprite as a background image for each tile. Use the Type as a class name, and set the background x,y positioning in CSS. The single image will have a large file size, but it will be a single request that could easily be cached.
As for it not working, what errors are you getting? What do you see in the network tab in Chrome dev tools for the image request?
I can't get through this problem though it must be only a very small syntax problem, as you will see: In fact, I'm searching for just a little piece of syntax, unless what I intend to do would be impossible (But I can see no reason why it should be impossible...).
I have written a function to encode an image into Base64 on server side, because I want to store numerous images into an array:
So, with Base64 I can download images as ordinary strings that I can organize in an array, then put them into an object just when I have chosen the right image and the right moment, without having to refer to the server again, so that the user doesn't have to wait.
Then I do something like this:
First phase:
function download64(imageUrl) //->string
{ // ask the server to send the 'imageUrl' as a base64 string
var tx = DoTheJob(); // ...connect through ajax and download the image converted in base64 as a string in var 'tx'
return tx
}
At this stage, I'm holding the image in the 'tx' Base64-string on client side.
Somewhat later I want to display my image in the div called "cadre", so I do the following:
Second phase:
I just have to call the "display64" function to set my image into the "cadre" div-object on the screen:
display64("cadre",tx);
using this function:
function display64(destinationDiv,imgText64) //->void
{ // display 'imgText64' into destinationDiv
var oImg = "<img alt='' src='data:image/jpg;base64," + imgText64 + "'>";
var x = document.getElementById(destinationDiv);
x.innerHTML = oImg;
}
Now the image is displayed. Unfortunately, this works well only with Firefox, because Internet Explorer 8 can't read Base64 images above 32Kb! And in my entreprise, we use IE 8 only!
Then I dropped my base64 encoder and decided to fetch the image as a binary string, which I could manage though I initially had a problem with nul character.
Now, I'm here with my binary string containing the exact copy of the source JPG file (including zeros that I have encoded on server side then restored on client side). So, what I need now is the simple function 'displayBin', but I can't find the syntax on the web:
function displayBin(destinationDiv,imgTextBin) //->void
{ // display 'imgTextBin' into destinationDiv
var oImg = "<img alt='' src='??????? + imgTextBin + "'>"; // What's the syntax here, please?
var x = document.getElementById(destinationDiv);
x.innerHTML = oImg;
}
Can anyone help ? Thanks a lot.
If I understand your question your are wanting to store images so you do not have to connect back with the server. One way of doing this is to preload the images like var img=new Image; img.src='path'; You could load all of the images into an array and you could then add them to the page as necessary. There is a lot out there on image preloading since that seems what your trying to accomplish.
I'm working on a PhoneGap application that captures images using the camera and, later, uploads them. There are two modes of operation for camera in PhoneGap: raw base64 encoded data or a file URI.
The docs themselves say:
Note: The image quality of pictures taken using the camera on newer
devices is quite good. Encoding such images using Base64 has caused
memory issues on some of these devices (iPhone 4, BlackBerry Torch
9800). Therefore, using FILE_URI as the 'Camera.destinationType' is
highly recommended.
So I'm keen to use FILE_URI option. This works great and you can even show the images in IMG tags. The URL looks like this:
file://localhost/var/mobile/Applications/4FE4642B-944C-449BB-9BD6-1E442E47C7CE/tmp/photo_047.jpg
However, at some point later I want to read the contents of the file to upload to a server. I was going to do this using the FileReader type. This doesn't work and I think it's because I can't access the file at the URL above.
The error code I get back from readDataUrl is 1 > FileError.NOT_FOUND_ERR = 1;
Any ideas how I can get to the file? I tried just accessing the last part of the path (photo_047.jpg) based on another sample I saw but no luck.
I'm just getting started with PhoneGap, and given the age of this question you may have found an answer already, but I'll give it a try anyway.
First, would you be able to use the built-in FileTransfer object? It takes a file: URI as an argument.
If FileTransfer won't work for you, and you need to read the file data yourself, you'll need the PhoneGap File objects, like FileReader , as you said. But most of those expect a plain pathname -- not a URI -- to specify the file to work with. The reason you're getting NOT_FOUND_ERR is because it's trying to open a file named file:/localhost/var....
Here's a quick one-liner to extract the path part from your URI:
var path = /file:\/\/.*?(\/.*)/.exec(fileuri)[1];
Hope this helps!
The answer from jgarbers was of help to me but it did not solve the problem. I realized the camera stores photos in Temp folder instead of Document folder. Setting my local file system to temporary allowed it to find the correct location for the camera images.
window.requestFileSystem(LocalFileSystem.TEMPORARY, 0, ...
...
window.requestFileSystem(LocalFileSystem.TEMPORARY, 0, ...
...
var path = /file://.?(/.)/.exec(fileuri)[1];
Ref. above jgarbers and Rik answers (solution has been tested successfully on iOs 7)
you can user the file transfer plugin for uploading any file to the server.
//// pass your file uri to the mediafie param
function uploadFile(mediaFile) {
var ft = new FileTransfer();
path = mediaFile.fullPath;
name = mediaFile.name;
////your service method url
var objUrl = http://example.com;
ft.upload(path,
objUrl,
function (result) {
alert("Success");
},
function (error) {
alert('Error uploading file ' + path + ': ' + error.code);
},
{ fileName: name });
}