本文实例讲述了php生成图片缩略图功能。分享给大家供大家参考,具体如下:
<?php
/*
* created on 2011-3-18
*
* to change the template for this generated file go to
* window - preferences - phpeclipse - php - code templates
*/
/*构造函数-生成缩略图+水印,参数说明:
$srcfile-图片文件名,
$dstfile-另存文件名,
$markwords-水印文字,
$markimage-水印图片,
$dstw-图片保存宽度,
$dsth-图片保存高度,
$rate-图片保存品质*/
makethumb("1.jpg", "aa/b.jpg", "50", "50");
function makethumb($srcfile, $dstfile, $dstw, $dsth, $rate = 100, $markwords = null, $markimage = null) {
$data = getimagesize($srcfile);
switch ($data[2]) {
case 1:
$im = @imagecreatefromgif($srcfile);
break;
case 2:
$im = @imagecreatefromjpeg($srcfile);
break;
case 3:
$im = @imagecreatefrompng($srcfile);
break;
}
if (!$im) return false;
$srcw = imagesx($im);
$srch = imagesy($im);
$dstx = 0;
$dsty = 0;
if ($srcw * $dsth > $srch * $dstw) {
$fdsth = round($srch * $dstw / $srcw);
$dsty = floor(($dsth - $fdsth) / 2);
$fdstw = $dstw;
} else {
$fdstw = round($srcw * $dsth / $srch);
$dstx = floor(($dstw - $fdstw) / 2);
$fdsth = $dsth;
}
$ni = imagecreatetruecolor($dstw, $dsth);
$dstx = ($dstx < 0) ? 0 : $dstx;
$dsty = ($dstx < 0) ? 0 : $dsty;
$dstx = ($dstx > ($dstw / 2)) ? floor($dstw / 2) : $dstx;
$dsty = ($dsty > ($dsth / 2)) ? floor($dsth / s) : $dsty;
$white = imagecolorallocate($ni, 255, 255, 255);
$black = imagecolorallocate($ni, 0, 0, 0);
imagefilledrectangle($ni, 0, 0, $dstw, $dsth, $white); // 填充背景色
imagecopyresized($ni, $im, $dstx, $dsty, 0, 0, $fdstw, $fdsth, $srcw, $srch);
if ($markwords != null) {
$markwords = iconv("gb2312", "utf-8", $markwords);
//转换文字编码
imagettftext($ni, 20, 30, 450, 560, $black, "simhei.ttf", $markwords); //写入文字水印
//参数依次为,文字大小|偏转度|横坐标|纵坐标|文字颜色|文字类型|文字内容
} elseif ($markimage != null) {
$wimage_data = getimagesize($markimage);
switch ($wimage_data[2]) {
case 1:
$wimage = @imagecreatefromgif($markimage);
break;
case 2:
$wimage = @imagecreatefromjpeg($markimage);
break;
case 3:
$wimage = @imagecreatefrompng($markimage);
break;
}
imagecopy($ni, $wimage, 500, 560, 0, 0, 88, 31); //写入图片水印,水印图片大小默认为88*31
imagedestroy($wimage);
}
imagejpeg($ni, $dstfile, $rate);
imagejpeg($ni, $srcfile, $rate);
imagedestroy($im);
imagedestroy($ni);
}
?>
希望本文所述对大家php程序设计有所帮助。
更多php生成图片缩略图功能。