bevy_image/
image_texture_conversion.rs

1use crate::{Image, TextureFormatPixelInfo};
2use bevy_asset::RenderAssetUsages;
3use derive_more::derive::{Display, Error};
4use image::{DynamicImage, ImageBuffer};
5use wgpu::{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        match self.texture_descriptor.format {
174            TextureFormat::R8Unorm => ImageBuffer::from_raw(self.width(), self.height(), self.data)
175                .map(DynamicImage::ImageLuma8),
176            TextureFormat::Rg8Unorm => {
177                ImageBuffer::from_raw(self.width(), self.height(), self.data)
178                    .map(DynamicImage::ImageLumaA8)
179            }
180            TextureFormat::Rgba8UnormSrgb => {
181                ImageBuffer::from_raw(self.width(), self.height(), self.data)
182                    .map(DynamicImage::ImageRgba8)
183            }
184            // This format is commonly used as the format for the swapchain texture
185            // This conversion is added here to support screenshots
186            TextureFormat::Bgra8UnormSrgb | TextureFormat::Bgra8Unorm => {
187                ImageBuffer::from_raw(self.width(), self.height(), {
188                    let mut data = self.data;
189                    for bgra in data.chunks_exact_mut(4) {
190                        bgra.swap(0, 2);
191                    }
192                    data
193                })
194                .map(DynamicImage::ImageRgba8)
195            }
196            // Throw and error if conversion isn't supported
197            texture_format => return Err(IntoDynamicImageError::UnsupportedFormat(texture_format)),
198        }
199        .ok_or(IntoDynamicImageError::UnknownConversionError(
200            self.texture_descriptor.format,
201        ))
202    }
203}
204
205/// Errors that occur while converting an [`Image`] into a [`DynamicImage`]
206#[non_exhaustive]
207#[derive(Error, Display, Debug)]
208pub enum IntoDynamicImageError {
209    /// Conversion into dynamic image not supported for source format.
210    #[display("Conversion into dynamic image not supported for {_0:?}.")]
211    #[error(ignore)]
212    UnsupportedFormat(TextureFormat),
213
214    /// Encountered an unknown error during conversion.
215    #[display("Failed to convert into {_0:?}.")]
216    #[error(ignore)]
217    UnknownConversionError(TextureFormat),
218}
219
220#[cfg(test)]
221mod test {
222    use image::{GenericImage, Rgba};
223
224    use super::*;
225
226    #[test]
227    fn two_way_conversion() {
228        // Check to see if color is preserved through an rgba8 conversion and back.
229        let mut initial = DynamicImage::new_rgba8(1, 1);
230        initial.put_pixel(0, 0, Rgba::from([132, 3, 7, 200]));
231
232        let image = Image::from_dynamic(initial.clone(), true, RenderAssetUsages::RENDER_WORLD);
233
234        // NOTE: Fails if `is_srbg = false` or the dynamic image is of the type rgb8.
235        assert_eq!(initial, image.try_into_dynamic().unwrap());
236    }
237}