How do you create a thumbnail image out of a JPEG in Java?

后端 未结 13 2290
日久生厌
日久生厌 2020-11-29 16:51

Can someone please help with some code for creating a thumbnail for a JPEG in Java.

I\'m new at this, so a step by step explanation would be appreciated.

相关标签:
13条回答
  • 2020-11-29 17:46

    Maybe the simplest approach would be:

    static public BufferedImage scaleImage(BufferedImage image, int max_width, int max_height) {
        int img_width = image.getWidth();
        int img_height = image.getHeight();
    
        float horizontal_ratio = 1;
        float vertical_ratio    = 1;
    
    
        if(img_height > max_height) {
            vertical_ratio = (float)max_height / (float)img_height;
        }
        if(img_width > max_width) {
            horizontal_ratio = (float)max_width / (float)img_width;
        }
    
        float scale_ratio = 1;
    
        if (vertical_ratio < horizontal_ratio) {
            scale_ratio = vertical_ratio;
        }
        else if (horizontal_ratio < vertical_ratio) {
            scale_ratio = horizontal_ratio;
        }
    
        int dest_width  = (int) (img_width * scale_ratio);
        int dest_height = (int) (img_height * scale_ratio);
    
        BufferedImage scaled = new BufferedImage(dest_width, dest_height, image.getType());
        Graphics graphics = scaled.getGraphics();
        graphics.drawImage(image, 0, 0, dest_width, dest_height, null);
        graphics.dispose();
    
        return scaled;
    
    }
    
    0 讨论(0)
提交回复
热议问题