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

@ -169,15 +169,22 @@ fn show_image<'mw>(req: &mut Request, mut res: Response<'mw>)
if let Ok(photo) = req.orm_get::<Photo>("id", &id) { if let Ok(photo) = req.orm_get::<Photo>("id", &id) {
if req.authorized_user().is_some() || photo.is_public() { if req.authorized_user().is_some() || photo.is_public() {
if let Some(size) = match req.param("size").unwrap() { if let Some(size) = match req.param("size").unwrap() {
"s" => Some(200), "s" => Some(200),
"m" => Some(800), "m" => Some(800),
"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) {
res.set(MediaType::Jpeg); Ok(buf) => {
res.set(Expires(HttpDate(time::now() + Duration::days(14)))); res.set(MediaType::Jpeg);
return res.send(buf); res.set(Expires(HttpDate(time::now() + Duration::days(14))));
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)]