Задача: Масштабирование, пропорциональное изменение размеров картинки
Исходник: Вычисление коэфициэнта пропорции от большей величины, язык: php [code #99, hits: 8836]
автор: this [добавлен: 26.03.2006]
  1. function ResizeImg2($strSourceImagePath, $strDestImagePath, $intMaxWidth = 200, $intMaxHeight = 200)
  2. {
  3. $arrImageProps = getimagesize($strSourceImagePath);
  4. $intImgWidth = $arrImageProps[0];
  5. $intImgHeight = $arrImageProps[1];
  6. $intImgType = $arrImageProps[2];
  7.  
  8. switch( $intImgType) {
  9. case 1: $rscImg = ImageCreateFromGif($strSourceImagePath); break;
  10. case 2: $rscImg = ImageCreateFromJpeg($strSourceImagePath); break;
  11. case 3: $rscImg = ImageCreateFromPng($strSourceImagePath); break;
  12. default: return false;
  13. }
  14.  
  15. if ( !$rscImg) return false;
  16.  
  17. if ($intImgWidth > $intImgHeight) {
  18. $fltRatio = floatval($intMaxWidth / $intImgWidth);
  19. } else {
  20. $fltRatio = floatval($intMaxHeight / $intImgHeight);
  21. }
  22.  
  23. $intNewWidth = intval($fltRatio * $intImgWidth);
  24. $intNewHeight = intval($fltRatio * $intImgHeight);
  25.  
  26. $rscNewImg = ImageCreate($intNewWidth, $intNewHeight);
  27. if (!ImageCopyResized($rscNewImg, $rscImg, 0, 0,0, 0, $intNewWidth, $intNewHeight, $intImgWidth, $intImgHeight)) return false;
  28.  
  29. switch($intImgType) {
  30. case 1: $retVal = ImageGIF($rscNewImg, $strDestImagePath); break;
  31. case 3: $retVal = ImagePNG($rscNewImg, $strDestImagePath); break;
  32. case 2: $retVal = ImageJPEG($rscNewImg, $strDestImagePath, 90); break;
  33. default: return false;
  34. }
  35.  
  36. ImageDestroy($rscNewImg);
  37.  
  38. return true;
  39. }
  40.  
  41. // Тест:
  42. $strTestImgPath = dirname(__FILE__).'/testimg.gif';
  43. $strDestImgPath = dirname(__FILE__).'/testimg.preview.gif';
  44.  
  45. print (int)ResizeImg2($strTestImgPath, $strDestImgPath, 300, 300);
Масштабирование производится на основе вычисления коэфициэнта пропорции от большей величины (высоты или ширины исходной картинки).

В php должна быть подключена библиотека GD.
Тестировалось на: Apache 1.3.33, PHP 5.0

+добавить реализацию