PHP实现图片缩放
原创 52cxy 11-25 09:18 阅读数:453

PHP实现图片缩放代码:

/**
  * 图像缩放
 * @param $src string  原图路径
 * @param $dst string  裁剪图片路径
 * @param $zoom double 缩放比例
 */
function imageZoom($src, $dst, $ratio)
{
  list($sourceWidth, $sourceHeight, $type) = getimagesize($src);
  $sourceRatio = $sourceWidth/$sourceHeight;
  $sourceX = 0;
  $sourceY = 0;

  $targetWidth = $sourceWidth * $ratio;
  $targetHeight = $sourceHeight * $ratio;

  $sourceImage = null;
  if($type == 1) $sourceImage = imagecreatefromgif($src);
  elseif($type == 2) $sourceImage = imagecreatefromjpeg($src);
  elseif($type == 3) $sourceImage = imagecreatefrompng($src);

  $tmpImage = imagecreatetruecolor($sourceWidth, $sourceHeight);
  $targetImage = imagecreatetruecolor($targetWidth, $targetHeight);
  //copy
  imagecopy($tmpImage, $sourceImage, 0, 0, $sourceX, $sourceY, $sourceWidth, $sourceHeight);
  //zoom
  imagecopyresampled($targetImage, $tmpImage, 0, 0, 0, 0, $targetWidth, $targetHeight, $sourceWidth, $sourceHeight);

  imagepng($targetImage, $dst);

  //clear data
  imagedestroy($tmpImage);
  imagedestroy($sourceImage);
  imagedestroy($targetImage);
}

测试代码:

imageZoom("sample.jpg", "last.png", 0.8);


共0条评论
我要评论