You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

328 lines
11KB

  1. #[macro_use]
  2. extern crate lazy_static;
  3. extern crate regex;
  4. extern crate image;
  5. extern crate rayon;
  6. extern crate twox_hash;
  7. extern crate utils;
  8. extern crate errors;
  9. use std::path::{Path, PathBuf};
  10. use std::hash::{Hash, Hasher};
  11. use std::collections::HashMap;
  12. use std::collections::hash_map::Entry as HEntry;
  13. use std::fs::{self, File};
  14. use regex::Regex;
  15. use image::{GenericImage, FilterType};
  16. use image::jpeg::JPEGEncoder;
  17. use rayon::prelude::*;
  18. use twox_hash::XxHash;
  19. use utils::fs as ufs;
  20. use errors::{Result, ResultExt};
  21. static RESIZED_SUBDIR: &'static str = "_resized_images";
  22. lazy_static!{
  23. pub static ref RESIZED_FILENAME: Regex = Regex::new(r#"([0-9a-f]{16})([0-9a-f]{2})[.]jpg"#).unwrap();
  24. }
  25. /// Describes the precise kind of a resize operation
  26. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  27. pub enum ResizeOp {
  28. /// A simple scale operation that doesn't take aspect ratio into account
  29. Scale(u32, u32),
  30. /// Scales the image to a specified width with height computed such that aspect ratio is preserved
  31. FitWidth(u32),
  32. /// Scales the image to a specified height with width computed such that aspect ratio is preserved
  33. FitHeight(u32),
  34. /// Scales the image such that it fits within the specified width and height preserving aspect ratio.
  35. /// Either dimension may end up being smaller, but never larger than specified.
  36. Fit(u32, u32),
  37. /// Scales the image such that it fills the specified width and height. Output will always have the exact dimensions specified.
  38. /// The part of the image that doesn't fit in the thumbnail due to differing aspect ratio will be cropped away, if any.
  39. Fill(u32, u32),
  40. }
  41. impl ResizeOp {
  42. pub fn from_args(op: &str, width: Option<u32>, height: Option<u32>) -> Result<ResizeOp> {
  43. use ResizeOp::*;
  44. // Validate args:
  45. match op {
  46. "fitwidth" => if width.is_none() { return Err(format!("op=fitwidth requires a `width` argument").into()) },
  47. "fitheight" => if height.is_none() { return Err(format!("op=fitwidth requires a `height` argument").into()) },
  48. "scale" | "fit" | "fill" => if width.is_none() || height.is_none() {
  49. return Err(format!("op={} requires a `width` and `height` argument", op).into())
  50. },
  51. _ => return Err(format!("Invalid image resize operation: {}", op).into())
  52. };
  53. Ok(match op {
  54. "scale" => Scale(width.unwrap(), height.unwrap()),
  55. "fitwidth" => FitWidth(width.unwrap()),
  56. "fitheight" => FitHeight(height.unwrap()),
  57. "fit" => Fit(width.unwrap(), height.unwrap()),
  58. "fill" => Fill(width.unwrap(), height.unwrap()),
  59. _ => unreachable!(),
  60. })
  61. }
  62. pub fn width(self) -> Option<u32> {
  63. use ResizeOp::*;
  64. match self {
  65. Scale(w, _) => Some(w),
  66. FitWidth(w) => Some(w),
  67. FitHeight(_) => None,
  68. Fit(w, _) => Some(w),
  69. Fill(w, _) => Some(w),
  70. }
  71. }
  72. pub fn height(self) -> Option<u32> {
  73. use ResizeOp::*;
  74. match self {
  75. Scale(_, h) => Some(h),
  76. FitWidth(_) => None,
  77. FitHeight(h) => Some(h),
  78. Fit(_, h) => Some(h),
  79. Fill(_, h) => Some(h),
  80. }
  81. }
  82. }
  83. impl From<ResizeOp> for u8 {
  84. fn from(op: ResizeOp) -> u8 {
  85. use ResizeOp::*;
  86. match op {
  87. Scale(_, _) => 1,
  88. FitWidth(_) => 2,
  89. FitHeight(_) => 3,
  90. Fit(_, _) => 4,
  91. Fill(_, _) => 5,
  92. }
  93. }
  94. }
  95. impl Hash for ResizeOp {
  96. fn hash<H: Hasher>(&self, hasher: &mut H) {
  97. hasher.write_u8(u8::from(*self));
  98. if let Some(w) = self.width() { hasher.write_u32(w); }
  99. if let Some(h) = self.height() { hasher.write_u32(h); }
  100. }
  101. }
  102. /// Holds all data needed to perform a resize operation
  103. #[derive(Debug, PartialEq, Eq)]
  104. pub struct ImageOp {
  105. source: String,
  106. op: ResizeOp,
  107. quality: u8,
  108. hash: u64,
  109. collision: Option<u32>,
  110. }
  111. impl ImageOp {
  112. pub fn new(source: String, op: ResizeOp, quality: u8) -> ImageOp {
  113. let mut hasher = XxHash::with_seed(0);
  114. hasher.write(source.as_ref());
  115. op.hash(&mut hasher);
  116. hasher.write_u8(quality);
  117. let hash = hasher.finish();
  118. ImageOp { source, op, quality, hash, collision: None }
  119. }
  120. pub fn from_args(source: String, op: &str, width: Option<u32>, height: Option<u32>, quality: u8) -> Result<ImageOp> {
  121. let op = ResizeOp::from_args(op, width, height)?;
  122. Ok(Self::new(source, op, quality))
  123. }
  124. fn num_colli(&self) -> u32 { self.collision.unwrap_or(0) }
  125. fn perform(&self, content_path: &Path, target_path: &Path) -> Result<()> {
  126. use ResizeOp::*;
  127. let src_path = content_path.join(&self.source);
  128. if !ufs::file_stale(&src_path, target_path) {
  129. return Ok(())
  130. }
  131. let mut img = image::open(&src_path)?;
  132. let (img_w, img_h) = img.dimensions();
  133. const RESIZE_FILTER: FilterType = FilterType::Gaussian;
  134. const RATIO_EPSILLION: f32 = 0.1;
  135. let img = match self.op {
  136. Scale(w, h) => img.resize_exact(w, h, RESIZE_FILTER),
  137. FitWidth(w) => img.resize(w, u32::max_value(), RESIZE_FILTER),
  138. FitHeight(h) => img.resize(u32::max_value(), h, RESIZE_FILTER),
  139. Fit(w, h) => img.resize(w, h, RESIZE_FILTER),
  140. Fill(w, h) => {
  141. let fw = img_w as f32 / w as f32;
  142. let fh = img_h as f32 / h as f32;
  143. if (fw - fh).abs() <= RATIO_EPSILLION {
  144. // The aspect is similar enough that there's not much point in cropping
  145. img.resize_exact(w, h, RESIZE_FILTER)
  146. } else {
  147. // We perform the fill such that a crop is performed first and then resize_exact can be used,
  148. // which should be cheaper than resizing and then cropping (smaller number of pixels to resize).
  149. let (crop_w, crop_h) = match fw < fh {
  150. true => (img_w, (fw * h as f32).round() as u32),
  151. false => ((fh * w as f32).round() as u32, img_h),
  152. };
  153. let (off_w, off_h) = match fw < fh {
  154. true => (0, (img_h - crop_h) / 2),
  155. false => ((img_w - crop_w) / 2, 0),
  156. };
  157. img.crop(off_w, off_h, crop_w, crop_h).resize_exact(w, h, RESIZE_FILTER)
  158. }
  159. },
  160. };
  161. let mut f = File::create(target_path)?;
  162. let mut enc = JPEGEncoder::new_with_quality(&mut f, self.quality);
  163. let (img_w, img_h) = img.dimensions();
  164. enc.encode(&img.raw_pixels(), img_w, img_h, img.color())?;
  165. Ok(())
  166. }
  167. }
  168. /// A strcture into which image operations can be enqueued and then performed.
  169. /// All output is written in a subdirectory in `static_path`,
  170. /// taking care of file stale status based on timestamps and possible hash collisions.
  171. #[derive(Debug)]
  172. pub struct Processor {
  173. content_path: PathBuf,
  174. resized_path: PathBuf,
  175. resized_url: String,
  176. img_ops: HashMap<u64, ImageOp>,
  177. // Hash collisions go here:
  178. img_ops_colls: Vec<ImageOp>,
  179. }
  180. impl Processor {
  181. pub fn new(content_path: PathBuf, static_path: &Path, base_url: &str) -> Processor {
  182. Processor {
  183. content_path,
  184. resized_path: static_path.join(RESIZED_SUBDIR),
  185. resized_url: Self::resized_url(base_url),
  186. img_ops: HashMap::new(),
  187. img_ops_colls: Vec::new(),
  188. }
  189. }
  190. fn resized_url(base_url: &str) -> String {
  191. match base_url.ends_with('/') {
  192. true => format!("{}{}", base_url, RESIZED_SUBDIR),
  193. false => format!("{}/{}", base_url, RESIZED_SUBDIR),
  194. }
  195. }
  196. pub fn set_base_url(&mut self, base_url: &str) {
  197. self.resized_url = Self::resized_url(base_url);
  198. }
  199. pub fn source_exists(&self, source: &str) -> bool {
  200. self.content_path.join(source).exists()
  201. }
  202. pub fn num_img_ops(&self) -> usize {
  203. self.img_ops.len() + self.img_ops_colls.len()
  204. }
  205. fn insert_with_colls(&mut self, mut img_op: ImageOp) -> u32 {
  206. match self.img_ops.entry(img_op.hash) {
  207. HEntry::Occupied(entry) => if *entry.get() == img_op { return 0; },
  208. HEntry::Vacant(entry) => {
  209. entry.insert(img_op);
  210. return 0;
  211. },
  212. }
  213. // If we get here, that means a hash collision.
  214. let mut num = 1;
  215. for op in self.img_ops_colls.iter().filter(|op| op.hash == img_op.hash) {
  216. if *op == img_op {
  217. return num;
  218. } else {
  219. num += 1;
  220. }
  221. }
  222. if num == 1 {
  223. self.img_ops.get_mut(&img_op.hash).unwrap().collision = Some(0);
  224. }
  225. img_op.collision = Some(num);
  226. self.img_ops_colls.push(img_op);
  227. num
  228. }
  229. fn op_filename(hash: u64, colli_num: u32) -> String {
  230. // Please keep this in sync with RESIZED_FILENAME
  231. assert!(colli_num < 256, "Unexpectedly large number of collisions: {}", colli_num);
  232. format!("{:016x}{:02x}.jpg", hash, colli_num)
  233. }
  234. fn op_url(&self, hash: u64, colli_num: u32) -> String {
  235. format!("{}/{}", &self.resized_url, Self::op_filename(hash, colli_num))
  236. }
  237. pub fn insert(&mut self, img_op: ImageOp) -> String {
  238. let hash = img_op.hash;
  239. let num_colli = self.insert_with_colls(img_op);
  240. self.op_url(hash, num_colli)
  241. }
  242. pub fn prune(&self) -> Result<()> {
  243. ufs::ensure_directory_exists(&self.resized_path)?;
  244. let entries = fs::read_dir(&self.resized_path)?;
  245. for entry in entries {
  246. let entry_path = entry?.path();
  247. if entry_path.is_file() {
  248. let filename = entry_path.file_name().unwrap().to_string_lossy();
  249. if let Some(capts) = RESIZED_FILENAME.captures(filename.as_ref()) {
  250. let hash = u64::from_str_radix(capts.get(1).unwrap().as_str(), 16).unwrap();
  251. let num_colli = u32::from_str_radix(capts.get(2).unwrap().as_str(), 16).unwrap();
  252. if num_colli > 0 || !self.img_ops.contains_key(&hash) {
  253. fs::remove_file(&entry_path)?;
  254. }
  255. }
  256. }
  257. }
  258. Ok(())
  259. }
  260. pub fn do_process(&mut self) -> Result<()> {
  261. self.img_ops.par_iter().map(|(hash, op)| {
  262. let target = self.resized_path.join(Self::op_filename(*hash, op.num_colli()));
  263. op.perform(&self.content_path, &target)
  264. .chain_err(|| format!("Failed to process image: {}", op.source))
  265. })
  266. .fold(|| Ok(()), Result::and)
  267. .reduce(|| Ok(()), Result::and)
  268. }
  269. }
  270. /// Looks at file's extension and returns whether it's a supported image format
  271. pub fn file_is_img<P: AsRef<Path>>(p: P) -> bool {
  272. p.as_ref().extension().and_then(|s| s.to_str()).map(|ext| {
  273. match ext.to_lowercase().as_str() {
  274. "jpg" | "jpeg" => true,
  275. "png" => true,
  276. "gif" => true,
  277. "bmp" => true,
  278. _ => false,
  279. }
  280. }).unwrap_or(false)
  281. }