在 PHP 中将 JPG/GIF 图像转换为 PNG?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8550015/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert JPG/GIF image to PNG in PHP?
提问by Aaron
Possible Duplicate of
Convert jpg image to gif, png & bmp format using PHP
I have a PHP form that allows image uploads and checks exif_imagetype();
to make sure an image is valid.
我有一个 PHP 表单,它允许上传图像并检查exif_imagetype();
以确保图像有效。
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?
我该怎么做呢?
回答by mario
You just need imagepng()
then. In fact it almost becomes a one-liner:
你只需要imagepng()
那时。事实上,它几乎变成了单行:
imagepng(imagecreatefromstring(file_get_contents($filename)), "output.png");
You would use $_FILES["id"]["tmp_name"]
for the filename, and a different output filename obviously. But the image format probing itself would become redundant.
$_FILES["id"]["tmp_name"]
显然,您将使用文件名和不同的输出文件名。但是图像格式探测本身将变得多余。
回答by Cyclonecode
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);
回答by Zulkhaery Basrul
<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';
}
}
?>
回答by deceze
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,这显然不能处理这种情况。