core/image
이미지. (원본 HTMLImageElement / ImageAsset 자리)
- 형식: 원본은 브라우저가 푸는 형식을 모두 받는다. 데스크탑은 image 크레이트로 PNG, JPEG, WebP, GIF(첫 장), BMP, ICO, resvg 로 SVG, HEIF 상자는 엔진이 읽고 AV1 은 rav1d 로 풀어 AVIF 를 받는다. (core/avifimage.rs) 웹은 원본처럼 그림을 늘 브라우저(HTMLImageElement)가 푼다. 애셋을 받을 때(ImageAsset, AssetLoader)와 ImageAsset::load_from_bytes 때 풀어 손잡이에 둔다. (platform/web.rs, AVIF 와 애니메이션 PNG 의 첫 장 포함) 웹의 이 길에는 image 크레이트와 엔진 JPEG 해독기를 싣지 않는다. 그래서 웹의 load_from_memory 와 load_from_memory_with_mime_type 은 바이트를 그 자리에서 풀지 않고 Err 를 돌려준다. (원본에도 그림 바이트를 그 자리에서 푸는 길이 없다)
- 형(MIME)을 아는 바이트(data: 주소)는 load_from_memory_with_mime_type 으로 푼다. 브라우저처럼 형이 image/svg+xml 일 때만 SVG 이고, 그 밖은 내용으로 가린다. 형을 모르는 바이트(파일)는 load_from_memory 가 내용으로 SVG 까지 가린다. (데스크탑에는 응답의 형이 없다)
- sniff_image_mime_type: WHATWG MIME 스니핑의 그림 표(ICO, CUR, BMP, GIF, WebP, PNG, JPEG)에 AVIF 를 더해 내용으로 형을 고른다. (데스크탑 Material 이 응답의 형 대신 쓴다)
- 색 프로필: 크롬처럼 그림에 박힌 색 공간(PNG 의 cICP, iCCP, gAMA 와 cHRM, JPEG 의 APP2 ICC, WebP 의 ICCP, AVIF 의 colr)을 sRGB 로 바꾼다. (core/colorprofile.rs) 원본은 WebGL texImage2D 때 브라우저가 바꾼다. 3D 재질(graphics3d/material.rs)은 원본의 createImageBitmap(colorSpaceConversion "none")처럼 바꾸지 않는다.
- 픽셀은 프리멀티플라이드 알파 RGBA 로 들고 있다. (원본은 텍스처에 올릴 때 UNPACK_PREMULTIPLY_ALPHA 로 같은 일을 한다)
- Rc 로 나눠 쓰고, GPU 텍스처는 Graphic 의 ImageTextureCache 가 처음 그릴 때 만든다.
- GPU 에 올린 뒤에는 CPU 픽셀을 놓아 메모리를 돌려준다. (원본은 브라우저가 HTMLImageElement 를 들고 있다) 픽셀을 다시 읽어야 하는 그림은 set_pixels_retained(true) 로 남긴다. (ShadowImage 는 그림을 받을 때 스스로 남기고, 이미 놓였으면 텍스처에서 되읽는다) 그림은 올린 텍스처를 기억해, Canvas2D 처럼 Graphic 이 없는 곳도 놓인 픽셀을 텍스처에서 되읽는다. (imagetexturecache::restore_image_pixels_from_texture) 이 엔진은 GL 컨텍스트를 잃었다 되살리는 길이 없어서 놓은 픽셀로 텍스처를 다시 올릴 일은 없다.
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.
Imagestruct
이미지. (프리멀티플라이드 알파 RGBA 픽셀과 크기, Rc<Image> 로 나눠 쓴다)
- GPU 텍스처는 Graphic 이 처음 그릴 때 올리고, 올린 뒤에는 CPU 픽셀을 놓는다. (set_pixels_retained(true) 면 남긴다)
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))
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);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());파일에서 읽기. (load_from_memory 의 형식, 데스크탑은 읽은 파일을 리소스 사용량에 적는다)
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.
반환ReturnsResult<Rc<Image>, String> 읽어 푼 그림. 파일을 읽지 못하거나 풀지 못하면 그 까닭을 담은 Err.The loaded and decoded image. Err holding the reason if the file cannot be read or decoded.
메모리에서 읽기. (데스크탑, PNG, JPEG, WebP, GIF 의 첫 장, BMP, ICO, SVG, AVIF)
- 웹은 원본처럼 브라우저가 비동기로 푼다. (ImageAsset::load, ImageAsset::load_from_bytes, AssetLoader 가 풀어 손잡이에 둔다) 웹에서 여기를 부르면 Err 다.
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.
반환ReturnsResult<Rc<Image>, String> 푼 그림. 형식을 모르거나 풀지 못하면 그 까닭을 담은 Err.The decoded image. Err holding the reason if the format is unknown or it cannot be decoded.
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>#형을 아는 바이트 읽기. (브라우저처럼 형이 image/svg+xml 이면 SVG, 그 밖은 내용으로 가린 래스터. data: 주소의 그림)
- 웹은 원본처럼 브라우저가 비동기로 푼다. (여기서는 Err, load_from_memory 와 같다)
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
- 그림의 형. ("image/png" 처럼, ; 뒤의 매개 변수와 대소문자는 보지 않는다)Type of the image. (like "image/png", parameters after ; and case are ignored)
반환ReturnsResult<Rc<Image>, String> 푼 그림. 풀지 못하면 그 까닭을 담은 Err. (형이 image/svg+xml 이 아니면 형을 보지 않고 내용으로 가린다)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>#프리멀티플라이드 RGBA 픽셀로 생성. (SVG 를 그린 판처럼 이미 알파를 곱한 픽셀) # 패닉 pixels 길이가 width * height * 4 가 아니면. (원본 ImageData 가 길이가 틀리면 예외를 던지는 것과 같다)
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)
- widthu32
- 폭. (픽셀)Width. (pixels)
- heightu32
- 높이. (픽셀)Height. (pixels)
- pixelsVec<u8>
- 알파를 곱한 RGBA 바이트. (줄마다 왼쪽에서 오른쪽으로,
width * height * 4개)RGBA bytes with alpha multiplied. (row by row from left to right,width * height * 4of them)
반환ReturnsRc<Image> 새 그림. (새 인스턴스 식별자)New image. (new instance identifier)
스트레이트 알파 RGBA 픽셀로 생성. (코드로 만든 그림) # 패닉 straight_pixels 길이가 width * height * 4 가 아니면.
Creates from straight alpha RGBA pixels. (images made in code) # Panics If the length of straight_pixels is not width * height * 4.
- widthu32
- 폭. (픽셀)Width. (pixels)
- heightu32
- 높이. (픽셀)Height. (pixels)
- straight_pixelsVec<u8>
- 알파를 곱하지 않은 RGBA 바이트. (줄마다 왼쪽에서 오른쪽으로,
width * height * 4개, 들일 때 알파를 곱한다)RGBA bytes without alpha multiplied. (row by row from left to right,width * height * 4of them, alpha is multiplied when taken in)
반환ReturnsRc<Image> 새 그림. (새 인스턴스 식별자)New image. (new instance identifier)
인스턴스 식별자.
Instance identifier.
반환Returnsu64 만들 때 받은 식별자. (그림마다 다르다, 텍스처 캐시의 열쇠)Identifier received at creation. (different for every image, the key of the texture cache)
너비. (픽셀)
Width. (pixels)
반환Returnsu32 너비. (픽셀)Width. (pixels)
높이. (픽셀)
Height. (pixels)
반환Returnsu32 높이. (픽셀)Height. (pixels)
프리멀티플라이드 RGBA 픽셀. (GPU 에 올린 뒤 놓았으면 빈 배열, has_pixels 로 가린다)
Premultiplied RGBA pixels. (empty array if released after uploading to the GPU, check with has_pixels)
반환ReturnsRef<'_, [u8]> 픽셀 바이트를 빌린 것. (위 줄부터 RGBA, 놓았으면 빈 배열)Borrowed pixel bytes. (RGBA from the top row, empty array if released)
CPU 픽셀을 들고 있는지. (GPU 에 올린 뒤 놓았으면 false)
Whether the CPU pixels are held. (false if released after uploading to the GPU)
반환Returnsbool 픽셀 배열이 비지 않았으면 true.true if the pixel array is not empty.
GPU 에 올린 뒤에도 CPU 픽셀을 남길지 설정. (기본 false. 픽셀을 다시 읽는 그림이 켠다)
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_retainedbool
- true 면 GPU 에 올린 뒤에도 CPU 픽셀을 남긴다.true keeps the CPU pixels after uploading to the GPU.
GPU 에 올린 뒤에도 CPU 픽셀을 남기는지.
Whether the CPU pixels are kept after uploading to the GPU.
반환Returnsbool 남기게 했으면 true. (처음 false)true if set to keep. (initially false)
함수Functions
내용으로 그림 형 고르기. (WHATWG MIME 스니핑 6.1 의 그림 표에 AVIF 를 더한 것, 모르면 None)
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.
반환ReturnsOption<&'static str> "image/x-icon", "image/bmp", "image/gif", "image/webp", "image/png", "image/jpeg", "image/avif" 가운데 하나. 맞는 것이 없으면 None. (SVG 는 가리지 않는다)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)
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);