Posted By

oso96_2000 on 02/11/07


Tagged

php image gd thumbnail


Versions (?)

Who likes this?

2 people have marked this snippet as a favorite

luman
vali29


function thumb


 / Published in: PHP
 

With this function you can make a thumbnail from an image. Usage: $image = "something.jpg"; thumb($image, 100, 100);

It can be easy modified to accept other types of images, actually only support jpeg, gif and png. Gif images lost their animation, and png or gif image lost their transparency.

  1. <?php
  2. function thumb($img, $w, $h, $fill = true) {
  3. if (!extension_loaded('gd') && !extension_loaded('gd2')) {
  4. trigger_error("No dispones de la libreria GD para generar la imagen.", E_USER_WARNING);
  5. return false;
  6. }
  7.  
  8. //$ext = strtolower(array_pop(explode(".",$img)));
  9. $imgInfo = getimagesize($img);
  10. switch ($imgInfo[2]) {
  11. case 1: $im = imagecreatefromgif($img); break;
  12. case 2: $im = imagecreatefromjpeg($img); break;
  13. case 3: $im = imagecreatefrompng($img); break;
  14. default: trigger_error('Tipo de imagen no reconocido.', E_USER_WARNING); break;
  15. }
  16.  
  17. if ($imgInfo[0] <= $w && $imgInfo[1] <= $h && !$fill) {
  18. $nHeight = $imgInfo[1];
  19. $nWidth = $imgInfo[0];
  20. }else{
  21. if ($w/$imgInfo[0] < $h/$imgInfo[1]) {
  22. $nWidth = $w;
  23. $nHeight = $imgInfo[1]*($w/$imgInfo[0]);
  24. }else{
  25. $nWidth = $imgInfo[0]*($h/$imgInfo[1]);
  26. $nHeight = $h;
  27. }
  28. }
  29.  
  30. $nWidth = round($nWidth);
  31. $nHeight = round($nHeight);
  32.  
  33. $newImg = imagecreatetruecolor($nWidth, $nHeight);
  34.  
  35. imagecopyresampled($newImg, $im, 0, 0, 0, 0, $nWidth, $nHeight, $imgInfo[0], $imgInfo[1]);
  36.  
  37. header("Content-type: ". $imgInfo['mime']);
  38.  
  39. switch ($imgInfo[2]) {
  40. case 1: imagegif($newImg); break;
  41. case 2: imagejpeg($newImg); break;
  42. case 3: imagepng($newImg); break;
  43. default: trigger_error('Imposible mostrar la imagen.', E_USER_WARNING); break;
  44. }
  45.  
  46. imagedestroy($newImg);
  47. }
  48. ?>

Report this snippet  

You need to login to post a comment.