php - 使用 PHP 将 base64 图像分解为像素数组
问题描述
我有一些 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 编码的更多信息,我建议您观看这个非常短的视频)
你要做的是一个一个地获取每个像素的颜色值。因此,对于初学者,您应该使用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 的数组
推荐阅读
- javascript - 全日历 | 在列表视图中更改 fc-event-dot 的颜色
- node.js - 如何正确地对 Joi Schemas 验证进行单元测试?
- python - 索引后用递增值填充列行
- swift - CollectionView 上的 reloadData,Swift
- spring - Hibernate / Jpa 异常无法重新关联未初始化的瞬态集合
- javascript - javascript中的工厂模式模块和类问题给了我ReferenceError
- java - Spring Cloud Dataflow 文件启动器修改
- python - 组合两个具有不同分组要求的正则表达式
- node.js - 获取 throw new ERR_INVALID_ARG_TYPE(name, 'string', value);
- flutter - pub.dev - 包 - 版权 - Flutter / Dart