# core/image (vanilla-engine 0.4.0)

> https://vanillapunch.com/docs/vanilla-engine/0.4.0/api/core/image/

Image. (in place of the original HTMLImageElement / ImageAsset)
- Formats: the original accepts every format the browser decodes. Desktop accepts PNG, JPEG, WebP, GIF (first frame), BMP and ICO with the image crate, SVG with resvg,
  and AVIF, with the engine reading the HEIF boxes and rav1d decoding AV1. (core/avifimage.rs)
  On the web, as in the original, the browser (HTMLImageElement) always decodes images. It decodes them when assets are received (ImageAsset, AssetLoader) and on ImageAsset::load_from_bytes, and keeps them in the handle.
  (platform/web.rs, including AVIF and the first frame of animated PNG) This path on the web does not ship the image crate or the engine JPEG decoder.
  So on the web, load_from_memory and load_from_memory_with_mime_type do not decode bytes on the spot and return Err. (the original has no path that decodes image bytes on the spot either)
- Bytes with a known type (MIME) (data: URLs) are decoded with load_from_memory_with_mime_type. As in browsers, it is SVG only when the type is image/svg+xml, and anything else is identified by content.
  Bytes with an unknown type (files) are identified by content, SVG included, by load_from_memory. (desktop has no response type)
- sniff_image_mime_type: picks the type by content using the image table of WHATWG MIME sniffing (ICO, CUR, BMP, GIF, WebP, PNG, JPEG) plus AVIF. (desktop Material uses it instead of the response type)
- Color profiles: as in Chrome, the color space embedded in the image (PNG cICP, iCCP, gAMA and cHRM, JPEG APP2 ICC, WebP ICCP, AVIF colr) is converted to sRGB. (core/colorprofile.rs)
  In the original, the browser converts it at WebGL texImage2D. 3D materials (graphics3d/material.rs) are not converted, like the original's createImageBitmap (colorSpaceConversion "none").
- Pixels are held as premultiplied alpha RGBA. (the original does the same with UNPACK_PREMULTIPLY_ALPHA when uploading to a texture)
- Shared with Rc, and the GPU texture is created by Graphic's ImageTextureCache on first draw.
- After uploading to the GPU, the CPU pixels are released to return memory. (in the original, the browser holds the HTMLImageElement)
  Images whose pixels must be read again are kept with set_pixels_retained(true). (ShadowImage keeps them on its own when it receives an image, and reads back from the texture if already released)
  An image remembers its uploaded texture, so places without a Graphic, such as Canvas2D, also read released pixels back from the texture. (imagetexturecache::restore_image_pixels_from_texture)
  This engine has no path for restoring a lost GL context, so released pixels never need to be uploaded to a texture again.

## Image (struct)

Image. (premultiplied alpha RGBA pixels and size, shared as `Rc<Image>`)
- The GPU texture is uploaded by Graphic on first draw, and the CPU pixels are released after uploading. (kept if set_pixels_retained(true))

Example: Loading from a file

```rust
use std::path::Path;
use vanilla::Image;

let image = Image::load(Path::new("examples/assets/atlas/icons.png")).unwrap();
assert_eq!((image.get_width(), image.get_height()), (128, 128));
assert!(image.has_pixels());
assert_eq!(image.get_pixels().len(), 128 * 128 * 4);
```

Example: Pixels made in code are held with alpha multiplied in

```rust
use vanilla::Image;

let image = Image::create_from_pixels(2, 1, vec![255, 0, 0, 255, 255, 255, 255, 128]);
assert_eq!(&image.get_pixels()[0..4], &[255, 0, 0, 255]);
assert_eq!(&image.get_pixels()[4..8], &[128, 128, 128, 128]);
assert_ne!(image.get_instance_id(), Image::create_from_pixels(1, 1, vec![0, 0, 0, 0]).get_instance_id());
```

- `pub fn load(path: &Path) -> Result<Rc<Image>, String>` (static, since 0.3.2): Loads from a file. (the formats of load_from_memory, desktop records the read file in resource usage)
  - `path` &Path: Path of the image file to load.
  - returns Result<Rc<Image>, String>: The loaded and decoded image. Err holding the reason if the file cannot be read or decoded.
- `pub fn load_from_memory(bytes: &[u8]) -> Result<Rc<Image>, String>` (static, since 0.3.2): Loads from memory. (desktop, PNG, JPEG, WebP, first frame of GIF, BMP, ICO, SVG, AVIF)
  - On the web, as in the original, the browser decodes asynchronously. (ImageAsset::load, ImageAsset::load_from_bytes and AssetLoader decode and keep it in the handle) Calling this on the web returns Err.
  - `bytes` &[u8]: Bytes of the image file.
  - returns Result<Rc<Image>, String>: The decoded image. Err holding the reason if the format is unknown or it cannot be decoded.

  Example: Decoding from file bytes

  ```rust
  use vanilla::Image;
  
  let bytes = std::fs::read("examples/assets/atlas/icons.png").unwrap();
  let image = Image::load_from_memory(&bytes).unwrap();
  assert_eq!(image.get_width(), 128);
  assert!(Image::load_from_memory(b"not an image").is_err());
  ```

