Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resize Blob image before saving in Play Framework

I am developing a web page using Java and Play Framework 1.2.4.

I have a simple form with a file input that allows the user to upload an image file. Sometimes, the image is too big and then it needs a lot of time to display the image, so I need to resize the image. How can I do it with play?

I know Images.resize(from, to, w, h) function, I have 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();
}
like image 541
Marta Rodriguez Avatar asked Nov 20 '25 10:11

Marta Rodriguez


2 Answers

Maybe you should define different destination file instead of writing over the original file:

File f = data.getFile();
File newFile = new File("Foo.jpg"); // create random unique filename here
Images.resize(f, newFile, 500, -1);
like image 139
Tommi Avatar answered Nov 21 '25 23:11

Tommi


Images resized with standard Java libraries have poor quality. I would use ImageMagic with Java libs like im4java. It is necessary to install ImageMagic on a server.

So for example resizing image to thumb with white background could 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 -> *
like image 22
Marek Sybilak Avatar answered Nov 21 '25 22:11

Marek Sybilak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!