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

后端 未结 13 2331
日久生厌
日久生厌 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:36

    Simple way to create a thumbnail without stretching or a library. Works with transparency in pngs, too.

    public File createThumbnail(String imageUrl, String targetPath) {
        final int imageSize = 100;
        File thumbnail = new File(targetPath);
    
        try {
            thumbnail.getParentFile().mkdirs();
            thumbnail.createNewFile();
            BufferedImage sourceImage = ImageIO.read(new File(imageUrl));
            float width = sourceImage.getWidth();
            float height = sourceImage.getHeight();
    
            BufferedImage img2;
            if (width > height) {
                float scaledWidth = (width / height) * (float) imageSize;
                float scaledHeight = imageSize;
    
                BufferedImage img = new BufferedImage((int) scaledWidth, (int) scaledHeight, sourceImage.getType());
                Image scaledImage = sourceImage.getScaledInstance((int) scaledWidth, (int) scaledHeight, Image.SCALE_SMOOTH);
                img.createGraphics().drawImage(scaledImage, 0, 0, null);
    
                int offset = (int) ((scaledWidth - scaledHeight) / 2f);
                img2 = img.getSubimage(offset, 0, imageSize, imageSize);
            }
            else if (width < height) {
                float scaledWidth = imageSize;
                float scaledHeight = (height / width) * (float) imageSize;
    
                BufferedImage img = new BufferedImage((int) scaledWidth, (int) scaledHeight, sourceImage.getType());
                Image scaledImage = sourceImage.getScaledInstance((int) scaledWidth, (int) scaledHeight, Image.SCALE_SMOOTH);
                img.createGraphics().drawImage(scaledImage, 0, 0, null);
    
                int offset = (int) ((scaledHeight - scaledWidth) / 2f);
                img2 = img.getSubimage(0, offset, imageSize, imageSize);
            }
            else {
                img2 = new BufferedImage(imageSize, imageSize, sourceImage.getType());
                Image scaledImage = sourceImage.getScaledInstance(imageSize, imageSize, Image.SCALE_SMOOTH);
                img2.createGraphics().drawImage(scaledImage, 0, 0, null);
            }
            ImageIO.write(img2, "png", thumbnail);
        }
        catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return thumbnail;
    }
    

提交回复
热议问题