PhantomJS - Capture screen to HTMLImageElement, HTMLCanvasElement or ImageData - javascript

Is it possible with PhantomJS to capture a web page screen without saving it to the file system?
I need this because I want to make some post processing (color scheme detection) with the page screenshot.
The color detection is also made with JS .(https://github.com/leeoniya/RgbQuant.js) and can handle HTMLImageElement, HTMLCanvasElement, ImageData or CanvasRenderingContext2D
Here is the PhantomJS API, but the render method only supports a file path: http://phantomjs.org/screen-capture.html

Thank you Artjom B. for your solution in the comment. It worked fine.
First I created the screenshot of the page, and saved it to the folder screenshots with an html file that includes this screenshot.
page.open(url, function (status) {
// Make screenshot and save it to './screenshots'
var rel_path = 'screenshots/' + btoa(url) + '_' + (new Date().getTime());
// Image path
var img_path = rel_path + '.png';
// HTML page path
var html_path = rel_path + '.html';
// Make screenshot
page.render(img_path);
// Create webpage with the image, but take the absolute path.
fs.write(html_path, '<html><body><img id="image" src="' + 'file:///' + fs.absolute(img_path) + '"/></body></html>', 'w');
});
After that I opend the created file again with phantom. Loaded the image by the id=image and performed my RGB-Quantification.
p.open('file:///' + html_path, function start(status) {
console.log('[RGB-QUANTIFICATION]: ' + self.url);
// Inject image quantification library
p.injectJs('ext/rgbquant.js');
// Generate color palette
var colors = p.evaluate(function () {
var rgb_quant_settings = {colors: 5, method: 2, initColors: 4096, minHueCols: 0};
var rgb_quant = new RgbQuant(rgb_quant_settings);
rgb_quant.sample(document.getElementById('image'));
return rgb_quant.palette(true);
});
...
});

Related

COMBINING CSS and SVG Filters to Edit and Save an Image [duplicate]

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>

jCrop resize with correct coords when changing image

Hoping this doesn't get flagged as a duplicate because none of the other q/as on SO have helped me fix this, I think I need a more specific line of help.
I have a profile page on my site that allows the user to change their profile picture without page reloads (via AJAX / jQuery).
This all works fine. The user opens the "Change Profile Picture" modal, selects a file to upload and presses "Crop this image". When this button is pressed, it uploads a file to the website, using the typical way of sending the file and formData (which I append the file data to).
It gets sent backend with the following jQuery:
// Upload the image for cropping (Crop this Image!)
$("#image-upload").click(function(){
// File data
var fileData = $("#image-select").prop("files")[0];
// Set up a form
var formData = new FormData();
// Append the file to the new form for submission
formData.append("file", fileData);
// Send the file to be uploaded
$.ajax({
// Set the params
cache: false,
contentType: false,
processData: false,
// Page & file information
url: "index.php?action=uploadimage",
dataType: "text",
type: "POST",
// The data to send
data: formData,
// On success...
success: function(data){
// If no image was returned
// "not-image" is returned from the PHP script if we return it in case of an error
if(data == "not-image"){
alert("That's not an image, please upload an image file.");
return false;
}
// Else, load the image on to the page so we don't need to reload
$(profileImage).attr("src", data);
// If the API is already set, then we should apply a new image
if(jCropAPI){
jCropAPI.setImage(data + "?" + new Date().getTime());
}
// Initialise jCrop
setJCrop();
//$("#image-profile").show();
$("#send-coords").show();
}
})
});
setJcrop does the following
function setJCrop(){
// Get width / height of the image
var width = profileImage.width();
var height = profileImage.height();
// Var containing the source image
var imgSource = profileImage.attr("src");
// New image object to work on
var image = new Image();
image.src = imgSource;
// The SOURCE (ORIGINAL) width / height
var origWidth = image.width;
var origHeight = image.height;
// Set up the option to jCrop it
$(profileImage).Jcrop({
onSelect: setCoords,
onChange: setCoords,
setSelect: [0, 0, 51, 51],
aspectRatio: 1, // This locks it to a square image, so it fits the site better
boxWidth: width,
boxHeight: height, // Fixes the size permanently so that we can load new images
}, function(){jCropAPI = this});
setOthers(width, height, origWidth, origHeight);
}
And once backend, it does the following:
public function uploadImage($file){
// See if there is already an error
if(0 < $file["file"]["error"]){
return $file["file"]["error"] . " (error)";
}else{
// Set up the image
$image = $file["file"];
$imageSizes = getimagesize($image["tmp_name"]);
// If there are no image sizes, return the not-image error
if(!$imageSizes){
return "not-image";
}
// SIZE LIMIT HERE SOON (TBI)
// Set a name for the image
$username = $_SESSION["user"]->getUsername();
$fileName = "images/profile/$username-profile-original.jpg";
// Move the image which is guaranteed a unique name (unless it is due to overwrite), to the profile pictures folder
move_uploaded_file($image["tmp_name"], $fileName);
// Return the new filename
return $fileName;
}
}
Then, the user selects their area on the image with the selector and pressed "Change Profile Picture" which does the following
// Send the Coords and upload the new image
$("#send-coords").click(function(){
$.ajax({
type: "POST",
url: "index.php?action=uploadprofilepicture",
data: {
coordString: $("#coords").text() + $("#coords2").text(),
imgSrc: $("#image-profile").attr("src")
},
success: function(data){
if(data == "no-word"){
alert("Can not work with this image type, please try with another image");
}else{
// Append a date to make sure it reloads the image without using a cached version
var dateNow = new Date();
var newImageLink = data + "?" + dateNow.getTime();
$("#profile-picture").attr("src", newImageLink);
// Hide the modal
$("#profile-picture-modal").modal("hide");
}
}
});
})
The backend is:
public function uploadProfilePicture($coordString, $imgSrc){
// Target dimensions
$tarWidth = $tarHeight = 150;
// Split the coords in to an array (sent by a string that was created by JS)
$coordsArray = explode(",", $coordString);
//Set them all from the array
$x = $coordsArray[0];
$y = $coordsArray[1];
$width = $coordsArray[2];
$height = $coordsArray[3];
$newWidth = $coordsArray[4];
$newHeight = $coordsArray[5];
$origWidth = $coordsArray[6];
$origHeight = $coordsArray[7];
// Validate the image and decide which image type to create the original resource from
$imgDetails = getimagesize($imgSrc);
$imgMime = $imgDetails["mime"];
switch($imgMime){
case "image/jpeg":
$originalImage = imagecreatefromjpeg($imgSrc);
break;
case "image/png":
$originalImage = imagecreatefrompng($imgSrc);
break;
default:
return "no-work";
}
// Target image resource
$imgTarget = imagecreatetruecolor($tarWidth, $tarHeight);
$img = imagecreatetruecolor($newWidth, $newHeight);
// Resize the original image to work with our coords
imagecopyresampled($img, $originalImage, 0, 0, 0, 0,
$newWidth, $newHeight, $origWidth, $origHeight);
// Now copy the CROPPED image in to the TARGET resource
imagecopyresampled(
$imgTarget, // Target resource
$img, // Target image
0, 0, // X / Y Coords of the target image; this will always be 0, 0 as we do not want any black nothingness
$x, $y, // X / Y Coords (top left) of the target area
$tarWidth,
$tarHeight, // width / height of the target
$width,
$height // Width / height of the source image crop
);
$username = $_SESSION["user"]->getUsername();
$newPath = "images/profile/$username-profile-cropped.jpg";
// Create that shit!
imagejpeg($imgTarget, $newPath);
// Return the path
return $newPath;
}
So basically this the returns the path of the new file, which gets changed to the user's profile picture (same name every time) and uploaded live with a time appended after ? to refresh the image properly (no cache).
This all works fine, however if the user selects another image to upload, after already uploading one, the coords get all messed up (e.g. they go from 50 to 250) and they end up cropping a totally different part of the image, leaving most of it black nothing-ness.
Really sorry for the ridiculous amount of code that is in this question but I'd appreciate any help from people who might have worked around this before.
Some of the code may seem out of place but that's just me trying to debug it.
Thanks, and again, sorry for the size of this question.
-Edit-
My setCoords() and setOthers() functions look like so:
//Set the coords with this method, that is called every time the user makes / changes a selection on the crop panel
function setCoords(c){
$("#coords").text(c.x + "," + c.y + "," + c.w + "," + c.h + ",");
}
//This one adds the other parts to the second div; they will be concatenated in to the POST string
function setOthers(width, height, origWidth, origHeight){
$("#coords2").text(width + "," + height + "," + origWidth + "," + origHeight);
}
I have now resolved this issue.
The problem for me was that when using setJCrop(); - it was not re-loading the image. The reason for this is that the image uploaded and then loaded in to the JCrop window had the same name every time (username as a prefix, and then profile-cropped.jpg).
So to try and resolve this, I used the setImage method which loaded a full-sized image instead.
I got around this by setting the boxWidth / boxHeight params but they just left me with the issue of the coordinates being incorrect every time I loaded a new image in.
Turns out, it was loading the image from the cache every time, even when I was using new Image(); within jQuery.
To solve this, I have now used destroy(); on the jCropAPI and then re-initialised it every time, witout using setImage();
I set a max-width in the CSS on the image itself, which stopped it from being locked to a specific width.
The next problem was that every time I loaded an image a second time, it left the width / height of the old image there, which made the image look all skewed and wrong.
To solve this, I reset the width & height of the image that I use jCrop on, to "" with $(profileImage).css("width", ""); $(profileImage).css("height", ""); before re-setting the source of the image from the new uploaded image.
But I was still left with the issue of using the same name on the images, and then causing it to load from cache every time.
My solution to this was to add an "avatar" column in the database and save the image name in the Database each time. The image was named as $username-$time.jpg and $username-$time.jpg-cropped.jpg where $username is the username of the user (derp) and $time is simply time(); inside PHP.
This meant that every time I uploaded an image, it had a new name, so when any calls were made to this image, there was no cache of it.
Appending like imageName + ".jpg?" + new Date.getTime(); worked for some things but then when sending the image name backend, it didn't work properly, and deciding when to append it / not append it was a pain, and then one thing required it to be appended to force a re-load, but then when appended it didn't work properly, so I had to re-work it.
So the key: (TL;DR)
Don't use the same image name with jCrop, if you are loading a new image; upload an image with a different name and then refer to that one. Cache problems are a pain, and you can't really work around them properly without just using a new name every time, as this ensures that there will be absolutely no more problems (so long as the name is always unique).
Then, when you initialise jCrop, destroy the previous one beforehand if there is one. Use max-width instead of width on an image to stop it from locking the width, and re-set the width / height of the image if you're loading a new one in to the same <img> or <div>
Hope this helps somebody!
I used jcrop and I think this has happened to me. When there is a new image, you have to "reset" jcrop. Try something like this:
function resetJCrop()
{
if (jCropAPI) {
jCropAPI.disable();
jCropAPI.release();
jCropAPI.destroy();
}
}
$("#image-upload").click(function(){
success: function(data){
...
resetJCrop(); // RESETTING HERE
// If the API is already set, then we should apply a new image
if(jCropAPI){
jCropAPI.setImage(data + "?" + new Date().getTime());
}
// Initialise jCrop
setJCrop();
...
}
});
I can't remember the details about why I have to use disable() AND release() AND destroy() in my particular case. May be you can use only one of those. Just try it, and see if that works for you!

How to pick(choose) multiple images using camera API at the same time in phonegap?

How to choose or pick multiple images at the same time in phonegap camera API when using Camera.DestinationType.FILE_URI. I am able to pick only one images at a time. I am able to pick multiple files(including txt,pdf..) in sdcard using this. So i want same like for images.
navigator.camera.getPicture(function(imageData) {
window.resolveLocalFileSystemURI(imageData, function(fileEntry) {
fileEntry.file(function(fileObj) {
}, onFail, {
quality : 50,
destinationType : Camera.DestinationType.FILE_URI
});
My cordova version 3.3, Jquery Mobile 1.3.2.
Please suggest any plugins are available to do this.
Use this Cordova multiple image selector plugin to choose multiple image at a time. It is good plugin for choose multiple images.
Download the above plugin and copy paste the java classes. Set the required permission. Don't forget to copy the res folder just copy and paste in your res folder.
Inside assets/www create imagepicker.js copy and paste the dowloaded imagepicker.js
In your index.html set like this:
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="imagepicker.js"></script>
<script type="text/javascript">
document.addEventListener("deviceready",onDeviceReady,false);
function onDeviceReady(){
window.imagePicker.getPictures(
function(results) {
for (var i = 0; i < results.length; i++) {
alert('Image URI: ' + results[i]);
// read file type and size and file name like below(in comment)
/* window.resolveLocalFileSystemURI(results[i], function(fileEntry){
fileEntry.file(function(fileObj) {
alert(fileEntry.name);
alert(fileObj.size);
alert(fileObj.type);
});
}, function (error) {
alert('Error: ' + error);
});*/
}
}, function (error) {
alert('Error: ' + error);
}
);
}
</script>
Note: This should work only cordova 3.0 and above and android 4.0 and above
Open CameraLauncher.java file and replace these lines
String resizePath = getTempDirectoryPath() + "/resize.jpg";
this.callbackContext.success("file://" + resizePath + "?" + System.currentTimeMillis());
to
String resizePath = getTempDirectoryPath() + "/resize"+System.currentTimeMillis()+".jpg";
this.callbackContext.success("file://" + resizePath);
var x=0;
function onPhotoDataSuccess(imageURI)
{
x++;
// Uncomment to view the base64-encoded image data
console.log(imageURI);
alert(imageURI);
// Get image handle
//
var y = 'smallImage'+x;
var smallImage = document.getElementById(y);
alert(smallImage);
smallImage.src = "data:image/jpeg;base64," + imageURI;
// Unhide image elements
//
smallImage.style.display = 'block';
// Show the captured photo
// The in-line CSS rules are used to resize the image
//
//var fso=new ActiveXObject("Scripting.FileSystemObject");
//fso.CopyFile("data:image/jpeg;base64," + imageURI,"file:///storage/sdcard/DCIM/");
alert(smallImage.src)
}
where x is the loop for doing the multiple image from camera as well as from photogallery

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.

Image preloading with array

I am using the following code to preload images in an image gallery:
$(window).bind('load', function(){
var imageNumber = $(".image").attr("alt");
var imageUp = parseInt(imageNumber) + 1
var imageUp2 = parseInt(imageNumber) + 2
var imageDown = parseInt(imageNumber) - 1
var preload = [
'image' + imageUp + '.jpg',
'image' + imageUp2 + '.jpg',
'image' + imageDown + '.jpg',
];
$(document.createElement('img')).bind('load', function(){
if(preload[0]) this.src = preload.shift();
}).trigger('load');
});
I modified another basic javascript/jQuery preload script, adding variables in order to get a numeric value from the current image's alt-tag and preload images that are immediately before and after it (n+1 n+2 n-1) in the gallery. This works, though I imagine it may be kind of ugly.
What I want to do is add or call another array containing all images in the directory, so that after the previous and next images have loaded, the current page continues to preload other images, saving them in the browsers catche for future viewing as the user moves through the gallery.
Ideally, this second array would be called from an external .js file, so as to prevent having to update every page individually. (Or maybe it would be easier to save the entire script in a external .js file for each directory and fill out the rest of the array based on that directory's contents?).
Web design is only a hobby for me (I'm a photographer), so my knowledge of javascript is limited--just enough to customize pre-built functions and collage scraps of code.
I would really appreciate if someone could point me in the right direction on how to modify my code.
Thanks in advance,
Thom
I have never used a jQuery preload script but i have done a lot of preloading with 'vanilla' javascript.
Try the code i have added below, it may solve your problem.
function preLoad() { // my preload function;
var imgs = arguments, imageFolder = [];
for (var i = 0; i < imgs.length; i += 1) {
imageFolder[i] = new Image();
imageFolder[i].src = imgs[i];
}
}
var gallary = []; // all gallary images
$(window).bind('load', function(){
var imageNumber = $(".image").attr("alt");
var imageUp = parseInt(imageNumber) + 1
var imageUp2 = parseInt(imageNumber) + 2
var imageDown = parseInt(imageNumber) - 1
var preload = [
'image' + imageUp + '.jpg',
'image' + imageUp2 + '.jpg',
'image' + imageDown + '.jpg',
];
$(document.createElement('img')).bind('load', function(){
if(preload[0]) this.src = preload.shift();
}).trigger('load');
preLoad(gallary); // preload the whole gallary
});
EDIT
preLoad() : this function accepts image urls as arguments e.g preLoad('image_one.jpg', 'image_two.jpg','image_thre.jpg');
The preLoad function has two variables var imgs and var imageFolder, imgs stores all the image urls and imageFolder stores image Objects, that is, preload loaded images.

Categories

Resources