Thumbnail fixes (#121)

* Use dedicated thumbnail generation algorithm

* Fixed a bug where some images could not be encoded to JPG due to unsupported pixel formats
This commit is contained in:
Antoine Gersant 2020-12-20 03:27:20 -08:00 committed by GitHub
parent 72c8ed9289
commit 1d57691e8b
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -1,25 +1,24 @@
use anyhow::*;
use image::imageops::FilterType;
use image::{DynamicImage, GenericImage, GenericImageView, ImageBuffer};
use std::cmp;
use std::path::*;
use crate::app::thumbnail::{read, Options};
pub fn generate_thumbnail(image_path: &Path, thumbnailoptions: &Options) -> Result<DynamicImage> {
let source_image = read(image_path)?;
pub fn generate_thumbnail(image_path: &Path, options: &Options) -> Result<DynamicImage> {
let source_image = DynamicImage::ImageRgb8(read(image_path)?.into_rgb8());
let (source_width, source_height) = source_image.dimensions();
let largest_dimension = cmp::max(source_width, source_height);
let out_dimension = cmp::min(thumbnailoptions.max_dimension, largest_dimension);
let out_dimension = cmp::min(options.max_dimension, largest_dimension);
let source_aspect_ratio: f32 = source_width as f32 / source_height as f32;
let is_almost_square = source_aspect_ratio > 0.8 && source_aspect_ratio < 1.2;
let mut final_image;
if is_almost_square && thumbnailoptions.resize_if_almost_square {
final_image = source_image.resize_exact(out_dimension, out_dimension, FilterType::Lanczos3);
} else if thumbnailoptions.pad_to_square {
let scaled_image = source_image.resize(out_dimension, out_dimension, FilterType::Lanczos3);
if is_almost_square && options.resize_if_almost_square {
final_image = source_image.thumbnail_exact(out_dimension, out_dimension);
} else if options.pad_to_square {
let scaled_image = source_image.thumbnail(out_dimension, out_dimension);
let (scaled_width, scaled_height) = scaled_image.dimensions();
let background = image::Rgb([255, 255 as u8, 255 as u8]);
final_image = DynamicImage::ImageRgb8(ImageBuffer::from_pixel(
@ -33,7 +32,7 @@ pub fn generate_thumbnail(image_path: &Path, thumbnailoptions: &Options) -> Resu
(out_dimension - scaled_height) / 2,
)?;
} else {
final_image = source_image.resize(out_dimension, out_dimension, FilterType::Lanczos3);
final_image = source_image.thumbnail(out_dimension, out_dimension);
}
Ok(final_image)