fixed image processing logic, implement creating dir if it doesn't already exist

This commit is contained in:
Penelope Gwen 2025-09-22 19:10:08 -07:00
parent b1a2822324
commit 69dbead6ee
3 changed files with 20 additions and 11 deletions

2
Cargo.lock generated
View file

@ -420,7 +420,7 @@ dependencies = [
[[package]]
name = "random-image"
version = "0.1.0"
version = "0.1.2"
dependencies = [
"clap",
"globwalk",

View file

@ -1,7 +1,7 @@
[package]
name = "random-image"
authors = ["Penelope Gwen <support@pogmom.me>"]
version = "0.1.0"
version = "0.1.2"
edition = "2024"
description = "Finds a random image file in a directory and converts it into a sized square"
license-file = "license.md"

View file

@ -2,7 +2,7 @@
use clap::Parser;
use magick_rust::MagickWand;
use std::path::{Path, PathBuf};
use std::{fs, path::{Path, PathBuf}};
use rand::seq::IteratorRandom;
use xdg::BaseDirectories;
@ -73,22 +73,27 @@ pub fn output_path(image_path: PathBuf) -> Result<PathBuf,String> {
pub fn calc_img_ops(orig_height: usize, orig_width: usize, size: usize) -> ImgOps {
let r = orig_width as f32 / orig_height as f32;
//println!("r: {:#?}",r);
let w = match r.gt(&1.0) {
true => (r.abs() * size as f32) as usize,
false => size,
};
//println!("w: {:#?}",w);
let h = match r.lt(&1.0) {
true => (r.abs() * size as f32) as usize,
true => (size as f32 / r) as usize,
false => size,
};
//println!("h: {:#?}",h);
let x = match r.gt(&1.0) {
true => (w - size) / 2,
false => 0_usize,
} as isize;
//println!("x: {:#?}",x);
let y = match r.lt(&1.0) {
true => (h - size) / 2,
false => 0_usize,
} as isize;
//println!("y: {:#?}",y);
ImgOps{ width: w, height: h, x_offset: x, y_offset: y }
}
@ -99,14 +104,18 @@ pub fn scale_image(image_path: PathBuf, cached_image_path: PathBuf, size: usize)
match magick_image.read_image(img_str) {
Ok(_) => {
let ops = calc_img_ops(magick_image.get_image_height(), magick_image.get_image_width(), size);
match magick_image.resize_image(ops.width, ops.height, magick_rust::FilterType::Cubic) {
match magick_image.resize_image(ops.width, ops.height, magick_rust::FilterType::Undefined) {
Ok(_) => match magick_image.crop_image(size, size, ops.x_offset, ops.y_offset) {
Ok(_) => match cached_image_path.to_str() {
Some(cache_str) => match magick_image.write_image(cache_str) {
Ok(_) => Ok(cached_image_path),
Err(e) => Err(e.to_string()),
},
None => Err("Undefined filepath error".to_string()),
Ok(_) => {
let mut dir = fs::DirBuilder::new();
let _ = dir.recursive(true).create(cached_image_path.parent().unwrap());
match cached_image_path.to_str() {
Some(cache_str) => match magick_image.write_image(cache_str) {
Ok(_) => Ok(cached_image_path),
Err(e) => Err(e.to_string()),
},
None => Err("Undefined filepath error".to_string()),
}
},
Err(_) => todo!(),
}