使用 PHP 将 base64 图像分解为像素数组
Break up a base64 image into an array of pixels using PHP
我有一些 PHP 可以将图像转换为 Base64:
$data = file_get_contents($path);
$image = base64_encode($data);
这给了我一个长的、随机的字符串。如何使用 PHP?
将此图像分解为单个像素阵列
像素在 base64 字符串中究竟是如何分隔的?不同的图像类型(JPG、PNG 等)是否有所不同?
简而言之,你不能。 base64_encode
肯定不行。
base64_encode
将 jpg 或 png 数据编码为 base64。
这意味着它使用 64 个不同的字符将位编码为字母,这与您想要实现的(几乎)无关,因为原始数据实际上是根据文件格式进行压缩的。
(如果你有兴趣了解更多关于base 64编码的知识,我建议this quite short video)
你要做的是逐一获取每个像素的颜色值。
因此,对于初学者,您应该使用 imagecolorat()
并遍历图像的宽度和高度。
因此您的代码将如下所示:
$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]);
这将 return 三种颜色加上 alpha 的数组
我有一些 PHP 可以将图像转换为 Base64:
$data = file_get_contents($path);
$image = base64_encode($data);
这给了我一个长的、随机的字符串。如何使用 PHP?
将此图像分解为单个像素阵列像素在 base64 字符串中究竟是如何分隔的?不同的图像类型(JPG、PNG 等)是否有所不同?
简而言之,你不能。 base64_encode
肯定不行。
base64_encode
将 jpg 或 png 数据编码为 base64。
这意味着它使用 64 个不同的字符将位编码为字母,这与您想要实现的(几乎)无关,因为原始数据实际上是根据文件格式进行压缩的。
(如果你有兴趣了解更多关于base 64编码的知识,我建议this quite short video)
你要做的是逐一获取每个像素的颜色值。
因此,对于初学者,您应该使用 imagecolorat()
并遍历图像的宽度和高度。
因此您的代码将如下所示:
$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]);
这将 return 三种颜色加上 alpha 的数组