JavaScript to add sliced images to div automatically - javascript

Im new to stackoverflow and really hope you guys can help me. I designed a small website for a photographer and he is not okay with the options for his images being download. I know that there is no way to secure images online. (You can easily just save page and get everything you need). if there is a better way. Please kindly let me know..
So anyway i said i will slice his images and upload so people will be downloading only pieces of his image. Even though it is not 100%n secure, he was okay with it after several explanation hours :)
I was hoping to used SuperSimple image tiles but since it runs php alot, it is a bit slow to load images. Im sure, you guys are aware of it.
So anyway now im hoping to use a batch image slicer and slice the images. oh i forgot to tell, there are around 100 images :D
So anyway, i will equally slice an image to 25 pieces (5x5). and i will be adding the image full complete inside a div. What i need to know is, is there away to add the sliced images with a js loop so the process will be much smoother and simpler. Since the div will resize according to the screed dimensions, full image should be in 100% width and height.
this is the current full image syntax.
<div> <img src="IMAGE (1).jpg" width="100%" height="100%" /> </div>
What i want to do is, instead of image tag above, i need to run a loop script. to add 25 images (instead of 1 image to make an image tile).
images are named as IMAGE (1)1, IMAGE (1)2, IMAGE (1)3..etc.. till IMAGE (1)25 and the again IMAGE (2)1, IMAGE (2)2, IMAGE (2)3..etc.. till IMAGE (2)25...
Hope i explained my problem well. Please someone let me know an easy way to add a script to automate the image inserting process. i believe Image style should be as FLOAT=LEFT and WIDTH=20% and HEIGHT=20%..
Thanks a lot in advance.

Using PHP will be better for one important reason: not everyone has javascript enabled.
I'm not familiar with 'SuperSimple image tiles' so I can't comment on its performance but plain php will not slow it down compared - in most situations it should be faster than a similar javascript loop just due to the fact that it is on less piece of data to download to the client side.
To do that in plain php (assumptions spelled out in the initial variables and that the image chunk numbering starts at 0):
<?php
$img_path = "images/funkytree_" //the base image path without the number or the extension
$img_ext = ".jpg" //the extension
$img_alt = "funky tree" //alt text for the images
$i = 0;
while ($i < 25) {
echo "<img src='{$img_path}{$i}{$img_ext}' alt='{$img_alt}'/>;
$i ++;
}
?>
Then best would be to use CSS styling to set the position/size of each image.
HTH
Nick

Related

Speed up web page by compressing large images

I have a blog slideshow on my web page which accesses images from a given url.
The problem is, people add images with massive resolution (3000px*6000px), which noticeably slows down the animation of the slideshow.
These high resolution images are necessary, but not for this particular purpose, since the images live inside a div of size (300*600)
Is there any way CSS (or some other way) can convert the image to a smaller specified resolution (say 300px * 600px), before scaling down.
This way the animation won't involve high res image frames and so it won't be as laggy.
The only alternative I can think of, is that everytime an image is uploaded on the database, the backend creates a secondary compressed image for this purpose.
However, this seems like a lot of effort.
Since you said in the comments that bandwidth and download time are not the issue and it's acceptable to download the full res image, scale it down, then add it to the page, please consider the following solution which does exactly that.
Download the original image via AJAX, then use ctx.drawImage to draw the image to an HTML canvas with much smaller size. For instance, you can take a 3000px*6000px image and draw it scaled onto a 300px*600px canvas. Then free the original image using JavaScript so that it no longer takes up memory in the browser.
After that, you can use the canvas to do your animations and there should not be nearly as much lag as using the large, original image (since the compositor will need to move much fewer pixels).
Edit: According to your later comment, your users are uploading to an external image hosting service, so this solution will prevent them from having to upload a thumbnail version in addition to their full-res version.
If you choose Imgur.com like you are considering in the comments: They let you modify the image size a bit in the URL. So for instance if you have an image at https://i.imgur.com/9ZC02Os.jpg, you can use https://i.imgur.com/9ZC02Oss.jpg for the small version, https://i.imgur.com/9ZC02Osm.jpg for the medium version, and https://i.imgur.com/9ZC02Osl.jpg for the large scaled version (note the s, m, and l at the end of the URLs). That way you can probably avoid drawing to a canvas completely.
This was a site I found a few years agowhich may be of interest: http://sneak.co.nz/projects/img-resizing/
You could store a small version on your site for use in the slideshow. A good way to do this may be to check if a small image is available and if not create it the first time it is called and save it somewhere.
This code will resize an image on the fly but I think you would still have some lag while the image is resized.
$photo="sunflower.jpg";
$cmd = "convert $photo -thumbnail 200x200 ".
" -quality 100 JPG:-";
header("Content-type: image/jpeg");
passthru($cmd, $retval);

jQuery | Can I Run Speceific Code Based On What An Images Average Color Is?

