What is the best way to scale images in Java?

前端 未结 7 1073
时光取名叫无心
时光取名叫无心 2020-12-30 06:14

I have a web application written in Java (Spring, Hibernate/JPA, Struts2) where users can upload images and store them in the file system. I would like to scale those images

7条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-30 06:48

    I know this is a very old question, but I got my own solution for this using standard Java API

    import java.awt.*;
    import java.awt.event.*;
    import javax.imageio.*
    import java.awt.image.*;
    
    BufferedImage im, bi, bi2;
    Graphics2D gfx;
    int imWidth, imHeight, dstWidth, dstHeight;
    int DESIRED_WIDTH = 500, DESIRED_HEIGHT = 500;
    
    im = ImageIO.read(new File(filePath));
    imWidth = im.getWidth(null);
    imHeight = im.getHeight(null);
    
    dstWidth = DESIRED_WIDTH;
    dstHeight = (dstWidth * imHeight) / imWidth;
    
    bi = new BufferedImage(dstWidth, dstHeight, im.getType());
    
    gfx = bi.createGraphics();
    gfx.drawImage(im, 0, 0, dstWidth, dstHeight, 0, 0, imWidth, imHeight, null);
    
    bi2 = new BufferedImage(DESIRED_WIDTH, DESIRED_HEIGHT, im.getType());
    gfx = bi2.createGraphics();
    
    gfx.drawImage(bi, 0, 0, DESIRED_WIDTH, DESIRED_HEIGHT, null);
    
    ImageIO.write(bi2, "jpg", new File(filePath));
    

    I am sure it can be improved and adapted.

提交回复
热议问题