ImageIO.read( ) always rotates my uploaded picture

后端 未结 2 1152
孤独总比滥情好
孤独总比滥情好 2021-02-07 10:36

I want to create a web application that allow users to upload their image to the server. When they click send, their image will be uploaded to the server (multipart). Before sa

2条回答
  •  甜味超标
    2021-02-07 11:38

    Quite interesting issue... you can try to fix it by introducing a check on the image width and height to be larger than 2448 and 3264 respectively and then just swap its width and height

    Use below piece of code:

    BufferedImage oldImage = ImageIO.read(file.getInputStream());
    
    if (oldImage.getWidth() > 2448 || oldImage.getHeight() > 3264) {
    
        BufferedImage newImage = new BufferedImage(oldImage.getWidth(),
                    oldImage.getHeight(), oldImage.getType());
    
        Graphics2D graphics = (Graphics2D) newImage.getGraphics();
    
        graphics.drawImage(oldImage, 0, 0, oldImage.getHeight(),
                    oldImage.getWidth(), null);
    
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
    
        ImageIO.write(newImage, "JPG", bos);
    }
    

提交回复
热议问题