Skip to content

Commit

Permalink
chore: simplify the code in image.rs
Browse files Browse the repository at this point in the history
  • Loading branch information
nanpuyue committed Jan 20, 2024
1 parent fdd8d53 commit 1d9da87
Showing 1 changed file with 7 additions and 11 deletions.
18 changes: 7 additions & 11 deletions src/image.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ use std::io::Write;
use flate2::write::GzDecoder;
use image::error::ImageResult;
use image::load_from_memory;
use image::{DynamicImage, ImageBuffer, ImageOutputFormat, Rgba};
use image::{GenericImage, Pixel};
use image::GenericImage;
use image::{DynamicImage, ImageOutputFormat::Png, Rgba, RgbaImage};
use rlottie::{Animation, Surface};

use crate::error::Error;
Expand All @@ -17,7 +17,7 @@ fn alpha_composit(pixel: &mut Rgba<u8>, color: [i32; 3]) {
pixel[3] = 255;
}

fn trans_flag(img: &mut ImageBuffer<Rgba<u8>, Vec<u8>>) {
fn trans_flag(img: &mut RgbaImage) {
const COLOR: [[i32; 3]; 5] = [
[0x5b, 0xce, 0xfa],
[0xf5, 0xa9, 0xb8],
Expand Down Expand Up @@ -45,10 +45,7 @@ fn trans_flag(img: &mut ImageBuffer<Rgba<u8>, Vec<u8>>) {
});
}

fn square_image<P: Pixel<Subpixel = u8> + 'static>(
img: &mut ImageBuffer<P, Vec<u8>>,
align: &str,
) -> Option<ImageBuffer<P, Vec<u8>>> {
fn square_image(img: &mut RgbaImage, align: &str) -> Option<RgbaImage> {
let height = img.height();
let width = img.width();
if width >= height {
Expand Down Expand Up @@ -88,7 +85,7 @@ pub fn image_to_png(data: &mut Vec<u8>, background: &str, align: Option<&str>) -
}
}

DynamicImage::ImageRgba8(rgba).write_to(&mut Cursor::new(data), ImageOutputFormat::Png)
DynamicImage::ImageRgba8(rgba).write_to(&mut Cursor::new(data), Png)
}

pub fn tgs_to_png(data: Vec<u8>) -> Result<Vec<u8>, Error> {
Expand All @@ -99,13 +96,12 @@ pub fn tgs_to_png(data: Vec<u8>) -> Result<Vec<u8>, Error> {
let mut surface = Surface::new(animation.size());
animation.render(0, &mut surface);

let mut rgba = ImageBuffer::<Rgba<u8>, _>::new(surface.width() as _, surface.height() as _);
let mut rgba = RgbaImage::new(surface.width() as _, surface.height() as _);
for (x, y) in rgba.pixels_mut().zip(surface.data()) {
(x[0], x[1], x[2], x[3]) = (y.r, y.g, y.b, y.a);
}

let mut png_data = Vec::new();
DynamicImage::ImageRgba8(rgba)
.write_to(&mut Cursor::new(&mut png_data), ImageOutputFormat::Png)?;
DynamicImage::ImageRgba8(rgba).write_to(&mut Cursor::new(&mut png_data), Png)?;
Ok(png_data)
}

0 comments on commit 1d9da87

Please sign in to comment.