Re: Resizing thumbnails to the browser

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On Sun, August 21, 2005 3:04 pm, Murray @ PlanetThoughtful wrote:
> I have a series of thumbnails on my site of photos I've taken that are
> all
> 150px in width, but of variable height. I want to randomly display one
> of
> the thumbnails each time the home page of my site is loaded in a
> column that
> is 140px wide.
>
> I'm wondering if anyone can point me at some code that would achieve
> this?
> All of the thumbnails are in jpg format.
>
> So, essentially, I'm trying to resize the thumbnails down to 140px
> wide
> while maintaining the aspect ratio of the image's height.

The scaling is easy.

It's getting the damn browsers not to screw up that's hard :-)

Actually, a cheap and easy way would be to just use:
<img src="/image150.jpg" width="140">

The penalties are:
1. The browser downloads a 150x??? image which is a TINY bit larger
than 140x???, but, really, this is negligible.

2. The browser has to scale the image, and that's "slow" if it's a
really really old slow computer.


But, to do it "right" server-side.

1. Edit a .htaccess file and add this to it:
<Files thumbnail>
  ForceType application/x-httpd-php
</Files>

This informs Apache that your 'thumbnail' file is REALLY a PHP file,
even without the .php on the end.

2. Put this in 'thumbnail':

<?php
//Untested...
  $path = "/full/hard/drive/directory/path/to/your/images/";
  $image = imagecreatefromjpeg(filename($path . $_SERVER['PATH_INFO']));
  $width = imagesx($image);
  $height = imagesy($image);
  $new_width = 140;
  $new_height = round(140 * $height/$width);
  $new_image = imagecreatetruecolor($new_width, $new_height);
  // resource dst_image, resource src_image, int dst_x, int dst_y, int
src_x, int src_y, int dst_w, int dst_h, int src_w, int src_h
  imagecopyresamples($new_image, $image, 0, 0, 0, 0, $new_width,
$new_height, $width, $height);
  ob_start();
  imagejpeg($new_image);
  $data = ob_get_contents();
  ob_end_clean();
  header("Content-type: image/jpeg");
  header("Content-length: " . strlen($data));
  echo $data;
?>

Now, to use this script, make an IMG tag like:

<img src="thumbnail/original150image.jpg" width="140">

The browser will never know the image is dynamic, nor that you are
using PHP, and that's the way you want it.

-- 
Like Music?
http://l-i-e.com/artists.htm

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux