Skip to content

Novis\Image\Image::fromRaw

Starts an image from pixels in memory, in the same shape that raw returns.

The argument has a width, a height and 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. This is called RGBA8.

The length of pixels must be exactly width times height times 4. Otherwise encode, encodeVariants or raw throws an error. An image with more pixels than the server's limit also throws an error.

Good to know: together with raw, this lets you change single pixels in Novis code and then encode the result. For changes to the whole image, the step methods such as resized are faster.

Parameters

  • $rawRaw

Return value

Returns Image.

Examples

Pixels you build

<?nvs
// Shows how to make an image from bytes that you write yourself.
use Novis\Image\Image;
// Two pixels in one row: red on the left, blue on the right. Each pixel is four bytes.
bytes $pixels = Core\Encoding::fromHex('ff0000ff' . '0000ffff');
Image $image = Image::fromRaw({ width: 2, height: 1, pixels: $pixels });
// After a horizontal flip, blue is on the left. This prints 0000ffffff0000ff.
echo Core\Encoding::toHex($image->flipped(Image::Axis::Horizontal)->raw()->pixels), "\n";
Output
0000ffffff0000ff

Pixels back to a file

<?nvs
use Novis\Image\Color;
use Novis\Image\Format;
// Shows how to decode an image, keep its pixels, and later encode them as a new file.
use Novis\Image\Image;
// `raw` decodes a 64 by 48 image into pixels.
var $pixels = Image::create(64, 48, Color::hex('#336699'))->raw();
// `fromRaw` starts a new image from those pixels. `withFormat` and `encode` write a WebP file.
tainted bytes $file = Image::fromRaw($pixels)->withFormat(Format::Webp)->encode();
// This prints image/webp 64x48.
var $info = Image::info($file);
echo Image::mime($info->format), ' ', $info->width, 'x', $info->height, "\n";
Output
image/webp 64x48

Wrong number of bytes

<?nvs
// Shows the error when the pixels do not match the width and the height.
use Novis\Image\Image;
// A 4 by 4 image needs 4 times 4 times 4, which is 64 bytes. These are only 3 bytes.
Image $image = Image::fromRaw({ width: 4, height: 4, pixels: 'abc' as bytes });
// `raw` throws an error that names both lengths.
try {
$image->raw();
} catch (Throwable $e) {
echo $e->message, "\n";
}
Output
3 bytes are not the RGBA8 rows of an image of 4x4, which are 64 bytes