PHP在imagecopyresampled之后保存图像

时间:2012-02-26 11:22:03

标签: php image

$image_p = imagecreatetruecolor($new_width, $new_height);
$image = imagecreatefromjpeg($filename);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);

如何将已调整大小的图像保存到文件夹/? 我如何检测图像类型是jpg / png / gif?

6 个答案:

答案 0 :(得分:13)

要将图像保存到文件,您可以使用以下任何一种文件:imagejpeg()imagepng()imagegif(),具体取决于您所需的输出格式。

要检测图像类型,您只需检查文件的扩展名并自行确定。但是,有时人们手动更改图像文件的扩展名,认为实际上会更改图像类型,因此检查imagecreatefrom是否返回图像资源而不是false是一个好主意。

快速返回文件的扩展名:

$ext = pathinfo($path_to_file, PATHINFO_EXTENSION);

Manual entry on pathinfo()

答案 1 :(得分:5)

添加此代码

imagepng($iOut,'pic/mypic.png',3);

&安培;此代码用于从外部源获取您的图片格式

$link='http://example.com/example.png';
echo (substr ($link,strrpos ($link,".")+1));

答案 2 :(得分:4)

您可以定义任何类型的图像:

 // Save the image as 'simpletext.jpg'
 imagejpeg($im, 'path/to/your/image.jpg');
 // or another image
 imagepng($im, 'path/to/your/image.png');

请参阅此处的示例http://php.net/manual/en/function.imagecopyresampled.php

答案 3 :(得分:2)

$filename = 'path/to/original/file.xxx'; // where xxx is file type (jpg, gif, or png)
$newfilename = 'path/to/resized/file.xxx'; // where xxx is file type (jpg, gif, or png)
$path_parts = pathinfo($filename);
if ($path_parts['extension'] == 'jpg') {
    $image_p = imagecreatetruecolor($new_width, $new_height);
    $image = imagecreatefromjpeg($filename);
    imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
    imagejpeg($image_p, $newfilename);
} elseif ($path_parts['extension'] == 'gif') {
    $image_p = imagecreatetruecolor($new_width, $new_height);
    $image = imagecreatefromgif($filename);
    imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
    imagegif($image_p, $newfilename);
} elseif ($path_parts['extension'] == 'png') {
    $image_p = imagecreatetruecolor($new_width, $new_height);
    $image = imagecreatefrompng($filename);
    imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
    imagepng($image_p, $newfilename);
} else {
        echo "Source file is not a supported image file type.";
}

答案 4 :(得分:2)

应用imagecopyresampled()后,$dst_image将成为您的图片资源标识符。

仅应用imagecopyresampled()函数不会自动将其保存到文件系统。

所以你需要使用其中一个函数imagejpeg()imagepng()

来保存它
// Output
imagejpeg($dst_image, 'new-image.jpg', 100);

答案 5 :(得分:0)

将图像保存为jpg,请参阅imagejpeg函数

http://nz.php.net/manual/en/function.imagejpeg.php

使用

获取图片扩展名
$path_parts = pathinfo($filename);
echo $path_parts['extension'];