2012-07-31 94 views
1

我发现和修饰的小PHP脚本用于生成缩略图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); 

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

如何在飞行中显示这些缩略图?

我tryed到一个脚本

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

的底部添加这一点,但它说The image cannot be displayed because it contains errors。我究竟做错了什么?

+3

查找范围中使用文本编辑器图像的源代码;那里你可能会有一个PHP错误信息。 – 2012-07-31 11:47:50

+0

正如我所说:“它完全生成并保存缩略图” – Goldie 2012-07-31 11:49:56

+0

嗯,所以你将这个代码添加到了HTML页面。那不行;您需要将每个结果嵌入''标签中。您可以使用DATA URI来动态显示它们,但在Internet Explorer中不能正常工作,而且在旧版本中根本无法正常工作 – 2012-07-31 11:55:54

回答

2

尝试采取封闭?>关闭在文件的结尾,并确保没有在文件的顶部没有空格。它只需要在换行符上,图像就会被打破。

+0

我不能相信它!脚本顶部有一个空格。我现在感到羞愧:) – Goldie 2012-07-31 12:15:38

2

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

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

仍然一样的错误; '图像不能显示,因为它包含错误' – Goldie 2012-07-31 12:06:10

+1

@Goldie然后说,*查看图像的源代码,看看有什么不对* – 2012-07-31 12:09:48

4

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