PHP-JPEG图像到RGB值数组计数

问题描述 投票:1回答:1

我想从图像中获取一个RGB值数组,并对数组中的数据进行计数。例如。 (2 X 2像素示例。)

[[[R, G, B], [R, G, B]], [[R, G, B], [R, G, B]]]
Data = 12
SUM = total from all of the RGB values

我现在拥有的代码:

    <?php
    // open an image
    $image = imagecreatefromjpeg('image.jpg'); // imagecreatefromjpeg/png/
    // get image dimension, define colour array
    $width = imagesx($image);
    $height = imagesy($image);
    $colors = [];
    for ($y = 0; $y < $height; $y++)
    {
        for ($x = 0; $x < $width; $x++)
        {
            $rgb = imagecolorat($image, $x, $y);
            $r = ($rgb >> 16) & 0xFF;
            $g = ($rgb >> 8) & 0xFF;
            $b = $rgb & 0xFF;
            $y_array=array($r,$g,$b);
            $x_array[]=$y_array;
        }
        $colors=$x_array;
    }
    print_r($colors);
    print_r(sizeof($colors));
    print_r(array_sum($colors));
    ?>

我得到的输出:

[[[0, 255, 0], [255, 0, 0]], [[0, 0, 255], [255, 255, 255]]]
    Data = 2
    SUM = 0

以上无效。我的图像现在只是2 X 2 pix jpeg,应该输出:

[[[0, 255, 0], [255, 0, 0]], [[0, 0, 255], [255, 255, 255]]]
Data = 12
SUM = 0+255+0+255+0+0+0+0+255+255+255+255 = 2295

任何帮助,不胜感激!

php html jpeg rgb
1个回答
1
投票

这里的主要问题似乎是您没有存储值的事实。

添加:

$colors[] = [ $r, $g, $b ];

之后:

$b = $rgb & 0xFF;
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.