From 3e6c6142eb04ff2f9fb5fd24d8be49770c6646a3 Mon Sep 17 00:00:00 2001 From: mlarouche Date: Sat, 8 Jun 2024 18:31:56 -0400 Subject: [PATCH] Add convertNoFree() to add a convenience convert() that does not free the old pixel data --- src/ImageUnmanaged.zig | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/src/ImageUnmanaged.zig b/src/ImageUnmanaged.zig index 4c0cc58..d65a49a 100644 --- a/src/ImageUnmanaged.zig +++ b/src/ImageUnmanaged.zig @@ -231,6 +231,7 @@ pub fn writeToMemory(self: ImageUnmanaged, allocator: std.mem.Allocator, write_b /// Convert the pixel format of the Image into another format. /// It will allocate another pixel storage for the destination and free the old one +/// /// For the conversion to the indexed formats, no dithering is done. pub fn convert(self: *ImageUnmanaged, allocator: std.mem.Allocator, destination_format: PixelFormat) ConvertError!void { // Do nothing if the format is the same @@ -246,6 +247,23 @@ pub fn convert(self: *ImageUnmanaged, allocator: std.mem.Allocator, destination_ self.pixels = new_pixels; } +/// Convert the pixel format of the Image into another format. +/// It will allocate another pixel storage for the destination and not free the old one. +/// Ths is in the case the image doess not own the pixel data. +/// +/// For the conversion to the indexed formats, no dithering is done. +pub fn convertNoFree(self: *ImageUnmanaged, allocator: std.mem.Allocator, destination_format: PixelFormat) ConvertError!void { + // Do nothing if the format is the same + if (std.meta.activeTag(self.pixels) == destination_format) { + return; + } + + const new_pixels = try PixelFormatConverter.convert(allocator, &self.pixels, destination_format); + errdefer new_pixels.deinit(allocator); + + self.pixels = new_pixels; +} + /// Iterate the pixel in pixel-format agnostic way. In the case of an animation, it returns an iterator for the first frame. The iterator is read-only. pub fn iterator(self: *const ImageUnmanaged) color.PixelStorageIterator { return color.PixelStorageIterator.init(&self.pixels);