DazzledKid
DazzledKid

Reputation: 396

Is there a way to use JavaScript to crop & resize an image before displaying it?

I have a bunch of images held on a third party server that I want to load and display as thumbnails on a webpage...

Can I use JavaScript to load each image, crop and resize them to all be the same size, then display them in a grid on the page?

Ideally, I'd like to be able to do it client side. I don't really want to pre-load and process them on the server as I do not want to increase bandwidth usage..

Upvotes: 2

Views: 5748

Answers (4)

Dejan Cosic
Dejan Cosic

Reputation: 21

Maybe this is not exactly Javascript or Jquery based solution, but this script can help a lot on eCommerce websites or other types of sites where pages are full of thumbnails. It have cache mechanism, so images are processed only once: http://shiftingpixel.com/2008/03/03/smart-image-resizer/

Upvotes: 2

Thijs
Thijs

Reputation: 3055

Javascript is a client sided language. So the images must be downloaded first before javascript can control them. If you're loading a lot of images it's best to make a server sided script that crops the images before loading them.

Upvotes: 0

Jon
Jon

Reputation: 437534

You can put each image inside a block container with fixed dimensions and overflow: hidden, thus effectively cropping them (you can also position the image inside the container with negative top and left values to select which part of the image will be visible). All of this is standard CSS fare. The same goes for displaying the elements in a grid layout. See an example.

However, be advised that this kind of solution, although it requires almost no preparation, can be deceptively easy to follow. The user will still have to download the full, uncropped image for every cropped element you show in the page, which could turn out to be many MBs of data.

Depending on what your use case is, it might be far more preferable to adopt a server-side solution that pre-processes the images.

Upvotes: 7

Marc B
Marc B

Reputation: 360762

JS can't directly crop/resize an image, unless you're using a <canvas> tag. At most it can fake a crop by putting the image into another element with overflow:hidden and adjusting offsets/boundaries. You can fake a resize by setting the image's height/width/zoom CSS attributes.

But if you're concerned about bandwidth, consider that a client-side resizer requires the client to load a full-sized image from your server, BEFORE it can do any kind of adjustments on it.

Upvotes: 1

Related Questions