简体   繁体   English

如何将Base64 PNG转换为JPG图像?

[英]How to convert a Base64 PNG to a JPG image?

I have this Base64 PNG, which I want to decode to JPG. 我有这个Base64 PNG,我想解码到JPG。 If I convert to PNG it works fine, using: 如果我转换为PNG它工作正常,使用:

list($type, $data) = explode(';', $data);
list(, $data)      = explode(',', $data);
$data = base64_decode($data);
file_put_contents('myDirectory/filename.png', $data);

But if I try to save it as JPG, it comes out in black and white using ( MyDirectory/filename.jpg ). 但是,如果我尝试将其保存为JPG,则使用( MyDirectory/filename.jpg )以黑白方式显示。

How do I convert it to a JPG? 如何将其转换为JPG? here is an example of my Base64 PNG: 这是我的Base64 PNG的一个例子:

data:image/png;base64,iVBORw0KGgoAAAANSUhE...

Base64 is an encoding format that is strictly used to convert data into a text transportable format. Base64是一种编码格式,严格用于将数据转换为文本可传输格式。 Whatever is in that encoding format needs to be converted further if you want another format. 如果你想要另一种格式,那么编码格式需要进一步转换。 So if you want the PNG to be a JPEG, after the Base64 decode it needs to be converted by another tool into a JPEG. 因此,如果您希望PNG为JPEG,则在Base64解码后,需要将其他工具转换为JPEG。 This thread has some good suggestions. 这个帖子有一些很好的建议。 @Andrew Moore who answers the thread recommends using a function like this. 回答线程的@Andrew Moore建议使用这样的函数。 Be sure to have the GD library installed as part of your PHP setup: 确保在PHP设置中安装GD库:

// Quality is a number between 0 (best compression) and 100 (best quality)
function png2jpg($originalFile, $outputFile, $quality) {
    $image = imagecreatefrompng($originalFile);
    imagejpeg($image, $outputFile, $quality);
    imagedestroy($image);
}

So using your code as an example, you would then use this function to do the following: 因此,使用您的代码作为示例,您将使用此函数执行以下操作:

png2jpg('myDirectory/filename.png','myDirectory/filename.jpg', 100);

Or you can deconstruct the functions of that png2jpg function and use them in your code like this: 或者你可以解构那个png2jpg函数的函数,并在你的代码中使用它们,如下所示:

list($type, $data) = explode(';', $data);
list(, $data)      = explode(',', $data);
$data = base64_decode($data);
file_put_contents('myDirectory/filename.png', $data);
$image = imagecreatefrompng('myDirectory/filename.png');
imagejpeg($image, 'myDirectory/filename.jpg', 100);
imagedestroy($image);

The easiest way to to this since PHP 5.2.0, is using the data:// wrapper, you can use it like a file in many of functions. 自PHP 5.2.0以来最简单的方法是使用data:// wrapper,你可以像许多函数中的文件一样使用它。

$image = 'data:image/png;base64,iVBORw0KGgoAAAANSUhE...';
$image = imagecreatefrompng($image);
imagejpeg($image, 'myDirectory/filename.jpg', 100);
imagedestroy($image);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM