首页 > 解决方案 > 使用 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);

标签: phploopsmultidimensional-arraygd

解决方案


正如您所说,您的数组只是行,您需要构建每一行,然后将其添加到行列表中

$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);

    }
}    

推荐阅读