首页 > 解决方案 > 使用 PHP 将 base64 图像分解为像素数组

问题描述

我有一些 PHP 可以将图像转换为 Base64:

$data = file_get_contents($path);
$image = base64_encode($data);

这给了我一个长而随机的字符串。如何使用 PHP 将此图像分解为单个像素的数组?

base64 字符串中的像素究竟是如何分隔的?不同的图像类型(JPG、PNG 等)是否不同?

标签: phpbase64

解决方案


对于一个简短的答案,你不能。不是base64_encode肯定的。

base64_encode将 jpg 或 png 数据编码为 base64。这意味着它使用 64 个不同的字符将位编码为字母,这(几乎)与您想要实现的目标无关,因为原始数据实际上是根据文件格式压缩的。(如果您有兴趣了解有关 base 64 编码的更多信息,我建议您观看这个非常短的视频

你要做的是一个一个地获取每个像素的颜色值。因此,对于初学者,您应该使用imagecolorat() and 循环遍历图像的宽度和高度。

所以你的代码看起来像这样:

$imagename="image.png";

$imgsize = getimagesize($imagename); //this return an array of info
$imgwidth = $imgsize[0]; //index 0 is the width
$imgheight = $imgsize[1]; //index 1 is the height

$im = imagecreatefrompng($imagename); 
//note that this is a function for png images
//use imagecreatefromjpeg() for jpg

$pixels = [];

for ($x = 1; $x <= $imgwidth; $x++) {
    for ($y = 1; $y <= $imgheight; $y++) {
        $pixels[$x][$y] = imagecolorat($im, $x, $y);
    }
}

这会将所有像素 rgb 存储到$pixels数组中。

要获得人类可读的版本,您应该imagecolorsforindex像这样使用:

$color = imagecolorsforindex($im, $pixel[1][5]);

这将返回三个颜色加上 alpha 的数组


推荐阅读