我是php的新手,我正在尝试制作缩略图
$src是图像的路径$thumbWidth是所需的宽度$imageName并不重要,它需要传递给为缩略图生成html代码的函数。
问题出现在第174行,我评论道,如果图像是jpeg文件,函数返回false,那么$source_image为false,有人能解释为什么吗?
这是我的方法:
function makeThumb( $src, $thumbWidth, $imageName )
{
$count = 0;
$len = strlen($src);
$indexlen = $len - 1;
$sourceArray = str_split($src);
for($i = $indexlen; $i > -1; $i--)
{
if($sourceArray[$i] == '.')
{
$count = $count + 1;
if($count == 1)
{
$hold = $i;
}
}
}
$ending = substr($src, $hold, $len);
if($ending === '.gif')
{
$type = '.gif';
$source_image = imagecreatefromgif($src);
}
if($ending === '.jpeg' || $ending === '.pjpeg' || $ending === '.jpg')
{
$type = '.jpg';
$source_image = imagecreatefromjpeg($src);
}
if($ending === '.png')
{
$type = '.png';
$source_image = imagecreatefrompng($src);
}
else
{
//throw new Exception('This file is not in JPG, GIF, or PNG format!');
$type = null;
}
/* read the source image */
if($ending = null)
{ return null; }
$width = imagesx($src);
$height = imagesy($src);
$newWidth = $thumbWidth;
/* find the "desired height" of this thumbnail, relative to the desired width */
$newHeight = floor($height * ($newWidth / $width));
/* create a new, "virtual" image */
$tempImg = imagecreatetruecolor($desired_width, $desired_height);
$pic = formatImage($tempImg, $imageName);
return $pic;
/* 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);
}
您确定该图像是有效的jpeg图像吗?
您可以通过扩展来检查图像的类型。您可以用一种简单得多的方式检查是否获得扩展。您还应该检查文件是否存在:
function makeThumb( $src, $thumbWidth, $imageName )
{
if(!file_exists($src))
throw new Exception('The file '.$src.' does not exist.');
$ext = pathinfo($src, PATHINFO_EXTENSION);
但是使用扩展来检查图像的类型是不可靠的。使用getimagesize
函数还有另一种检查方法:
function makeThumb( $src, $thumbWidth, $imageName )
{
if(!file_exists($src))
throw new Exception('The file '.$src.' does not exist.');
$info = getimagesize($src);
if($info === false)
throw new Exception('This file is not a valid image');
$type = $info[2];
$width = $info[0]; // you don't need to use the imagesx and imagesy functions
$height = $info[1];
switch($type) {
case IMAGETYPE_JPEG:
$source_image = imagecreatefromjpeg($src);
break;
case IMAGETYPE_GIF:
$source_image = imagecreatefromgif($src);
break;
case IMAGETYPE_PNG:
$source_image = imagecreatefrompng($src);
break;
default:
throw new Exception('This file is not in JPG, GIF, or PNG format!');
}
$newWidth = $thumbWidth;
// ..and here goes the rest of your code
请注意-我没有检查你的代码的其余部分,因为你的问题与函数的第一部分有关。