PHP生成并显示图像缩略图


PHP generate and display image thumbnail

我发现并修改了一个用于生成缩略图的小php脚本

$src = (isset($_GET['file']) ? $_GET['file'] : "");
$width = (isset($_GET['maxwidth']) ? $_GET['maxwidth'] : 73);
$thname = "xxx";
$file_extension = substr($src, strrpos($src, '.')+1);
switch(strtolower($file_extension)) {
     case "gif": $content_type="image/gif"; break;
     case "png": $content_type="image/png"; break;
     case "bmp": $content_type="image/bmp"; break;
     case "jpeg":
     case "jpg": $content_type="image/jpg"; break;
     default: $content_type="image/png"; break;
}
if (list($width_orig, $height_orig, $type, $attr) = @getimagesize($src)) {
    $height = ($width / $width_orig) * $height_orig;
}
$tn = imagecreatetruecolor($width, $height) ;
$image = imagecreatefromjpeg($src) ;
imagecopyresampled($tn, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
imagejpeg($tn, './media/'.$thname.'.'.$file_extension, 90);

它完美地生成和保存缩略图。

如何动态显示这些缩略图?

我试着在脚本的底部添加这个

header('Content-Type: image/jpeg');
imagegd($image);

但上面写着CCD_ 1。我做错了什么?

php中最简单的方法是使用imagejpeg()函数。

在我的一个解决方案中,我使用这个功能创建了图像缩略图,我可以在其中指定高度和宽度。

以下是相同的代码片段:

<?php
/*www.ashishrevar.com*/
/*Function to create thumbnails*/
function make_thumb($src, $dest, $desired_width) {
  /* read the source image */
  $source_image = imagecreatefromjpeg($src);
  $width = imagesx($source_image);
  $height = imagesy($source_image);
  /* find the “desired height” of this thumbnail, relative to the desired width  */
  $desired_height = floor($height * ($desired_width / $width));
  /* create a new, “virtual” image */
  $virtual_image = imagecreatetruecolor($desired_width, $desired_height);
  /* copy source image at a resized size */
  imagecopyresampled($virtual_image, $source_image, 0, 0, 0, 0, $desired_width, $desired_height, $width, $height);
  /* create the physical thumbnail image to its destination */
  imagejpeg($virtual_image, $dest);
}
make_thumb($src, $dest, $desired_width);
?>

是否尝试结束?>在文件末尾关闭,并确保文件顶部没有空白。只需要在换行符上,图像就会中断。

http://php.net/manual/en/function.imagegd.php

header('Content-Type: image/jpeg');
imagegd($image);