[英]Convert JPG/GIF image to PNG in PHP?
Possible Duplicate of
可能重复
Convert jpg image to gif, png & bmp format using PHP使用 PHP 将 jpg 图像转换为 gif、png 和 bmp 格式
I have a PHP form that allows image uploads and checks exif_imagetype();
我有一个 PHP 表单,允许上传图片并检查
exif_imagetype();
to make sure an image is valid.以确保图像有效。
However, I want all formats, PNG, JPG, JPEG, and GIF, to end up being PNG once submitted.但是,我希望所有格式(PNG、JPG、JPEG 和 GIF)在提交后最终成为 PNG。
How can I go about doing this?我该怎么做呢?
You just need imagepng()
then.那么你只需要
imagepng()
。 In fact it almost becomes a one-liner:事实上,它几乎变成了单行:
imagepng(imagecreatefromstring(file_get_contents($filename)), "output.png");
You would use $_FILES["id"]["tmp_name"]
for the filename, and a different output filename obviously.您将使用
$_FILES["id"]["tmp_name"]
作为文件名,显然使用不同的输出文件名。 But the image format probing itself would become redundant.但是图像格式探测本身将变得多余。
Based on what kind of image it is you could select the correct function to open the file:根据它是什么类型的图像,您可以选择正确的函数来打开文件:
$extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
switch ($extension) {
case 'jpg':
case 'jpeg':
$image = imagecreatefromjpeg($filename);
break;
case 'gif':
$image = imagecreatefromgif($filename);
break;
case 'png':
$image = imagecreatefrompng($filename);
break;
}
Then you just save the file using:然后您只需使用以下命令保存文件:
imagepng($image, $new_filename, $quality);
It might be worth noting that this will only parse the actual extension and not really validate so the file is in the specific format.可能值得注意的是,这只会解析实际的扩展名,而不会真正验证文件是否为特定格式。 For instance, you could take a jpg image and just change the extension to png.
例如,您可以采用 jpg 图像并将扩展名更改为 png。 So a better approach is to use the
exif_imagetype()
which will return the type of image not depending on the actual extension.所以更好的方法是使用
exif_imagetype()
,它会返回不依赖于实际扩展名的图像类型。
<form method="post" enctype="multipart/form-data">
<input type="file" name="image" />
<input type="submit" name="submit" value="Submit" />
</form>
<?php
if(isset($_POST['submit']))
{
if(exif_imagetype($_FILES['image']['tmp_name']) == IMAGETYPE_GIF)
{
$newpng = 'image.png';
$png = imagepng(imagecreatefromgif($_FILES['image']['tmp_name']), $newpng);
}
elseif(exif_imagetype($_FILES['image']['tmp_name']) == IMAGETYPE_JPEG)
{
$newpng = 'image.png';
$png = imagepng(imagecreatefromjpeg($_FILES['image']['tmp_name']), $newpng);
}
else //already png
{
$newpng = 'image.png';
}
}
?>
Very simple using the gd functions :使用gd 函数非常简单:
switch (exif_imagetype($image)) {
case IMAGETYPE_GIF :
$img = imagecreatefromgif($image);
break;
case IMAGETYPE_JPEG :
$img = imagecreatefromjpeg($image);
break;
default :
throw new InvalidArgumentException('Invalid image type');
}
imagepng($img, $filename);
For conciseness this obviously doesn't handle the case if the image is already a PNG.为简洁起见,如果图像已经是 PNG,这显然不能处理这种情况。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.