I have had trouble finding any examples of this so I thought Id ask here hoping to get a better idea on whether this is possible or not. What I want to do is have images being dynamically grabbed from a feed. Based on the images' average color is (or even better what color the image would look like if it were only a few pixals big) run a specific code that puts that images somewhere in a picture that will be built out by these images that are pulled. Would I need jQuery for this or the canvas tag maybe?
Any help or insight on how I could begin to make this possible would be excellent!
Thanks :)
This seems like a good solution for you, it gets the predominant color in a image, so from that you could execute your code.
https://github.com/briangonzalez/jquery.adaptive-backgrounds.js

Many images loading performance HTML/Javascript

Ok so after some searching and not finding the real anwser I was looking for I came with the following question in this situation:
I have a trading website that loads about 2300 PNG images of 37x50 twice, once in a left column and once in a right column. The images and all information that comes with it is inserted using jQuery on the document on the onLoad event. However loading 2300 images (even when the html came straight from the server) takes just TOO much time and even hangs new versions of chrome!. So now the quick solution was just to remove the images and show in a dynamic tooltip. Works great but got angry website users and it is indeed ugly.
So... I thought of some possible solutions but I have no idea what is good/bad practice here:
Make all images JPEG and reduce quality.
With the above or not: Add all images to 1 very large image, load it and draw 4600 canvasses based on locations in an array like 'imageArray["someimageID"] = { x = 0, y = 40 }'
Convert all images to base64, add them in an array 'imageArray["someimageID"] = "base64"' and draw 4600 canvasses.
And to an extend where I must think of as well that of all those 2300 images I have a small, medium and large version. (of which only the small ones, 37x40, are shown all together in a page)
Hope to get some nice insights on how to correctly solve such a problem!
Greets
If your images are static (not generated for every request) I think you should use CSS sprites. (similar to your own suggestion of lots of canvases).
Basically you create a div for each image you want to show (or some other container element) and set a background on it that takes a small portion of the big image that contains all images.
Example css:
img.icon1
{
width:50px;
height:50px;
background:url(spritesheet.png) 50 0;
}
in this example the 50 and 0 indicate the offset of your 50x50 icon in the spritesheet.
Update: Here http://css-tricks.com/css-sprites/ is an explanation that goes a bit further than my simple example.
First off, consider whether or not you actually need this many images, and loaded on the page all at once. Assuming you do...
Make all images JPEG and reduce quality.
Use the right format for what you're doing. JPEG is for photos. My guess is that since you have 37x50 pixel images that you're not showing photos. PNG is likely smaller from a file-size perspective in this case. It doesn't matter a whole lot though because the speed issue you're having is probably 80% browser time, 20% network time.
With the above or not: Add all images to 1 very large image, load it and draw 4600 canvasses based on locations in an array like 'imageArray["someimageID"] = { x = 0, y = 40 }'
Try it and see. I don't think this is going to help you. A canvas will have more overhead than a simple image.
Convert all images to base64, add them in an array 'imageArray["someimageID"] = "base64"' and draw 4600 canvasses.
Don't do this. You're adding 33% overhead to the file size, and again the load problem is mostly in your browser.
What you can do
Really question again whether or not you need this many images in the first place.
Cut down on network requests by using several hostnames to load the images. image1.example.com, image2.example.com, image3.example.com, etc. This will allow for more network requests in parallel.
Use your developer tools to verify where the problem actually is. Again, I suspect it's mostly client-side. Once you know the real problem, you can solve it directly.
I would advise if you can, creating a very low resolution sprite of images that can be placed to make it look like everything is loaded, then replace this with the proper images. Without better code/samples/what your images contain/ are they dynamic I am unable to give you a real answer with solution but at least it can lead you in the correct direction.
If your images are static, this will work fine, if dynamic there is not much else that can be done. I think some examples of the webpage you are creating would be great
The reason you're having problems is simply a massive amount of HTTP requests - something you should always be trying to minimize.
Like others are saying here, you're going to want to use a spritesheet technique if possible (it sounds like it is). A spritesheet will condense all of your images into one, removing 2299 of your HTTP requests.

Load images from bottom to top?

