Skip to content

Commit

Permalink
Merge pull request #6 from stevent-team/fix/webp-image-format-errors
Browse files Browse the repository at this point in the history
Convert image data to supported format before encoding as webp
  • Loading branch information
giraugh authored Aug 5, 2024
2 parents 8717d13 + 25f38c3 commit 03dd281
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 9 deletions.
Binary file added img.webp
Binary file not shown.
25 changes: 16 additions & 9 deletions src/favicon_image/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
pub mod fetch;
mod svg;

use image::{imageops::FilterType, ImageFormat};
use image::{imageops::FilterType, DynamicImage, ImageFormat};
use std::io;
use thiserror::Error;

Expand Down Expand Up @@ -40,9 +40,7 @@ impl FaviconImage {
}

// Convert image format to output format type
let output_format: image::ImageOutputFormat = format
.try_into()
.map_err(|_| WriteImageError::UnsupportedImageFormat)?;
let output_format: image::ImageOutputFormat = format.into();

// Write image
self.data.write_to(writer, output_format)?;
Expand All @@ -53,9 +51,22 @@ impl FaviconImage {
&self,
writer: &mut (impl io::Write + io::Seek),
) -> Result<(), WriteImageError> {
let encoder = webp::Encoder::from_image(&self.data).expect("Image format is supported");
// Ensure image data is in a format supported by `webp`
let data = match self.data {
DynamicImage::ImageRgba8(_) => &self.data,
DynamicImage::ImageRgb8(_) => &self.data,
_ => {
let data = self.data.to_rgba8();
&DynamicImage::ImageRgba8(data)
}
};

// Write to webp
let encoder =
webp::Encoder::from_image(data).map_err(|_| WriteImageError::UnsupportedImageFormat)?;
let webp = encoder.encode(WEBP_QUALITY);
writer.write_all(webp.as_ref())?;

Ok(())
}

Expand Down Expand Up @@ -92,8 +103,4 @@ mod server {
([("content-type", content_type)], body.into_inner()).into_response()
}
}

trait ImageFormatContentTypeExt {
fn content_type(&self) -> String;
}
}

0 comments on commit 03dd281

Please sign in to comment.