我想上传和调整不同扩展名的图片。 php从原始图片的中心裁剪出最大可能的正方形,然后将其保存为360 * 360像素。
代码适用于jpeg文件,但是使用gif,bmp和png我得到一个33字节大小的损坏文件。
以下是大部分代码:
$file_temp = $_FILES["pic"]["tmp_name"];
list ($width, $height, $type) = getimagesize ($file_temp);
$picture_name = "... a name.ext ...";
$upload = "... some dir/$picture_name";
if (move_uploaded_file($file_temp, "$upload"))
{
//switches content-type and calls the imagecreatefrom... function
if ($type == 1)
{
header ('Content-Type: image/gif');
$image = imagecreatefromgif($upload);
}
elseif ($type == 2)
{
header ('Content-Type: image/jpeg');
$image = imagecreatefromjpeg($upload);
}
elseif ($type == 3)
{
header ('Content-Type: image/png');
$image = imagecreatefrompng($upload);
}
else
{
header ('Content-Type: image/x-ms-bmp');
$image = imagecreatefromwbmp($upload);
}
$image_p = imagecreatetruecolor(360, 360);
//this code below should preserve transparency but I couldn't try it out for now...
if($type==1 or $type==3)
{
imagecolortransparent($image_p, imagecolorallocatealpha($image_p, 0, 0, 0, 127));
imagealphablending($image_p, true);
imagesavealpha($image_p, true);
}
//this part is for cropping
$x=0;
$y=0;
if ($width > $height)
{
$x= ($width - $height)/2;
$width = $height;
}
else
{
$y = ($height - $width)/2;
$height = $width;
}
imagecopyresampled ($image_p, $image, 0, 0, $x, $y, 360, 360, $width, $height);
if ($type == 1)
imagegif ($image_p, $upload, 80);
elseif ($type == 2)
imagejpeg ($image_p, $upload, 80);
elseif ($type == 3)
imagepng ($image_p, $upload, 80);
else
imagewbmp ($image_p, $upload, 80);
}
因此,只有正确处理jpeg文件,gif,png和bmp文件才能正确处理。我没有想法......
提前谢谢!
答案 0 :(得分:3)
您的PHP可能无法编译并支持这些格式。运行phpinfo()并检查输出,如下所示:
GD Support => enabled
GD Version => bundled (2.0.34 compatible)
GIF Read Support => enabled
GIF Create Support => enabled
PNG Support => enabled
libPNG Version => 1.2.10
答案 1 :(得分:1)
由于你似乎每次为jpg之外的图像获取一个损坏的33字节图像文件,这可能是一个PHP错误,正在写入文件(因为看起来你的PHP文件直接显示图像内容,从您的内容类型标题)。您是否尝试在文本编辑器中打开文件并查看其内容?如果它标记为垃圾,那么它是一个错误,但如果它是一个PHP警告,你的PHP版本可能不支持那些扩展的图像类型。那,或者你的代码中可能会出现警告。