Skip to content

Commit

Permalink
guess image formats
Browse files Browse the repository at this point in the history
  • Loading branch information
robtfm committed Feb 20, 2024
1 parent 6d547d7 commit 6b3ffac
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
22 changes: 22 additions & 0 deletions crates/bevy_render/src/texture/image.rs
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,26 @@ impl ImageFormat {
ImageFormat::Basis | ImageFormat::Ktx2 => return None,
})
}

pub fn from_image_crate_format(format: image::ImageFormat) -> Option<Self> {
Some(match format {
image::ImageFormat::Avif => ImageFormat::Avif,
image::ImageFormat::Bmp => ImageFormat::Bmp,
image::ImageFormat::Dds => ImageFormat::Dds,
image::ImageFormat::Farbfeld => ImageFormat::Farbfeld,
image::ImageFormat::Gif => ImageFormat::Gif,
image::ImageFormat::OpenExr => ImageFormat::OpenExr,
image::ImageFormat::Hdr => ImageFormat::Hdr,
image::ImageFormat::Ico => ImageFormat::Ico,
image::ImageFormat::Jpeg => ImageFormat::Jpeg,
image::ImageFormat::Png => ImageFormat::Png,
image::ImageFormat::Pnm => ImageFormat::Pnm,
image::ImageFormat::Tga => ImageFormat::Tga,
image::ImageFormat::Tiff => ImageFormat::Tiff,
image::ImageFormat::WebP => ImageFormat::WebP,
_ => return None,
})
}
}

#[derive(Asset, Reflect, Debug, Clone)]
Expand Down Expand Up @@ -734,6 +754,8 @@ pub enum TextureError {
InvalidImageMimeType(String),
#[error("invalid image extension: {0}")]
InvalidImageExtension(String),
#[error("invalid image content type: {0:?}")]
InvalidImageContentType(image::ImageFormat),
#[error("failed to load an image: {0}")]
ImageError(#[from] image::ImageError),
#[error("unsupported texture format: {0}")]
Expand Down
15 changes: 15 additions & 0 deletions crates/bevy_render/src/texture/image_loader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ pub(crate) const IMG_FILE_EXTENSIONS: &[&str] = &[
#[derive(Serialize, Deserialize, Default, Debug)]
pub enum ImageFormatSetting {
#[default]
FromContent,
FromExtension,
Format(ImageFormat),
}
Expand Down Expand Up @@ -98,6 +99,20 @@ impl AssetLoader for ImageLoader {
let mut bytes = Vec::new();
reader.read_to_end(&mut bytes).await?;
let image_type = match settings.format {
ImageFormatSetting::FromContent => {
let image_crate_format =
image::guess_format(&bytes).map_err(|err| FileTextureError {
error: TextureError::ImageError(err),
path: format!("{}", load_context.path().display()),
})?;

let format = ImageFormat::from_image_crate_format(image_crate_format)
.ok_or_else(|| FileTextureError {
error: TextureError::InvalidImageContentType(image_crate_format),
path: format!("{}", load_context.path().display()),
})?;
ImageType::Format(format)
}
ImageFormatSetting::FromExtension => ImageType::Extension(ext),
ImageFormatSetting::Format(format) => ImageType::Format(format),
};
Expand Down

0 comments on commit 6b3ffac

Please sign in to comment.