From 1a16585b10044255097e0abaa73aa4f0a422cbd1 Mon Sep 17 00:00:00 2001 From: Jeroen van Rijn Date: Fri, 2 Aug 2024 14:54:52 +0200 Subject: [PATCH] Add image.pixels_to_image helper. --- core/image/common.odin | 29 ++++++++++++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/core/image/common.odin b/core/image/common.odin index 2b1f717115e..94321f64478 100644 --- a/core/image/common.odin +++ b/core/image/common.odin @@ -112,7 +112,8 @@ Image_Option: `.alpha_drop_if_present` If the image has an alpha channel, drop it. - You may want to use `.alpha_premultiply` in this case. + You may want to use `.alpha_ + tiply` in this case. NOTE: For PNG, this also skips handling of the tRNS chunk, if present, unless you select `alpha_premultiply`. @@ -587,6 +588,32 @@ Channel :: enum u8 { A = 4, } +// Take a slice of pixels (`[]RGBA_Pixel`, etc), and return an `Image` +// Don't call `destroy` on the resulting `Image`. Instead, delete the original `pixels` slice. +pixels_to_image :: proc(pixels: [][$N]$E, width: int, height: int) -> (img: Image, ok: bool) where E == u8 || E == u16, N >= 1 && N <= 4 { + if len(pixels) != width * height { + return {}, false + } + + img.height = height + img.width = width + img.depth = 8 when E == u8 else 16 + img.channels = N + + s := transmute(runtime.Raw_Slice)pixels + d := runtime.Raw_Dynamic_Array{ + data = s.data, + len = s.len * size_of(E) * N, + cap = s.len * size_of(E) * N, + allocator = runtime.nil_allocator(), + } + img.pixels = bytes.Buffer{ + buf = transmute([dynamic]u8)d, + } + + return img, true +} + // When you have an RGB(A) image, but want a particular channel. return_single_channel :: proc(img: ^Image, channel: Channel) -> (res: ^Image, ok: bool) { // Were we actually given a valid image?