1

我想从图像中获取一组 RGB 值。例如(2 X 2 像素示例。)

[[[R, G, B], [R, G, B]], [[R, G, B], [R, G, B]]]

我现在拥有的代码:

<?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;
    } 
}
print_r($colors);
?>

以上不起作用。我的图像现在只是一个 2 X 2 pix jpeg,应该输出:

    [[[0, 255, 0], [255, 0, 0]], [[0, 0, 255], [255, 255, 255]]]

非常感谢任何帮助!

4

4 回答 4

2

好的,搞定了。谢谢大家。

<?php
$image = imagecreatefromjpeg('image.jpg'); // imagecreatefromjpeg/png/

$width = imagesx($image);
$height = imagesy($image);
$colors = array();

for ($y = 0; $y < $height; $y++) {
$y_array = array() ;

for ($x = 0; $x < $width; $x++) {
    $rgb = imagecolorat($image, $x, $y);
    $r = ($rgb >> 16) & 0xFF;
    $g = ($rgb >> 8) & 0xFF;
    $b = $rgb & 0xFF;

    $x_array = array($r, $g, $b) ;
    $y_array[] = $x_array ; 
} 
$colors[] = $y_array ;
}

print_r($colors);
?>

注释正确,添加了 $r、$g、$b。重组@jari 答案,现在得到了很好的输出。

干杯!

于 2013-10-18T08:41:31.423 回答
1
function getArrayOfPixelsFromFile($source) {
 $image = imagecreatefromjpeg($source); // imagecreatefromjpeg/png/

 $width = imagesx($image);
 $height = imagesy($image);
 $colors = array();

 for ($y = 0; $y < $height; $y++) {
    $y_array = array();
    for ($x = 0; $x < $width; $x++) {
        //Seleciona a cor localizada em ($x, $y)
        $rgb = imagecolorat($image, $x, $y);
        //echo $rgb." = ".decbin($rgb),"<br>";
        //Seleciona os primeiros dois bytes que representam vermelho
        $r = ($rgb >> 16) & 0xFF;
        //Seleciona os dois bytes do meio que representam o verde
        $g = ($rgb >> 8) & 0xFF;
        //Seleciona os dois últimos bytes que representam o azul
        $b = $rgb & 0xFF;
        $x_array = array($r, $g, $b);
        $y_array[] = $x_array;
    }
    $colors[] = $y_array;
  }
  return $colors;
}
于 2015-06-03T00:27:21.163 回答
0

这个怎么样?

[...]
$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;
        $colors[$y][$x] = array($r,$g,$b);  // or, $colors[$x][$y] = array($r,$g,$b);
    } 
}
print_r($colors);
于 2013-10-17T15:04:47.503 回答
0

我通过创建子数组并向其添加应有的元素来修复您的代码。

for ($y = 0; $y < $height; $y++)
{
    $height_arr = array() ;

    for ($x = 0; $x < $width; $x++)
    {
        $rgb = imagecolorat($image, $x, $y);
        $r = ($rgb >> 16) & 0xFF;
        $g = ($rgb >> 8) & 0xFF;
        $b = $rgb & 0xFF;

        $width_arr = array($r, $g, $b) ;
        $height_array[] = $width_arr ; 
    } 

    $colors[] = $height_arr ;
}
于 2013-10-17T15:00:43.500 回答