Resize Blob image before saving to Play Framework
I am developing a webpage using Java and Play Framework 1.2.4.
I have a simple file input form that allows the user to upload an image file. Sometimes the image is too big and it takes a long time to display the image, so I need to resize the image. How can I do this with the game?
I know the function Images.resize (from, to, w, h), I tried to use it, but it doesn't work as I expected, here is my code:
public static void uploadPicture(long product_id, Blob data) throws FileNotFoundException {
String type = data.type();
File f = data.getFile();
Images.resize(f, f, 500, -1);
data.set(new FileInputStream(f), type);
Product product = Product.findById(product_id);
product.photo = data;
product.save();
}
source to share
Images modified by the Java standard libraries are of poor quality. I would use ImageMagic with Java libraries like im4java . ImageMagic must be installed on the server.
So, for example, resizing an image to a thumb with a white background might look like this:
private static void toThumb(File original) {
// create command
ConvertCmd cmd = new ConvertCmd();
// create the operation, add images and operators/options
IMOperation op = new IMOperation();
op.addImage(original.getPath());
op.thumbnail(THUMB_WIDTH, THUMB_WIDTH);
op.unsharp(0.1);
op.gravity("center");
op.background("white");
op.extent(THUMB_WIDTH, THUMB_WIDTH);
op.addImage(original.getPath());
try {
// execute the operation
cmd.run(op);
} catch (IOException ex) {
Logger.error("ImageMagic - IOException %s", ex);
} catch (InterruptedException ex) {
Logger.error("ImageMagic - InterruptedException %s", ex);
} catch (IM4JavaException ex) {
Logger.error("ImageMagic - IM4JavaException %s", ex);
}
}
Add im4java to your dependencies:
require:
- play ]1.2,)
- repositories.thirdparty -> im4java 1.1.0
repositories:
- im4java:
type: http
artifact: http://maven.cedarsoft.com/content/repositories/thirdparty/[module]/[module]/[revision]/[module]-[revision].[ext]
contains:
- repositories.thirdparty -> *
source to share
You can use http://imagemagick.org along with http://im4java.sourceforge.net/ to convert images . Use something like this, but with your custom parameters:
createThumb(from, to, "-thumbnail", "60x60", "-quality", "100", "-format", "jpg");
private void createThumb(File from, File to, String... args) throws ImageConvertException {
ConvertCmd cmd = new ConvertCmd();
IMOperation op = new IMOperation();
op.addImage(from.getAbsolutePath());
op.addRawArgs(args);
op.addImage(to.getAbsolutePath());
try {
cmd.run(op);
} catch (Exception e) {
throw new ImageConvertException(e);
}
}
source to share