首页 > 解决方案 > PHP - JPEG 图像到 RGB 值数组计数

问题描述

我想从图像中获取一个 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

非常感谢任何帮助!

标签: phphtmljpegrgb

解决方案


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

添加:

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

后:

$b = $rgb & 0xFF;

推荐阅读