Add JPEG Support for HG3

This commit is contained in:
2025-08-14 22:53:55 +08:00
parent 3973f3bb43
commit db8feced48
5 changed files with 137 additions and 29 deletions

View File

@@ -321,6 +321,37 @@ pub fn load_png<R: std::io::Read>(data: R) -> Result<ImageData> {
})
}
#[cfg(feature = "mozjpeg")]
pub fn load_jpg<R: std::io::Read>(data: R) -> Result<ImageData> {
let decoder = mozjpeg::decompress::Decompress::new_reader(std::io::BufReader::new(data))?;
let color_type = match decoder.color_space() {
mozjpeg::ColorSpace::JCS_GRAYSCALE => ImageColorType::Grayscale,
mozjpeg::ColorSpace::JCS_RGB => ImageColorType::Rgb,
mozjpeg::ColorSpace::JCS_EXT_RGBA => ImageColorType::Rgba,
_ => ImageColorType::Rgb, // Convert other types to RGB
};
let width = decoder.width() as u32;
let height = decoder.height() as u32;
let stride = width as usize * color_type.bpp(8) as usize / 8;
let mut data = vec![0; stride * height as usize];
let mut re = match color_type {
ImageColorType::Grayscale => decoder.grayscale()?,
ImageColorType::Rgb => decoder.rgb()?,
ImageColorType::Rgba => decoder.rgba()?,
_ => {
unreachable!(); // We already checked the color type above
}
};
re.read_scanlines_into(&mut data)?;
Ok(ImageData {
width,
height,
depth: 8,
color_type,
data,
})
}
/// Decodes an image from the specified file path and returns its data.
///
/// * `typ` - The type of the image to decode.
@@ -334,33 +365,7 @@ pub fn decode_img(typ: ImageOutputType, filename: &str) -> Result<ImageData> {
#[cfg(feature = "image-jpg")]
ImageOutputType::Jpg => {
let file = crate::utils::files::read_file(filename)?;
let decoder = mozjpeg::decompress::Decompress::new_mem(&file)?;
let color_type = match decoder.color_space() {
mozjpeg::ColorSpace::JCS_GRAYSCALE => ImageColorType::Grayscale,
mozjpeg::ColorSpace::JCS_RGB => ImageColorType::Rgb,
mozjpeg::ColorSpace::JCS_EXT_RGBA => ImageColorType::Rgba,
_ => ImageColorType::Rgb, // Convert other types to RGB
};
let width = decoder.width() as u32;
let height = decoder.height() as u32;
let stride = width as usize * color_type.bpp(8) as usize / 8;
let mut data = vec![0; stride * height as usize];
let mut re = match color_type {
ImageColorType::Grayscale => decoder.grayscale()?,
ImageColorType::Rgb => decoder.rgb()?,
ImageColorType::Rgba => decoder.rgba()?,
_ => {
unreachable!(); // We already checked the color type above
}
};
re.read_scanlines_into(&mut data)?;
Ok(ImageData {
width,
height,
depth: 8,
color_type,
data,
})
load_jpg(&file[..])
}
#[cfg(feature = "image-webp")]
ImageOutputType::Webp => {