Skip to content

Novis\Image\Image::create

Starts an image from a blank canvas of one colour.

$width and $height are the size of the canvas in pixels. $fill is its colour, made with Color::hex or Color::rgba. Without $fill, every pixel is transparent.

The canvas is made when encode, encodeVariants or raw runs. A canvas of width or height 0 throws an error there. So does a canvas with more pixels than the server's limit.

A canvas did not come from a file, so it has no format of its own. Without withFormat, encode writes it as PNG.

Good to know: a canvas is useful as a placeholder, as a background, and in tests that need an image without a file.

Parameters

  • $widthuint
  • $heightuint
  • $fill?Colordefault null

Return value

Returns Image.

Examples

Coloured canvas

<?nvs
use Novis\Image\Color;
// Shows how to make a canvas of one colour and read its first pixel.
use Novis\Image\Image;
var $canvas = Image::create(800, 600, Color::hex('#336699'))->raw();
// This prints 800x600.
echo $canvas->width, 'x', $canvas->height, "\n";
// `#336699` is red 51, green 102 and blue 153. The alpha 255 means not transparent.
array<mixed> $pixel = Core\Bytes::unpack(Core\Bytes::slice($canvas->pixels, 0, 4), 'C4');
echo $pixel[0], ' ', $pixel[1], ' ', $pixel[2], ' ', $pixel[3], "\n";
Output
800x600
51 102 153 255

Transparent canvas

<?nvs
// Shows that a canvas without a fill colour is transparent.
use Novis\Image\Image;
var $canvas = Image::create(16, 16)->raw();
// Every byte of the first pixel is 0, so its alpha is 0. This prints 0 0 0 0.
array<mixed> $pixel = Core\Bytes::unpack(Core\Bytes::slice($canvas->pixels, 0, 4), 'C4');
echo $pixel[0], ' ', $pixel[1], ' ', $pixel[2], ' ', $pixel[3], "\n";
Output
0 0 0 0

Placeholder file

<?nvs
use Novis\Image\Color;
use Novis\Image\Format;
// Shows how to make a small grey PNG file, for a product that has no photo yet.
use Novis\Image\Image;
// A canvas has no format of its own, so `withFormat` chooses PNG.
tainted bytes $file = Image::create(120, 80, Color::hex('#cccccc'))->withFormat(Format::Png)->encode();
// This prints image/png 120x80.
var $info = Image::info($file);
echo Image::mime($info->format), ' ', $info->width, 'x', $info->height, "\n";
Output
image/png 120x80