Refactor for testing.
This commit is contained in:
@@ -7,8 +7,10 @@ use std::sync::Arc;
|
||||
|
||||
use google_photoslibrary1 as photos;
|
||||
use image::imageops::FilterType;
|
||||
use image::DynamicImage;
|
||||
use image::GenericImageView;
|
||||
use image::ImageFormat;
|
||||
use image::ImageResult;
|
||||
use log::error;
|
||||
use log::info;
|
||||
use log::warn;
|
||||
@@ -28,6 +30,37 @@ pub struct Library {
|
||||
cache_db: Arc<DB>,
|
||||
}
|
||||
|
||||
pub fn load_image<P>(path: P) -> ImageResult<DynamicImage>
|
||||
where
|
||||
P: AsRef<Path>,
|
||||
{
|
||||
image::io::Reader::open(&path)?
|
||||
.with_guessed_format()?
|
||||
.decode()
|
||||
}
|
||||
|
||||
pub fn resize(
|
||||
img: &DynamicImage,
|
||||
dimensions: (Option<u32>, Option<u32>),
|
||||
filter: FilterType,
|
||||
) -> DynamicImage {
|
||||
let (w, h) = dimensions;
|
||||
let (orig_w, orig_h) = img.dimensions();
|
||||
let (w, h) = match (w, h) {
|
||||
(Some(w), Some(h)) => (w, h),
|
||||
(Some(w), None) => (w, orig_h * w / orig_w),
|
||||
(None, Some(h)) => (orig_w * h / orig_h, h),
|
||||
(None, None) => (orig_w, orig_h),
|
||||
};
|
||||
img.resize_to_fill(w, h, filter)
|
||||
}
|
||||
|
||||
pub fn save_to_jpeg_bytes(img: DynamicImage) -> ImageResult<Vec<u8>> {
|
||||
let mut buf = Vec::new();
|
||||
img.write_to(&mut buf, ImageFormat::Jpeg)?;
|
||||
Ok(buf)
|
||||
}
|
||||
|
||||
impl Library {
|
||||
pub fn new(root: PathBuf) -> Result<Library, Box<dyn std::error::Error>> {
|
||||
let db = DB::open_default(root.join("cache"))?;
|
||||
@@ -155,7 +188,7 @@ impl Library {
|
||||
pub fn generate_thumbnail(
|
||||
&self,
|
||||
media_items_id: &str,
|
||||
(w, h): (Option<u32>, Option<u32>),
|
||||
dimensions: (Option<u32>, Option<u32>),
|
||||
filter: FilterType,
|
||||
) -> Result<Vec<u8>, io::Error> {
|
||||
match self.original(&media_items_id) {
|
||||
@@ -167,21 +200,11 @@ impl Library {
|
||||
))
|
||||
}
|
||||
Some(path) => {
|
||||
let orig_img = image::io::Reader::open(&path)?
|
||||
.with_guessed_format()?
|
||||
.decode()
|
||||
.map_err(|e| io::Error::new(io::ErrorKind::Other, e))?;
|
||||
let (orig_w, orig_h) = orig_img.dimensions();
|
||||
let (w, h) = match (w, h) {
|
||||
(Some(w), Some(h)) => (w, h),
|
||||
(Some(w), None) => (w, orig_h * w / orig_w),
|
||||
(None, Some(h)) => (orig_w * h / orig_h, h),
|
||||
(None, None) => (orig_w, orig_h),
|
||||
};
|
||||
let img = orig_img.resize_to_fill(w, h, filter);
|
||||
let mut buf = Vec::new();
|
||||
img.write_to(&mut buf, ImageFormat::Jpeg)
|
||||
.map_err(|e| io::Error::new(io::ErrorKind::Other, e))?;
|
||||
let orig_img =
|
||||
load_image(&path).map_err(|e| io::Error::new(io::ErrorKind::Other, e))?;
|
||||
let img = resize(&orig_img, dimensions, filter);
|
||||
let buf =
|
||||
save_to_jpeg_bytes(img).map_err(|e| io::Error::new(io::ErrorKind::Other, e))?;
|
||||
Ok(buf)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user