Is it possible to load images from bottom to top?
Assume that I have a long, very long image that needs 60 seconds to load. And the content is readable from bottom to top, can I do anything to make the browsers to load my image from bottom to top so users can read it while the image is loading?
Thank you,
This is a funny "AAAAAND ITS GONE" meme related to this question.
Thanks to all you guys who have answered my question, here are some solutions I have summary:
Solution 1: (Derek's answer)
Flip the image and then display it with -webkit-transform: scaleY(-1);
Demo: http://jsfiddle.net/Nk6VP/
Solution 2 (aloisdg's answer)
Use BMP format, this way browser will load the image "upwards" but BMP is not a good file type to save big images, but its still a good try since you doesn't need to flip the image at server-side.
Demo: http://jsfiddle.net/dfbPz/
(Please disable cache to see the loading in the demo)
In fact, you can. Just use BMP format. This format is stored from the bottom.
You can find a sample of image loading upward here. (You have to click on the button "Bitmap and .rle Images to display the sample.)
From the Bitmap file format at fileformat.info:
[Regarding file header structure] If Height is a positive number, then the image is a "bottom-up" bitmap with the origin in the lower-left corner. If Height is a negative number, then the image is a "top-down" bitmap with the origin in the upper-left corner.
You can find more info on this topic in SO or this one.
You can chop it up into slices in the server and load them separately. This is probably the only way to do this since you don't really have that much control over how contents are sent.
OR, just rotate the image in the server, load it normally, and display it with transform: rotate(-180deg).
I think technology like Spdy (which is a replacement) for Http makes such stuff possible..
And even Browsers like IE/Safari don't support it,
because of the fact, that it's an Google technology
Look at this demo:
https://www.youtube.com/watch?v=zN5MYf8FtN0&feature=youtube_gdata_player
around minute 38
And yes, you would also need to split your image up in multiple parts for this... Like suggested in another comment here
LIVE DEMO
<img src="perfect.jpg" style="background-image:url(imperfect.jpg);">
The huge image will slowly appear over the placeholder by magic!
A bit of CSS for that img like background-size might also come handy. You got the idea.
If your goal is to make your content readable by user when your image loaded, you can use jquery lazy load image plugin, here a demo http://www.appelsiini.net/projects/lazyload/enabled.html
and you still can use jpeg image which have smaller size than bmp
Here is an alternate way that is Backwards-Compatible with uncommon browsers. The flipside (aha) is increased page size and more prep work. You decide if the benefits outweigh the cons for your specific needs.
Step 1: Open the image in an image editor, flip it vertically, and upload it as a new file on your site.
Step 2: Code! Details below...
JSFiddle: http://jsfiddle.net/5uLZD/1/
Libraries: Modernizer, JQuery
HTML:
<!--Source below is the 'unflipped' image-->
<img src="http://i62.tinypic.com/wratsj.jpg" id="bottomtotop">
CSS:
.flipped {
transform: rotate(-180deg);
}
JS:
if (Modernizr.csstransforms) {
// Source below is the 'flipped' image.
$("#bottomtotop").attr('src', 'http://i60.tinypic.com/2qajqqr.jpg').addClass('flipped');
}
You can alleviate the size issue by simplifying the Javascript and getting away from the frameworks (i.e, use "document.getElementById('bottomtotop')" in place of "$('bottomtotop')" and so forth), but that will take a significant amount of time and work.

Optimizing website images for Retina display

I've been trying to find a good approach to solve a very commmon problem in the retina era.
Lets say the following is given:
Create a website with responsive images
No CSS background images
Websites basic functionality must be working without JS
The websites images must be optimized for retina displays.
An easy way to solve this could be something like this: 
<img src="img.jpg" data-highres="img#2x.jpg" />
and write some kind of js to swap out img.jpg with img#2x.jpg if retina device is detected. This would work, but if I enter the website on a retina device both img.jpg and img#2x.jpg would be loaded. Not very bandwidth friendly :(
Is it possible somehow to intercept and change the src of the image before the original src is loaded?
Or do any of you have another approach in solving the problem?
In the future, you might be able to use the picture element. In the meantime, the only approach I've seen that might work is to:
Put a div or span where you want the image. Style it to have the dimensions and layout of the image. Add some kind of identifying mark to it so you can find it (e.g. class="retina-image")
Store information about the different sizes of images you have on or in the element (e.g. using data-something attributes)
Put a <noscript><img src="..." alt="..."></script> inside the div
On DOM ready:
use JS to find all the elements with the identifier from step 1
detect the type of image you want
find the attribute that tells you what URL to use for that image
add the image to the DOM inside the container from step 1
This is the approach used by the picturefill library.
This will probably be flame-bait, but here's my two cents:
The concern over bandwidth is largely a mobile platforming issue. Considering that most modern mobile platforms now adopt high pixel density displays, the demand for high res images from these devices is going to be pretty high. Why serve 3 times the image resolution 90% of the time (a low res and high res image) when you can server 2 times the resolution 100% of the time?
Hence, in some scenarios, it may be easier to just serve up the higher resolution images (halving their width/height styles) and leave it at that - thereby saving (expensive) time and energy elsewhere. In an industry where everything seems to be a compromise, this sometimes makes the most sense as an approach.
I think Quentin essentially answered your question.
What I can add is that while having an img element without a src it technically not per spec, omitting it won't break your code and you'll avoid pre-loading. Then you can just have <img data-src="" data-src2=""> and swap images in/out using JavaScript. The <noscript> element is probably the "correct" way of doing this but it makes code really verbose and I've heard some browsers will pre-load <noscript> images as well.
One service I've come across which makes images responsive (including Retina displays) is Pixtulate. They also provide the JavaScript to correctly size and replace your img.src url before the page has finished loading. Should be pretty simple to drop in.
If you do something with window.devicePixelRatio and loop through images that have data-highres attribute.
This is quite rough, but you get my drift.
$(document).ready(function() {
if (window.devicePixelRatio > 1) {
// retina
} else {
// default
}
});
Use a blank/clear 1px gif
<img src="clear.gif" data-basesrc="img1" />
Then use basesrc atttribute and append the appropriate filename in your JS.

Categories

Resources