【问题标题】:PHP generate and display image thumbnailPHP生成并显示图像缩略图
【发布时间】:2013-04-12 02:19:54
【问题描述】:

我找到并修改了一个用于生成缩略图的小 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);

但上面写着The image cannot be displayed because it contains errors。我做错了什么?

【问题讨论】:

  • 使用文本编辑器查看图像的源代码;您可能会在其中看到一条 PHP 错误消息。
  • 正如我所说:“它完美地生成和保存缩略图”
  • 啊,所以您将该代码添加到 HTML 页面。那是行不通的;您需要将每个结果嵌入<img> 标记中。您可以使用 DATA URI 动态显示它们,但这在 Internet Explorer 中效果不佳,在旧版本中根本无法使用
  • 脚本顶部的空格是问题所在。非常感谢您的努力

标签: php image header thumbnails


【解决方案1】:

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

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

下面是相同的代码sn-p:

<?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);
?>

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 我不敢相信!脚本顶部有一个空格。我现在感到很惭愧:)
    【解决方案3】:

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

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

    【讨论】:

    • 还是同样的错误; The image cannot be displayed because it contains errors
    • @Goldie 然后如前所述,查看图像的源代码,看看有什么问题
    猜你喜欢
    • 1970-01-01
    • 2014-10-24
    • 2019-02-14
    • 1970-01-01
    • 2016-06-09
    • 2023-04-08
    • 2011-10-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多