bevy_image/
image_texture_conversion.rs1use crate::{Image, TextureFormatPixelInfo};
2use bevy_asset::RenderAssetUsages;
3use image::{DynamicImage, ImageBuffer};
4use thiserror::Error;
5use wgpu_types::{Extent3d, TextureDimension, TextureFormat};
6
7impl Image {
8 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 = Vec::with_capacity(
112 width as usize * height as usize * format.pixel_size().unwrap_or(0),
113 );
114
115 for [r, g, b] in image.into_raw().as_chunks().0 {
116 let a = 1f32;
117
118 local_data.extend_from_slice(&r.to_le_bytes());
119 local_data.extend_from_slice(&g.to_le_bytes());
120 local_data.extend_from_slice(&b.to_le_bytes());
121 local_data.extend_from_slice(&a.to_le_bytes());
122 }
123
124 data = local_data;
125 }
126 DynamicImage::ImageRgba32F(image) => {
127 width = image.width();
128 height = image.height();
129 format = TextureFormat::Rgba32Float;
130
131 let raw_data = image.into_raw();
132
133 data = cast_slice(&raw_data).to_owned();
134 }
135 _ => {
137 let image = dyn_img.into_rgba8();
138 width = image.width();
139 height = image.height();
140 format = TextureFormat::Rgba8UnormSrgb;
141
142 data = image.into_raw();
143 }
144 }
145
146 Image::new(
147 Extent3d {
148 width,
149 height,
150 depth_or_array_layers: 1,
151 },
152 TextureDimension::D2,
153 data,
154 format,
155 asset_usage,
156 )
157 }
158
159 pub fn try_into_dynamic(self) -> Result<DynamicImage, IntoDynamicImageError> {
169 let width = self.width();
170 let height = self.height();
171 let Some(data) = self.data else {
172 return Err(IntoDynamicImageError::UninitializedImage);
173 };
174 match self.texture_descriptor.format {
175 TextureFormat::R8Unorm => {
176 ImageBuffer::from_raw(width, height, data).map(DynamicImage::ImageLuma8)
177 }
178 TextureFormat::Rg8Unorm => {
179 ImageBuffer::from_raw(width, height, data).map(DynamicImage::ImageLumaA8)
180 }
181 TextureFormat::Rgba8UnormSrgb => {
182 ImageBuffer::from_raw(width, height, data).map(DynamicImage::ImageRgba8)
183 }
184 TextureFormat::Bgra8UnormSrgb | TextureFormat::Bgra8Unorm => {
187 ImageBuffer::from_raw(width, height, {
188 let mut data = data;
189 for [b, _, r, _] in data.as_chunks_mut().0 {
190 core::mem::swap(b, r);
191 }
192 data
193 })
194 .map(DynamicImage::ImageRgba8)
195 }
196 texture_format => return Err(IntoDynamicImageError::UnsupportedFormat(texture_format)),
198 }
199 .ok_or(IntoDynamicImageError::UnknownConversionError(
200 self.texture_descriptor.format,
201 ))
202 }
203}
204
205#[non_exhaustive]
207#[derive(Error, Debug)]
208pub enum IntoDynamicImageError {
209 #[error("Conversion into dynamic image not supported for {0:?}.")]
211 UnsupportedFormat(TextureFormat),
212
213 #[error("Failed to convert into {0:?}.")]
215 UnknownConversionError(TextureFormat),
216
217 #[error("Image has no texture data")]
219 UninitializedImage,
220}
221
222#[cfg(test)]
223mod test {
224 use image::{GenericImage, Rgba};
225
226 use super::*;
227
228 #[test]
229 fn two_way_conversion() {
230 let mut initial = DynamicImage::new_rgba8(1, 1);
232 initial.put_pixel(0, 0, Rgba::from([132, 3, 7, 200]));
233
234 let image = Image::from_dynamic(initial.clone(), true, RenderAssetUsages::RENDER_WORLD);
235
236 assert_eq!(initial, image.try_into_dynamic().unwrap());
238 }
239}