php图像上传显示缩略图,php – 从上传的图像创建缩略图

更新:

如果您想利用Imagick(如果它安装在您的服务器上)。注意:我没有使用Imagick的自然写入文件,因为我在我的服务器上遇到问题。文件放置内容也是如此。

/**

*

* Generate Thumbnail using Imagick class

*

* @param string $img

* @param string $width

* @param string $height

* @param int $quality

* @return boolean on true

* @throws Exception

* @throws ImagickException

*/

function generateThumbnail($img, $width, $height, $quality = 90)

{

if (is_file($img)) {

$imagick = new Imagick(realpath($img));

$imagick->setImageFormat('jpeg');

$imagick->setImageCompression(Imagick::COMPRESSION_JPEG);

$imagick->setImageCompressionQuality($quality);

$imagick->thumbnailImage($width, $height, false, false);

$filename_no_ext = reset(explode('.', $img));

if (file_put_contents($filename_no_ext . '_thumb' . '.jpg', $imagick) === false) {

throw new Exception("Could not put contents.");

}

return true;

}

else {

throw new Exception("No valid image provided with {$img}.");

}

}

// example usage

try {

generateThumbnail('test.jpg', 100, 50, 65);

}

catch (ImagickException $e) {

echo $e->getMessage();

}

catch (Exception $e) {

echo $e->getMessage();

}

?>

我一直在使用这个,只需在存储原始图像后执行该功能,并使用该位置创建缩略图。根据您的喜好编辑…

function makeThumbnails($updir, $img, $id)

{

$thumbnail_width = 134;

$thumbnail_height = 189;

$thumb_beforeword = "thumb";

$arr_image_details = getimagesize("$updir" . $id . '_' . "$img"); // pass id to thumb name

$original_width = $arr_image_details[0];

$original_height = $arr_image_details[1];

if ($original_width > $original_height) {

$new_width = $thumbnail_width;

$new_height = intval($original_height * $new_width / $original_width);

} else {

$new_height = $thumbnail_height;

$new_width = intval($original_width * $new_height / $original_height);

}

$dest_x = intval(($thumbnail_width - $new_width) / 2);

$dest_y = intval(($thumbnail_height - $new_height) / 2);

if ($arr_image_details[2] == IMAGETYPE_GIF) {

$imgt = "ImageGIF";

$imgcreatefrom = "ImageCreateFromGIF";

}

if ($arr_image_details[2] == IMAGETYPE_JPEG) {

$imgt = "ImageJPEG";

$imgcreatefrom = "ImageCreateFromJPEG";

}

if ($arr_image_details[2] == IMAGETYPE_PNG) {

$imgt = "ImagePNG";

$imgcreatefrom = "ImageCreateFromPNG";

}

if ($imgt) {

$old_image = $imgcreatefrom("$updir" . $id . '_' . "$img");

$new_image = imagecreatetruecolor($thumbnail_width, $thumbnail_height);

imagecopyresized($new_image, $old_image, $dest_x, $dest_y, 0, 0, $new_width, $new_height, $original_width, $original_height);

$imgt($new_image, "$updir" . $id . '_' . "$thumb_beforeword" . "$img");

}

}

上述功能创建具有统一缩略图大小的图像。如果图像与指定的缩略图大小(按比例)没有相同的尺寸,则它的顶部和底部只有黑色空间。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值