refactor cowgen api

This commit is contained in:
cel 🌸 2023-01-12 16:00:46 +00:00
parent 6f34278423
commit 8893ca0c33
Signed by: cel
GPG Key ID: 48E29AF13B5F1349
2 changed files with 29 additions and 49 deletions

View File

@ -1,22 +1,10 @@
use ril::prelude::*;
pub struct Generate {
elements: Vec<Element>,
base: Image<Rgba>,
}
impl Generate {
pub fn new(base: Vec<u8>, elements: Vec<Element>) -> Result<Self, CowError> {
Ok(Self {
base: Image::<Rgba>::from_bytes_inferred(&base)?,
elements,
})
}
pub fn produce(self) -> Result<Vec<u8>, CowError> {
let size = self.base.dimensions();
let mut base_image = self.base.with_overlay_mode(OverlayMode::Merge);
for element in self.elements {
pub fn produce(base: &Vec<u8>, elements: Vec<Element>) -> Result<Vec<u8>, CowError> {
let base = Image::<Rgba>::from_bytes_inferred(base)?;
let size = base.dimensions();
let mut base_image = base.with_overlay_mode(OverlayMode::Merge);
for element in elements {
let mut pos = element.position;
let mut img: Image = element.into_image()?;
if pos.0 < 0 {
@ -34,7 +22,6 @@ impl Generate {
base_image.encode(ImageFormat::Png, &mut buf).unwrap();
Ok(buf)
}
}
pub struct Element {
@ -54,7 +41,7 @@ impl Element {
fn into_image(self) -> Result<Image, CowError> {
match self.media {
Media::Image(image) => Ok(Image::from_bytes_inferred(image)?.resized(
Media::Image(image) => Ok(Image::from_bytes_inferred(*image)?.resized(
self.dimensions.0,
self.dimensions.1,
ResizeAlgorithm::Bicubic,
@ -83,7 +70,7 @@ impl Element {
pub enum Media {
Text(Text),
Image(Vec<u8>),
Image(Box<Vec<u8>>),
}
pub struct Text {

View File

@ -7,28 +7,21 @@ use std::{
#[test]
fn test_overlay_text_and_image() {
println!("{}", std::env::current_dir().unwrap().to_str().unwrap());
let out = Generate::new(
include_bytes!("assets/cow.png").to_vec(),
let base = Box::new(include_bytes!("assets/cow.png").to_vec());
let font = Box::new(include_bytes!("assets/OpenSans-ExtraBold.ttf").to_vec());
let superimpose = Box::new(include_bytes!("assets/mariah.jpg").to_vec());
let out = produce(
&base,
vec![
Element::new(
Media::Text(Text::new(
"Hello",
"tests/assets/OpenSans-ExtraBold.ttf",
20.0,
(0, 0, 0, 128),
)),
Media::Text(Text::new("Hello".to_string(), font, 20.0, (0, 0, 0, 128))),
(0, 0),
(64, 64),
),
Element::new(
Media::Image(include_bytes!("assets/mariah.jpg").to_vec()),
(400, 400),
(800, 200),
),
Element::new(Media::Image(superimpose), (400, 400), (800, 200)),
],
)
.unwrap()
.produce()
.unwrap();
let mut f = File::create("tests/out/one.png").unwrap();
f.write_all(&out).unwrap();