Dont panic.

Handle errors in image scaling properly.
This commit is contained in:
Rasmus Kaj 2016-05-03 18:37:35 +02:00
parent 1a421537fb
commit 88b0d8b57b
2 changed files with 21 additions and 14 deletions

View File

@ -174,10 +174,17 @@ fn show_image<'mw>(req: &mut Request, mut res: Response<'mw>)
"l" => Some(1200), "l" => Some(1200),
_ => None _ => None
} { } {
let buf = req.photos().get_scaled_image(photo, size, size); match req.photos().get_scaled_image(photo, size, size) {
Ok(buf) => {
res.set(MediaType::Jpeg); res.set(MediaType::Jpeg);
res.set(Expires(HttpDate(time::now() + Duration::days(14)))); res.set(Expires(HttpDate(time::now() + Duration::days(14))));
return res.send(buf); return res.send(buf);
},
Err(err) => {
return res.error(StatusCode::InternalServerError,
format!("{}", err));
}
}
} }
} }
} }

View File

@ -2,7 +2,7 @@ use std::path::{Path, PathBuf};
use std::fs; use std::fs;
use std::io; use std::io;
use image::open as image_open; use image::open as image_open;
use image::{FilterType, ImageFormat, GenericImage}; use image::{FilterType, ImageFormat, GenericImage, ImageError};
use rexif::{self, ExifData}; use rexif::{self, ExifData};
use models::Photo; use models::Photo;
@ -20,10 +20,10 @@ impl PhotosDir {
#[allow(dead_code)] #[allow(dead_code)]
pub fn get_scaled_image(&self, photo: Photo, width: u32, height: u32) pub fn get_scaled_image(&self, photo: Photo, width: u32, height: u32)
-> Vec<u8> { -> Result<Vec<u8>, ImageError> {
let path = self.basedir.join(photo.path); let path = self.basedir.join(photo.path);
info!("Should open {:?}", path); info!("Should open {:?}", path);
let img = image_open(path).unwrap(); let img = try!(image_open(path));
let img = let img =
if width < img.width() || height < img.height() { if width < img.width() || height < img.height() {
img.resize(width, height, FilterType::CatmullRom) img.resize(width, height, FilterType::CatmullRom)
@ -43,8 +43,8 @@ impl PhotosDir {
}; };
// TODO Put the icon in some kind of cache! // TODO Put the icon in some kind of cache!
let mut buf : Vec<u8> = Vec::new(); let mut buf : Vec<u8> = Vec::new();
img.save(&mut buf, ImageFormat::JPEG).unwrap(); try!(img.save(&mut buf, ImageFormat::JPEG));
buf Ok(buf)
} }
#[allow(dead_code)] #[allow(dead_code)]