java 使用Thumbnails压缩图片后 表面红色 解决方案

        
            net.coobird
            thumbnailator
            0.4.8
        
public static boolean saveFileByMultipartFile(String directoryPath, String fileName, MultipartFile multipartFile) {
        try {
            if (StringUtils.isEmpty(directoryPath)) {
                throw new Exception("文件夹不能为空");
            }
            File tmp = new File(directoryPath);
            if (!tmp.exists()) {
                tmp.mkdirs();
            }
            String filePath = directoryPath + fileName;
            multipartFile.transferTo(new File(filePath));

            String fileType = multipartFile.getContentType();
            if (!StringUtils.isEmpty(fileType) && fileType.contains("image")) {
//                File file = new File(filePath);
//                log.error("压缩前图片大小:Byte:" + file.length());

                // 压缩代码
                //防止图片变红
                Image src = Toolkit.getDefaultToolkit().getImage(filePath);
                BufferedImage image = toBufferedImage(src);
                Thumbnails.of(image).scale(1f).toFile(filePath);

//                log.error("压缩前图片大小:Byte:" + file.length());
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public static BufferedImage toBufferedImage(Image image) {
        if (image instanceof BufferedImage) {
            return (BufferedImage) image;
        }
        // This code ensures that all the pixels in the image are loaded
        image = new ImageIcon(image).getImage();
        BufferedImage bimage = null;
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        try {
            int transparency = Transparency.OPAQUE;
            GraphicsDevice gs = ge.getDefaultScreenDevice();
            GraphicsConfiguration gc = gs.getDefaultConfiguration();
            bimage = gc.createCompatibleImage(image.getWidth(null), image.getHeight(null), transparency);
        } catch (HeadlessException e) {
            // The system does not have a screen
        }
        if (bimage == null) {
            // Create a buffered image using the default color model
            int type = BufferedImage.TYPE_INT_RGB;
            bimage = new BufferedImage(image.getWidth(null), image.getHeight(null), type);
        }
        // Copy image to buffered image
        Graphics g = bimage.createGraphics();
        // Paint the image onto the buffered image
        g.drawImage(image, 0, 0, null);
        g.dispose();
        return bimage;
    }

我测试过 可以解决

你可能感兴趣的:(java 使用Thumbnails压缩图片后 表面红色 解决方案)