Skip to content

Commit

Permalink
improve image mime type guessing
Browse files Browse the repository at this point in the history
  • Loading branch information
kayhhh committed Feb 23, 2024
1 parent 7829921 commit 898462c
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 8 deletions.
25 changes: 18 additions & 7 deletions bevy_gltf_kun/src/import/gltf/image.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,6 @@ use super::document::ImportContext;
pub enum ImageImportError {
#[error("Failed to load texture: {0}")]
Texture(#[from] TextureError),
#[error("Missing mime type")]
MissingMimeType,
}

pub fn import_images<E: BevyImportExtensions<GltfDocument>>(
Expand Down Expand Up @@ -94,14 +92,27 @@ pub fn load_texture(

let image_weight = image.get(context.graph);
let supported_compressed_formats = CompressedImageFormats::default();
let mime_type = image_weight
.mime_type
.as_deref()
.ok_or(ImageImportError::MissingMimeType)?;

let image_type = match image_weight.mime_type.as_deref() {
Some(mime_type) => ImageType::MimeType(mime_type),
None => match &image_weight.uri {
Some(uri) => match uri.split('.').last() {
Some(ext) => ImageType::Extension(ext),
None => {
warn!("No extension found for image uri, defaulting to image/png.");
ImageType::MimeType("image/png")
}
},
None => {
warn!("No mime type or uri found for image, defaulting to image/png.");
ImageType::MimeType("image/png")
}
},
};

let texture = Image::from_buffer(
&image_weight.data,
ImageType::MimeType(mime_type),
image_type,
supported_compressed_formats,
is_srgb,
ImageSampler::Descriptor(sampler_descriptor),
Expand Down
24 changes: 23 additions & 1 deletion gltf_kun/src/io/format/gltf/import.rs
Original file line number Diff line number Diff line change
Expand Up @@ -144,10 +144,14 @@ pub async fn import(
weight.name = img.name.clone();
weight.extras = img.extras.clone();
weight.mime_type = img.mime_type.clone().map(|m| m.0);

if let Some(uri) = img.uri.as_ref() {
weight.uri = img.uri.clone();

// If no mime type, guess from the URI
if weight.mime_type.is_none() {
weight.mime_type = guess_mime_type(uri).map(|s| s.to_string())
}

if let Some(resolver) = resolver {
if let Ok(data) = resolver.resolve(uri).await {
debug!("Resolved image: {} ({} bytes)", uri, data.len());
Expand Down Expand Up @@ -470,6 +474,24 @@ fn import_texture_info(
texture_info
}

fn guess_mime_type(uri: &str) -> Option<&'static str> {
if uri.ends_with(".png") {
Some("image/png")
} else if uri.ends_with(".jpg") || uri.ends_with(".jpeg") {
Some("image/jpeg")
} else if uri.ends_with(".gif") {
Some("image/gif")
} else if uri.ends_with(".bmp") {
Some("image/bmp")
} else if uri.ends_with(".tiff") {
Some("image/tiff")
} else if uri.ends_with(".webp") {
Some("image/webp")
} else {
None
}
}

#[cfg(test)]
mod tests {
use gltf::json::{self, texture::Info, validation::USize64, Index};
Expand Down

0 comments on commit 898462c

Please sign in to comment.