2012-07-31 105 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); 
?>