如何在PHP中获取图像的像素值?

Mad*_*ngh 13 php

我需要使用PHP来读取图像中的每个像素.这是图形密码项目.当用户选择密码时,他们将选择图像上的某个区域.而我正试图通过像素值来做到这一点.可能吗??

Aus*_*rst 24

是的,您可以使用颜色获取像素"值" imagecolorat().

$color = imagecolorat($resource, $x, $y);
Run Code Online (Sandbox Code Playgroud)

哪里$resource是你的图像资源,并且$x,$y你想要得到的颜色的像素的坐标.

您可以像这样迭代所有像素.请注意,这可能是一项昂贵的任务,具体取决于图像的大小.

$width = imagesx($resource);
$height = imagesy($resource);

for($x = 0; $x < $width; $x++) {
    for($y = 0; $y < $height; $y++) {
        // pixel color at (x, y)
        $color = imagecolorat($resource, $x, $y);
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 请注意,这可能会返回1)该像素处的颜色索引2)该像素处的实际颜色.如果您使用imagecolorsforindex(),您可以确保获得RGB值. (6认同)