views:

94

answers:

3

Hi friends,
I am working with php and ajax. I'm able to retrive an image from a database, but I would like to show the image in 100px x 100px size, but it just retrieves the original image size and spoiling the aligning work that I did.

How can I fix the width and height for a retrieved image. I have used the following code for retriving from database

$query = "select bin_data from imageupload where Id=1;";
$result = mysql_query($query, $con);
$result_data = mysql_fetch_array($result, MYSQL_ASSOC);
header("Content-type: image/jpeg") ;
echo $result_data['bin_data'];
A: 

You can use PHP's gd module to do this. See the imagecopyresampled function and the examples in it's documentation.

Note that this is an expensive operation, so you should either save a resized image when it's uploaded or cache the result.

Lukáš Lalinský
+1  A: 

These are the steps this code performs

  1. Copies source image
  2. Calculates image dimensions
  3. Resizes image (you specify max height/width)
  4. Retains aspect ratio
  5. Writes destination image

This was created from a variety of code snippets I've found here at php.net and other places on the web.
I take no credit for any of this code other than putting the pieces together. http://www.php.net/manual/en/function.getimagesize.php

    <?php

$source_pic = 'images/source.jpg';
$destination_pic = 'images/destination.jpg';
$max_width = 500;
$max_height = 500;

$src = imagecreatefromjpeg($source_pic);
list($width,$height)=getimagesize($source_pic);

$x_ratio = $max_width / $width;
$y_ratio = $max_height / $height;

if( ($width <= $max_width) && ($height <= $max_height) ){
    $tn_width = $width;
    $tn_height = $height;
    }elseif (($x_ratio * $height) < $max_height){
        $tn_height = ceil($x_ratio * $height);
        $tn_width = $max_width;
    }else{
        $tn_width = ceil($y_ratio * $width);
        $tn_height = $max_height;
}

$tmp=imagecreatetruecolor($tn_width,$tn_height);
imagecopyresampled($tmp,$src,0,0,0,0,$tn_width, $tn_height,$width,$height);

imagejpeg($tmp,$destination_pic,100);
imagedestroy($src);
imagedestroy($tmp);

?>
Pasta
+1  A: 

Resize an image is CPU intensive for the server, if bandwith is not a problem:

<img src="theimage.jpg" style="width:100px; height:100px;" />

Modern browsers filters the image so it looks good when resized.

It you want to keep aspect ratio and crop, do this:

<div style="width:100px; height:100px; overflow:hidden; display:inline-block;">
  <img src="theimage.jpg" style="width:100px;" />
</div>

Also consider using Pasta's answer plus an image cache. To resize only once every picture without loosing the original.

Pedro Ladaria