用于创建缩略图的部分工作功能


Partially working function for creating thumbnails

我有一个制作缩略图的部分功能,但10%的图像没有被创建为缩略图,它们是完全相同的10%。其余90%有效。我不知道为什么。请看一下我的代码:

<?php
$image = "511photo.jpg";
if ($image) {
make_thumb("uploads", "thumbnails", $image, 500);
}
function make_thumb($imageFrom, $imageTo, $image, $thumbWidth) {
/* read the source image */
$getFrom = $imageFrom."/".$image;
$source_image = imagecreatefromjpeg($getFrom);
$width = imagesx($source_image);
$height = imagesy($source_image);
/* find the "desired height" of this thumbnail, relative to the desired width  */
$thumbHeight = floor($height * ($thumbWidth / $width));
/* create a new, "virtual" image */
$virtual_image = imagecreatetruecolor($thumbWidth, $thumbHeight);
/* copy source image at a resized size */
imagecopyresampled($virtual_image, $source_image, 0, 0, 0, 0, $thumbWidth, $thumbHeight, $width, $height);
/* create the physical thumbnail image to its destination */
$dest = $imageTo."/".$image;
imagejpeg($virtual_image, $dest);
} //end of function make_thumb($imageFrom, $imageTo, $image, $thumbWidth)
?>

注意:这是另外几个不起作用的$image:

"434cute-anime-couple-drawing-on-tumblr.png"
"503anime_head_vectorized_by_cona_cru-d784ls0.png"

注意:是的,我确信它们都在上传文件夹中——老实说,我已经检查了一遍又一遍,现在我很困惑。。。

这是因为您将imagecreatefromjpeg()用于png图像。您需要对这些图像使用imagecreatefrompng()

$source_image = imagecreatefrompng($getFrom);

对于检查图像类型,可以使用exif_imagetype()函数:

$imageType =  exif_imagetype($getFrom);
if($imageType == IMAGETYPE_PNG) {
    //It's PNG
} elseif($imageType == IMAGETYPE_JPEG) {
    //It's JPEG
} //You can check more types here.

检查文件类型,并在条件下使用imagejpeg函数添加此代码。例如,添加变量和值

if($fileType=="image/png"){
   $im=ImageCreateFromPNG($add); 
   $width=ImageSx($im);              // Original picture width is stored
   $height=ImageSy($im);             // Original picture height is stored
   $newimage=imagecreatetruecolor($n_width,$n_height);                 
   imageCopyResized($newimage,$im,0,0,0,0,$n_width,$n_height,$width,$height);
   ImagePng($newimage,$tsrc);
   chmod("$tsrc",0777);
}