Novis\Image\Image::raw
$image->raw(): RawRuns every step of the image and returns its pixels.
raw returns a shape (a value with named fields) with three fields. width and height are the size in pixels. pixels contains the image row by row, from the top-left corner. Each pixel is four bytes: red, green, blue and alpha, each from 0 to 255. So pixels has width times height times 4 bytes.
To read one pixel, take its four bytes with Core\Bytes::slice and read them with Core\Bytes::unpack and the format "C4". The pixel at column x and row y starts at byte (y * width + x) * 4.
pixels is tainted bytes, like the result of encode.
raw throws the same errors as encode. Image::fromRaw starts a new image from the shape that raw returns.
Good to know: raw copies the whole image into your program at once. For work on the whole image, such as a resize or a blur, the step methods are much faster than a loop over the pixels.
Return value
Returns Raw.
Changelog
| Version | Change |
|---|---|
0.0.6 | Image::encode, the pixels of Image::raw, each file of Image::encodeVariants and the result of Pages::merge are tainted bytes. An image or a PDF file may be an upload. Font::fromBytes takes tainted bytes. |
Examples
Read one pixel
<?nvsuse Novis\Image\Color;// Shows how to read the colour of one pixel.use Novis\Image\Image;
var $image = Image::create(10, 10, Color::hex('#ff8800'))->raw();
// The pixel at column 3 and row 2 starts at byte (2 * 10 + 3) * 4, which is 92.int $start = (2 * 10 + 3) * 4;array<mixed> $pixel = Core\Bytes::unpack(Core\Bytes::slice($image->pixels, $start, 4), 'C4');
// This prints 255 136 0 255.echo $pixel[0], ' ', $pixel[1], ' ', $pixel[2], ' ', $pixel[3], "\n";255 136 0 255Size of the pixels
<?nvsuse Novis\Image\Color;// Shows that the pixels have four bytes for each pixel of the image.use Novis\Image\Image;
// `raw` runs the resize first. The result is 30 by 20 pixels.var $image = Image::create(300, 200, Color::hex('#336699'))->resized({ width: 30 })->raw();echo $image->width, 'x', $image->height, "\n";
// 30 times 20 times 4 is 2400. This prints 2400.echo Core\Bytes::length($image->pixels), "\n";30x202400Check a step
<?nvsuse Novis\Image\Color;// Shows how to check the result of a step in a test, by reading a pixel.use Novis\Image\Image;
// After `grayscaled`, red, green and blue of every pixel are the same number.var $gray = Image::create(4, 4, Color::hex('#336699'))->grayscaled()->raw();array<mixed> $pixel = Core\Bytes::unpack(Core\Bytes::slice($gray->pixels, 0, 4), 'C4');
// This prints true.echo $pixel[0] == $pixel[1] && $pixel[1] == $pixel[2] ? 'true' : 'false', "\n";true