簡體   English   中英

在Play Framework中保存之前調整Blob圖像的大小

[英]Resize Blob image before saving in Play Framework

我正在使用Java和Play Framework 1.2.4開發一個網頁。

我有一個帶文件輸入的簡單表單,允許用戶上傳圖像文件。 有時,圖像太大,然后需要很多時間來顯示圖像,所以我需要調整圖像的大小。 我怎么能玩這個游戲?

我知道Images.resize(from,to,w,h)函數,我試過使用它但它沒有按照我的預期工作,這是我的代碼:

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();
}

也許您應該定義不同的目標文件,而不是寫入原始文件:

File f = data.getFile();
File newFile = new File("Foo.jpg"); // create random unique filename here
Images.resize(f, newFile, 500, -1);

使用標准Java庫調整大小的圖像質量很差。 我會將ImageMagicimljava等Java庫一起使用 必須在服務器上安裝ImageMagic。

因此,例如將圖像調整為具有白色背景的拇指可能如下所示:

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);
        }

    }

將im4java添加到您的依賴項:

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 -> *

對於圖像轉換,您可以將http://imagemagick.orghttp://im4java.sourceforge.net/庫一起使用。 使用這樣的東西,但使用你的自定義參數:

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);
            }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM