JAVA 压缩图片导致背景变黑

冰峰雪座
冰峰雪座 Apr 2, 2020 4:37:06 PM
0 479 0

上代码:

/**
     * 按照比例缩放
     *
     * @param sourceFile
     * @param targetFile
     */
    public void zoom(File sourceFile, File targetFile, int wh,int yh,boolean circular) {
        try {
            BufferedImage image = ImageIO.read(sourceFile);
            BufferedImage newImage = zoom(image, (int) Math.ceil(wh ), (int) Math.ceil(yh));
            //去除背景黑底
            newImage.getGraphics().fillRect( 0, 0 , wh, yh);
            newImage.getGraphics().drawImage(image.getScaledInstance(wh, yh,Image.SCALE_SMOOTH), 0, 0, null);
            String formatName = getImageFormatName(sourceFile);
            if (formatName == null || formatName.length() == 0) {
                return;
            }
            //设置图片变成圆形
            if(circular){
                newImage=convertCircular(newImage,wh);
            }
            ImageIO.write(newImage, formatName, targetFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }



/**
     * 传入的图像必须是正方形的 才会 圆形 如果是长方形的比例则会变成椭圆的
     *
     * 图片裁圆
     * @return
     * @throws IOException
     */
    public static BufferedImage convertCircular(BufferedImage bi1,int min) throws IOException {

      //BufferedImage bi1 = ImageIO.read(sourceFile);
        // 这种是黑色底的
       //BufferedImage bi2 = new BufferedImage(bi1.getWidth(), bi1.getHeight(), BufferedImage.TYPE_INT_RGB);

        // 透明底的图片
        BufferedImage bi2 = new BufferedImage(min, min, BufferedImage.TYPE_4BYTE_ABGR);
        Ellipse2D.Double shape = new Ellipse2D.Double(0, 0,min,min);
        Graphics2D g2 = bi2.createGraphics();
        g2.setClip(shape);
        // 使用 setRenderingHint 设置抗锯齿
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2.drawImage(bi1, 0, 0, null);
        // 设置颜色
        g2.setBackground(Color.green);
        g2.dispose();
        return bi2;
    }

 newImage.getGraphics().fillRect( 0, 0 , wh, yh);

  newImage.getGraphics().drawImage(image.getScaledInstance(wh, yh,Image.SCALE_SMOOTH), 0, 0, null);

这两行代码是为了背景去黑底起作用的



回帖