2009-11-13 24 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。