【问题标题】:Storing Image pixel values in a 2D array using PHP and then access them using a loop使用 PHP 将图像像素值存储在二维数组中,然后使用循环访问它们
【发布时间】:2018-11-01 19:35:37
【问题描述】:

我有这段代码,我试图将图像像素值存储在 2D 数组中,然后尝试访问它们,以便我可以从存储在数组中的像素重新创建相同的图像,以下是我试图做的但是它只访问一维数组,任何可以帮助的人都会非常感激它

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

【问题讨论】:

    标签: php loops multidimensional-array gd


    【解决方案1】:

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

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

    【讨论】:

    • 非常感谢@Nigel Ren,现在我可以访问 2D 中的索引值,但另一个问题是它创建了一个黑色图像,而不是我从中提取索引值的同一图像,您或任何人都可以帮忙吗我也这样??
    • 有几件事要检查,尝试使用原始图像 ($resource) 显示图像,看看它是否正确显示。使用第二个版本(使用 $x 和 $y),比较第一个图像和第二个图像中的像素,看看它们是否被正确复制。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-24
    • 2012-11-06
    • 2021-01-04
    • 2016-07-13
    • 1970-01-01
    • 1970-01-01
    • 2013-02-09
    相关资源
    最近更新 更多