2009-11-13 67 views
0

如何檢查圖像是否爲PNG,GIF,TIFF和JPG,如果是這樣,請創建縮略圖並將其保存到拇指文件中。如何使用PHP檢查並查看圖像擴展?

到目前爲止,我可以檢查並保存JPEG圖像。

以下是下面的代碼。

<?php 

//Name you want to save your file as 
$save = 'members/3/images/thumbs/thumb-pic.jpg'; 

$file = 'members/3/images/pic.jpg'; 
echo "Creating file: $save"; 


list($width, $height) = getimagesize($file) ; 

if ($width >= 180){ 
    $modwidth = 180; 
    $modheight = ((180.0/$width) * $height); 
} else { 
    $modwidth = $width; 
    $modheight = $height; 
} 

$tn = imagecreatetruecolor($modwidth, $modheight) ; 
$image = imagecreatefromjpeg($file) ; 
imagecopyresampled($tn, $image, 0, 0, 0, 0, $modwidth, $modheight, $width, $height) ; 

// Here we are saving the .jpg, you can make this gif or png if you want 
//the file name is set above, and the quality is set to 100% 
imagejpeg($tn, $save, 100) ; 
?> 

回答

1

我會去與ImageMagick的模塊,具體Imagick::identifyImage()方法。它像下面那樣返回數組 - 檢查格式的密鑰。

Array 
(
    [imageName] => /some/path/image.jpg 
    [format] => JPEG (Joint Photographic Experts Group JFIF format) 
    [geometry] => Array 
     (
      [width] => 90 
      [height] => 90 
     ) 

    [type] => TrueColor 
    [colorSpace] => RGB 
    [resolution] => Array 
     (
      [x] => 300 
      [y] => 300 
     ) 

    [units] => PixelsPerInch 
    [fileSize] => 1.88672kb 
    [compression] => JPEG 
    [signature] => 9a6dc8f604f97d0d691c0286176ddf992e188f0bebba98494b2146ee2d7118da 
) 
+0

如何將此代碼添加到我的代碼中? – ImAGe 2009-11-13 07:49:14

+0

依靠imagick生成縮略圖這樣簡單的東西簡直就是一個粗略的...我參加過的主持人並不多。 – brianreavis 2009-11-13 07:51:16

2

這裏有一個辦法做到這一點,使用關聯數組每種格式分配給適當的imagecreatefrom...功能:

$handlers = array(
    'jpg' => 'imagecreatefromjpeg', 
    'jpeg' => 'imagecreatefromjpeg', 
    'png' => 'imagecreatefrompng', 
    'gif' => 'imagecreatefromgif' 
); 

$extension = strtolower(substr($file, strrpos($file, '.')+1)); 
if ($handler = $handlers[$extension]){ 
    $image = $handler($file); 
    //do the rest of your thumbnail stuff here 
}else{ 
    //throw an 'invalid image' error 
} 
0

您可以使用MIME功能。嘗試echo mime_content_type('php.gif')

0

我會這樣做,因爲brianreavis已回答,但我不會依賴圖像文件的擴展名來確定圖像類型,而寧願使用exif_imagetype函數。

$filetypeinfo = exif_imagetype($file); 
switch($filetypeinfo){ 
    case 1: 
    $extension = 'gif'; 
    break; 
    case 2: 
    $extension = 'jpg'; 
    break; 
    case 3: 
    $extension = 'png'; 
    break; 
} 
1

你已經明白了。

使用exif_image type或使用pathinfo($image_path, PATHINFO_EXTENSION)獲取文件類型。然後將其保存到一個變量(例如$ type)。

然後,使用switch語句從*函數運行相應的圖像(檢查imagefromjpeg頁面「另請參見」列表),使用您設置的filetype變量作爲開關比較。

最後,使用相同的基本switch語句來運行image *(imagepng等[請查看imagejpeg頁面上的相關內容])將拇指保存回原始類型(這對於png很重要和可能具有透明度的gif,在這種情況下,您需要啓用保存透明度)。

順便說一句,對於透明度,請檢查imagesavealpha和imagealphablending。