Skip to content

Commit

Permalink
feat: optimize png encoding (#12)
Browse files Browse the repository at this point in the history
  • Loading branch information
fgardt authored Mar 21, 2024
1 parent d71dae1 commit 7a2dee7
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 8 deletions.
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,6 @@ cast_sign_loss = "allow"
[dependencies]
clap = { version = "4.5", features = ["derive"] }
env_logger = "0.10"
image = "0.25"
image = { version = "0.25", features = ["png"] }
log = "0.4"
thiserror = "1.0"
36 changes: 34 additions & 2 deletions src/image_util.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
use std::{fs, path::Path};
use std::{fs, ops::Deref, path::Path};

use image::RgbaImage;
use image::{
codecs::png, EncodableLayout, ImageBuffer, ImageEncoder, Pixel, PixelWithColorType, RgbaImage,
};

#[derive(Debug, thiserror::Error)]
pub enum ImgUtilError {
Expand Down Expand Up @@ -157,3 +159,33 @@ pub fn crop_images(images: &mut Vec<RgbaImage>) -> ImgUtilResult<(i32, i32)> {

Ok((shift_x, shift_y))
}

pub trait ImageBufferExt<P, C> {
fn save_optimized_png(&self, path: impl AsRef<Path>) -> ImgUtilResult<()>;
}

impl<P, C> ImageBufferExt<P, C> for ImageBuffer<P, C>
where
P: Pixel + PixelWithColorType,
[P::Subpixel]: EncodableLayout,
C: Deref<Target = [P::Subpixel]>,
{
fn save_optimized_png(&self, path: impl AsRef<Path>) -> ImgUtilResult<()> {
let mut file = fs::File::create(path)?;

let (width, height) = self.dimensions();
png::PngEncoder::new_with_quality(
&mut file,
png::CompressionType::Best,
png::FilterType::default(),
)
.write_image(
self.as_bytes(),
width,
height,
<P as PixelWithColorType>::COLOR_TYPE,
)?;

Ok(())
}
}
8 changes: 3 additions & 5 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ use std::{

use clap::{Args, Parser, Subcommand};
use image::{ImageBuffer, RgbaImage};
use image_util::ImageBufferExt;

#[macro_use]
extern crate log;
Expand Down Expand Up @@ -277,10 +278,7 @@ fn generate_mipmap_icon(args: &IconArgs) -> Result<(), CommandError> {

image::imageops::crop_imm(&res, 0, 0, total_width, res.height())
.to_image()
.save_with_format(
output_name(&args.source, &args.output, None, "png"),
image::ImageFormat::Png,
)?;
.save_optimized_png(output_name(&args.source, &args.output, None, "png"))?;

Ok(())
}
Expand Down Expand Up @@ -401,7 +399,7 @@ fn generate_spritesheet(

// save sheets
for (sheet, path) in sheets {
sheet.save_with_format(path, image::ImageFormat::Png)?;
sheet.save_optimized_png(path)?;
}

let name = output_name(source, &args.output, None, "");
Expand Down

0 comments on commit 7a2dee7

Please sign in to comment.