Java image resize, maintain aspect ratio

前端 未结 11 1474
盖世英雄少女心
盖世英雄少女心 2020-11-28 19:38

I have an image which I resize:

if((width != null) || (height != null))
{
    try{
        // scale image on disk
        BufferedImage originalImage = ImageI         


        
11条回答
  •  时光取名叫无心
    2020-11-28 19:56

    Here's a small piece of code that I wrote, it resizes the image to fit the container while keeping the image's original aspect ratio. It takes in as parameters the container's width, height and the image. You can modify it to fit your needs. It's simple and works fine for my applications.

    private Image scaleimage(int wid, int hei, BufferedImage img){
        Image im = img;
        double scale;
        double imw = img.getWidth();
        double imh = img.getHeight();
        if (wid > imw && hei > imh){
            im = img;
        }else if(wid/imw < hei/imh){
            scale = wid/imw;
            im = img.getScaledInstance((int) (scale*imw), (int) (scale*imh), Image.SCALE_SMOOTH);
        }else if (wid/imw > hei/imh){
            scale = hei/imh;
            im = img.getScaledInstance((int) (scale*imw), (int) (scale*imh), Image.SCALE_SMOOTH);
        }else if (wid/imw == hei/imh){
            scale = wid/imw;
            im = img.getScaledInstance((int) (scale*imw), (int) (scale*imh), Image.SCALE_SMOOTH);
        } 
        return im;
    }
    

提交回复
热议问题