使用 imagecreatefromstring 函数处理带有 data:image/png;base64 前缀的图像数据。

8
我有一个以字符串形式存储的图像,它以以下内容开头:

data:image/png;base64,

我需要将它转换为普通图像以便在GD中使用。

我尝试使用imagecreatefromstring(),但似乎只接受没有data:image/etc前缀的图片。

我该怎么做?


1
所有与base64数据本身无关的内容都需要被翻译,但不包括base64数据本身。 - Marc B
$image = explode('base64,', $data); $src = base64_decode($image[1]); 这样去掉它们可以吗?我需要处理未知的图像类型。 - Fez Vrasta
那么如果我不知道图像格式是jpeg、png、tiff、gif等等,我该如何剥离这些信息呢?可以在第一次出现时使用正则表达式吗? - Fez Vrasta
data uri 有一个相当标准的格式。data:type;base64,xxx。只需查找第一个逗号即可。 - Marc B
1
在base64图像中,逗号允许吗?如果不行,使用带逗号的 *base64,*爆炸应该没问题... - Fez Vrasta
显示剩余3条评论
1个回答

14
$exploded = explode(',', $data, 2); // limit to 2 parts, i.e: find the first comma
$encoded = $exploded[1]; // pick up the 2nd part
$decoded = base64_decode($encoded);
$img_handler = imagecreatefromstring($decoded);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接