可能重复:
使用php gd2 将图像从一种格式保存到另一种格式
我正在将任何图像格式转换为JPEG或JPG。将图像转换为jpg的代码为
function converttojpg($originalimg)
{
$filetype = @end(explode(".", $originalimg));
echo $originalimg . " asdasdfs";
if (strtolower($filetype) == 'jpg' or strtolower($filetype) == 'jpeg')
{
$srcImg = imagecreatefromjpeg($originalimg);
imagejpeg($srcImg,$originalimg,100);
imagedestroy($srcImg);
}
if (strtolower($filetype) == 'png')
{
$srcImg = imagecreatefrompng($originalimg);
imagejpeg($srcImg,$originalimg,100);
imagedestroy($srcImg);
}
if (strtolower($filetype) == 'gif')
{
echo "executed";
$srcImg = imagecreatefromgif($originalimg);
imagejpeg($srcImg,$originalimg,100);
imagedestroy($srcImg);
}
}
之后,我调整转换后的图像的大小,其代码为
function resizeImage($originalImage,$toWidth,$toHeight)
{
// Get the original geometry and calculate scales
list($width, $height) = getimagesize($originalImage);
$xscale=$width/$toWidth;
$yscale=$height/$toHeight;
// Recalculate new size with default ratio
if ($yscale>$xscale)
{
$new_width = round($width * (1/$yscale));
$new_height = round($height * (1/$yscale));
}
else
{
$new_width = round($width * (1/$xscale));
$new_height = round($height * (1/$xscale));
}
// Resize the original image
$imageResized = imagecreatetruecolor($new_width, $new_height);
$imageTmp = imagecreatefromjpeg ($originalImage);
imagecopyresampled($imageResized, $imageTmp, 0, 0, 0, 0, $new_width, $new_height, $width, $height );
return $imageResized;
}
在每张图像上,它都会报告错误和警告
Warning: imagecreatefromjpeg() [function.imagecreatefromjpeg]: gd-jpeg, libjpeg: recoverable error: Corrupt JPEG data: 9 extraneous bytes before marker 0xd9 in E:'xampp'htdocs'photo'functions.php on line 33
Warning: imagecreatefromjpeg() [function.imagecreatefromjpeg]: 'userphotos/corrupted_image_1.jpg' is not a valid JPEG file in E:'xampp'htdocs'photo'functions.php on line 33
Warning: imagejpeg() expects parameter 1 to be resource, boolean given in E:'xampp'htdocs'photo'functions.php on line 34
Warning: imagedestroy() expects parameter 1 to be resource, boolean given in E:'xampp'htdocs'photo'functions.php on line 35
Warning: imagecreatefromjpeg() [function.imagecreatefromjpeg]: gd-jpeg, libjpeg: recoverable error: Corrupt JPEG data: 9 extraneous bytes before marker 0xd9 in E:'xampp'htdocs'photo'functions.php on line 22
Warning: imagecreatefromjpeg() [function.imagecreatefromjpeg]: 'userphotos/53.jpg' is not a valid JPEG file in E:'xampp'htdocs'photo'functions.php on line 22
Warning: imagecopyresampled() expects parameter 2 to be resource, boolean given in E:'xampp'htdocs'photo'functions.php on line 23
userphotos/MG_diesel-04.gif_thumb.png asdasdfsuserphotos/Porsche_911_996_Carrera_4S.jpg asdasdfs
请帮我解决那个问题。我必须完成它。
不要使用扩展名来确定文件类型。要检查给定的文件是否是图像,并且其格式允许GD对其进行操作,请使用getimagesize
<?php
$image = @imagecreatefromstring(file_get_contents($file_path));
if ($image === false) {
throw new Exception (sprintf('invalid image or file not found, file=%s', $file_path));
}
?>
imagecreatefromstring检测图像类型并创建图像资源,否则将引发异常。