bevy_image/
image_texture_conversion.rs

1use crate::{Image, TextureFormatPixelInfo};
2use bevy_asset::RenderAssetUsages;
3use image::{DynamicImage, ImageBuffer};
4use thiserror::Error;
5use wgpu_types::{Extent3d, TextureDimension, TextureFormat};
6
7impl Image {
8    /// Converts a [`DynamicImage`] to an [`Image`].
9    pub fn from_dynamic(
10        dyn_img: DynamicImage,
11        is_srgb: bool,
12        asset_usage: RenderAssetUsages,
13    ) -> Image {
14        use bytemuck::cast_slice;
15        let width;
16        let height;
17
18        let data: Vec<u8>;
19        let format: TextureFormat;
20
21        match dyn_img {
22            DynamicImage::ImageLuma8(image) => {
23                let i = DynamicImage::ImageLuma8(image).into_rgba8();
24                width = i.width();
25                height = i.height();
26                format = if is_srgb {
27                    TextureFormat::Rgba8UnormSrgb
28                } else {
29                    TextureFormat::Rgba8Unorm
30                };
31
32                data = i.into_raw();
33            }
34            DynamicImage::ImageLumaA8(image) => {
35                let i = DynamicImage::ImageLumaA8(image).into_rgba8();
36                width = i.width();
37                height = i.height();
38                format = if is_srgb {
39                    TextureFormat::Rgba8UnormSrgb
40                } else {
41                    TextureFormat::Rgba8Unorm
42                };
43
44                data = i.into_raw();
45            }
46            DynamicImage::ImageRgb8(image) => {
47                let i = DynamicImage::ImageRgb8(image).into_rgba8();
48                width = i.width();
49                height = i.height();
50                format = if is_srgb {
51                    TextureFormat::Rgba8UnormSrgb
52                } else {
53                    TextureFormat::Rgba8Unorm
54                };
55
56                data = i.into_raw();
57            }
58            DynamicImage::ImageRgba8(image) => {
59                width = image.width();
60                height = image.height();
61                format = if is_srgb {
62                    TextureFormat::Rgba8UnormSrgb
63                } else {
64                    TextureFormat::Rgba8Unorm
65                };
66
67                data = image.into_raw();
68            }
69            DynamicImage::ImageLuma16(image) => {
70                width = image.width();
71                height = image.height();
72                format = TextureFormat::R16Uint;
73
74                let raw_data = image.into_raw();
75
76                data = cast_slice(&raw_data).to_owned();
77            }
78            DynamicImage::ImageLumaA16(image) => {
79                width = image.width();
80                height = image.height();
81                format = TextureFormat::Rg16Uint;
82
83                let raw_data = image.into_raw();
84
85                data = cast_slice(&raw_data).to_owned();
86            }
87            DynamicImage::ImageRgb16(image) => {
88                let i = DynamicImage::ImageRgb16(image).into_rgba16();
89                width = i.width();
90                height = i.height();
91                format = TextureFormat::Rgba16Unorm;
92
93                let raw_data = i.into_raw();
94
95                data = cast_slice(&raw_data).to_owned();
96            }
97            DynamicImage::ImageRgba16(image) => {
98                width = image.width();
99                height = image.height();
100                format = TextureFormat::Rgba16Unorm;
101
102                let raw_data = image.into_raw();
103
104                data = cast_slice(&raw_data).to_owned();
105            }
106            DynamicImage::ImageRgb32F(image) => {
107                width = image.width();
108                height = image.height();
109                format = TextureFormat::Rgba32Float;
110
111                let mut local_data =
112                    Vec::with_capacity(width as usize * height as usize * format.pixel_size());
113
114                for pixel in image.into_raw().chunks_exact(3) {
115                    // TODO: use the array_chunks method once stabilized
116                    // https://github.com/rust-lang/rust/issues/74985
117                    let r = pixel[0];
118                    let g = pixel[1];
119                    let b = pixel[2];
120                    let a = 1f32;
121
122                    local_data.extend_from_slice(&r.to_le_bytes());
123                    local_data.extend_from_slice(&g.to_le_bytes());
124                    local_data.extend_from_slice(&b.to_le_bytes());
125                    local_data.extend_from_slice(&a.to_le_bytes());
126                }
127
128                data = local_data;
129            }
130            DynamicImage::ImageRgba32F(image) => {
131                width = image.width();
132                height = image.height();
133                format = TextureFormat::Rgba32Float;
134
135                let raw_data = image.into_raw();
136
137                data = cast_slice(&raw_data).to_owned();
138            }
139            // DynamicImage is now non exhaustive, catch future variants and convert them
140            _ => {
141                let image = dyn_img.into_rgba8();
142                width = image.width();
143                height = image.height();
144                format = TextureFormat::Rgba8UnormSrgb;
145
146                data = image.into_raw();
147            }
148        }
149
150        Image::new(
151            Extent3d {
152                width,
153                height,
154                depth_or_array_layers: 1,
155            },
156            TextureDimension::D2,
157            data,
158            format,
159            asset_usage,
160        )
161    }
162
163    /// Convert a [`Image`] to a [`DynamicImage`]. Useful for editing image
164    /// data. Not all [`TextureFormat`] are covered, therefore it will return an
165    /// error if the format is unsupported. Supported formats are:
166    /// - `TextureFormat::R8Unorm`
167    /// - `TextureFormat::Rg8Unorm`
168    /// - `TextureFormat::Rgba8UnormSrgb`
169    /// - `TextureFormat::Bgra8UnormSrgb`
170    ///
171    /// To convert [`Image`] to a different format see: [`Image::convert`].
172    pub fn try_into_dynamic(self) -> Result<DynamicImage, IntoDynamicImageError> {
173        let width = self.width();
174        let height = self.height();
175        let Some(data) = self.data else {
176            return Err(IntoDynamicImageError::UninitializedImage);
177        };
178        match self.texture_descriptor.format {
179            TextureFormat::R8Unorm => {
180                ImageBuffer::from_raw(width, height, data).map(DynamicImage::ImageLuma8)
181            }
182            TextureFormat::Rg8Unorm => {
183                ImageBuffer::from_raw(width, height, data).map(DynamicImage::ImageLumaA8)
184            }
185            TextureFormat::Rgba8UnormSrgb => {
186                ImageBuffer::from_raw(width, height, data).map(DynamicImage::ImageRgba8)
187            }
188            // This format is commonly used as the format for the swapchain texture
189            // This conversion is added here to support screenshots
190            TextureFormat::Bgra8UnormSrgb | TextureFormat::Bgra8Unorm => {
191                ImageBuffer::from_raw(width, height, {
192                    let mut data = data;
193                    for bgra in data.chunks_exact_mut(4) {
194                        bgra.swap(0, 2);
195                    }
196                    data
197                })
198                .map(DynamicImage::ImageRgba8)
199            }
200            // Throw and error if conversion isn't supported
201            texture_format => return Err(IntoDynamicImageError::UnsupportedFormat(texture_format)),
202        }
203        .ok_or(IntoDynamicImageError::UnknownConversionError(
204            self.texture_descriptor.format,
205        ))
206    }
207}
208
209/// Errors that occur while converting an [`Image`] into a [`DynamicImage`]
210#[non_exhaustive]
211#[derive(Error, Debug)]
212pub enum IntoDynamicImageError {
213    /// Conversion into dynamic image not supported for source format.
214    #[error("Conversion into dynamic image not supported for {0:?}.")]
215    UnsupportedFormat(TextureFormat),
216
217    /// Encountered an unknown error during conversion.
218    #[error("Failed to convert into {0:?}.")]
219    UnknownConversionError(TextureFormat),
220
221    /// Tried to convert an image that has no texture data
222    #[error("Image has no texture data")]
223    UninitializedImage,
224}
225
226#[cfg(test)]
227mod test {
228    use image::{GenericImage, Rgba};
229
230    use super::*;
231
232    #[test]
233    fn two_way_conversion() {
234        // Check to see if color is preserved through an rgba8 conversion and back.
235        let mut initial = DynamicImage::new_rgba8(1, 1);
236        initial.put_pixel(0, 0, Rgba::from([132, 3, 7, 200]));
237
238        let image = Image::from_dynamic(initial.clone(), true, RenderAssetUsages::RENDER_WORLD);
239
240        // NOTE: Fails if `is_srgb = false` or the dynamic image is of the type rgb8.
241        assert_eq!(initial, image.try_into_dynamic().unwrap());
242    }
243}