php - 使用 PHP 将图像像素值存储在二维数组中,然后使用循环访问它们
问题描述
我有这段代码,我试图将图像像素值存储在二维数组中,然后尝试访问它们,以便我可以从存储在数组中的像素重新创建相同的图像,以下是我试图做的,但它只能访问一维数组,任何可以提供帮助的人都会非常感激
$resource = imagecreatefromjpeg("Broadway_tower_edit.jpg");
$width = 3;
$height = 3;
$arrayPixels = array();
//put pixels values in an array
for($x = 0; $x < $width; $x++) {
for($y = 0; $y < $height; $y++) {
// pixel color at (x, y)
$color = imagecolorat($resource, $x, $y);
$arrayPixels1 = array("$color");
//$myArray[$x][$y] = array('item' => "$color");
$arrayPixels[] = $arrayPixels1;
}
}
//access pixel values an try to create a image
$img = imagecreatetruecolor($width, $height);
for ($y = 0; $y < $height; ++$y) {
for ($x = 0; $x < $width; ++$x) {
imagesetpixel($img, $x, $y, $arrayPixels[$y][$x]);
}
}
// Dump the image to the browser
header('Content-Type: image/jpg');
imagejpeg($img);
// Clean up after ourselves
imagedestroy($img);
解决方案
正如您所说,您的数组只是行,您需要构建每一行,然后将其添加到行列表中
$arrayPixels = array();
//put pixels values in an array
for($x = 0; $x < $width; $x++) {
$row = array();
for($y = 0; $y < $height; $y++) {
// pixel color at (x, y)
$row[] = imagecolorat($resource, $x, $y);
}
$arrayPixels[] = $row;
}
或者在重新创建图像并使用 x 和 y 坐标时执行相同的操作...
//put pixels values in an array
for($x = 0; $x < $width; $x++) {
for($y = 0; $y < $height; $y++) {
// pixel color at (x, y)
$arrayPixels[$y][$x] = imagecolorat($resource, $x, $y);
}
}
推荐阅读
- python - 使用 Matplotlib 在 Python 中绘制数据框 - 水平条形图
- python - 在python中连接服务器和客户端时出现超时错误
- python - 以特定格式对字符串或整数数组进行排序
- django - 第一次通过for循环后,django模板中的上下文变量不可用
- c# - 可能导致此错误的原因:“csc.exe”以代码-2146232576 退出
- macos - 如何在容器内使用与在主机上访问相同的 url 访问服务
- xslt - 有没有办法制作整页表?
- vue.js - 添加拖放到 vuetify 的选择
- linux - Oracle Developer Studio 12.6 Fortran 编译器:ieee_arithmetic_semantics:断言“0”失败
- css - 框框内的标题 - CSS,前端开发 - UX