- `pub fn load_from_memory_with_mime_type(bytes: &[u8], mime_type: &str) -> Result<Rc<Image>, String>` (static, since 0.4.0): Loads bytes with a known type. (SVG if the type is image/svg+xml like the browser, otherwise a raster told by content. Images from data: URLs)
  - On the web, as in the original, the browser decodes asynchronously. (Err here, same as load_from_memory)
  - `bytes` &[u8]: Bytes of the image.
  - `mime_type` &str: Type of the image. (like "image/png", parameters after ; and case are ignored)
  - returns Result<Rc<Image>, String>: The decoded image. Err holding the reason if it cannot be decoded. (if the type is not image/svg+xml, the type is ignored and it is told by content)
- `pub fn create_from_premultiplied_pixels(width: u32, height: u32, pixels: Vec<u8>) -> Rc<Image>` (static, since 0.4.0): Creates from premultiplied RGBA pixels. (pixels with alpha already multiplied, like a rendered SVG)
  
  # Panics
  If the length of `pixels` is not `width * height * 4`. (same as the original `ImageData` throwing when the length is wrong)
  - `width` u32: Width. (pixels)
  - `height` u32: Height. (pixels)
  - `pixels` Vec<u8>: RGBA bytes with alpha multiplied. (row by row from left to right, `width * height * 4` of them)
  - returns Rc<Image>: New image. (new instance identifier)
- `pub fn create_from_pixels(width: u32, height: u32, straight_pixels: Vec<u8>) -> Rc<Image>` (static, since 0.3.2): Creates from straight alpha RGBA pixels. (images made in code)
  
  # Panics
  If the length of `straight_pixels` is not `width * height * 4`.
  - `width` u32: Width. (pixels)
  - `height` u32: Height. (pixels)
  - `straight_pixels` Vec<u8>: RGBA bytes without alpha multiplied. (row by row from left to right, `width * height * 4` of them, alpha is multiplied when taken in)
  - returns Rc<Image>: New image. (new instance identifier)
- `pub fn get_instance_id(&self) -> u64` (method, since 0.3.2): Instance identifier.
  - returns u64: Identifier received at creation. (different for every image, the key of the texture cache)
- `pub fn get_width(&self) -> u32` (method, since 0.3.2): Width. (pixels)
  - returns u32: Width. (pixels)
- `pub fn get_height(&self) -> u32` (method, since 0.3.2): Height. (pixels)
  - returns u32: Height. (pixels)
- `pub fn get_pixels(&self) -> Ref<'_, [u8]>` (method, since 0.3.2): Premultiplied RGBA pixels. (empty array if released after uploading to the GPU, check with has_pixels)
  - returns Ref<'_, [u8]>: Borrowed pixel bytes. (RGBA from the top row, empty array if released)
- `pub fn has_pixels(&self) -> bool` (method, since 0.4.0): Whether the CPU pixels are held. (false if released after uploading to the GPU)
  - returns bool: true if the pixel array is not empty.
- `pub fn set_pixels_retained(&self, is_pixels_retained: bool)` (method, since 0.4.0): Sets whether to keep the CPU pixels after uploading to the GPU. (default false. Images that read their pixels again turn it on)
  - `is_pixels_retained` bool: true keeps the CPU pixels after uploading to the GPU.
- `pub fn is_pixels_retained(&self) -> bool` (method, since 0.4.0): Whether the CPU pixels are kept after uploading to the GPU.
  - returns bool: true if set to keep. (initially false)

## Functions and constants

- `pub fn sniff_image_mime_type(bytes: &[u8]) -> Option<&'static str>` (method, since 0.4.0): Picks the image type by content. (the image table of WHATWG MIME sniffing 6.1 plus AVIF, None if unknown)
  - `bytes` &[u8]: Leading bytes of the image file.
  - returns Option<&'static str>: One of "image/x-icon", "image/bmp", "image/gif", "image/webp", "image/png", "image/jpeg", "image/avif". None if nothing matches. (SVG is not detected)

  Example: Picking the type from the file header

  ```rust
  use vanilla::core::image::sniff_image_mime_type;
  
  let png_bytes = std::fs::read("examples/assets/atlas/icons.png").unwrap();
  assert_eq!(sniff_image_mime_type(&png_bytes), Some("image/png"));
  assert_eq!(sniff_image_mime_type(b"GIF89a"), Some("image/gif"));
  assert_eq!(sniff_image_mime_type(b"plain text"), None);
  ```

