Java ImageIO 图片背景变成透明

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Transparency;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;

public class TestMainPNG{
    
    public static void main(String[] args) throws Exception{
        BufferedImage image = ImageIO.read(new File("d:/images/origion/1/1.jpg"));
        // 高度和宽度
        int height = image.getHeight();
        int width = image.getWidth();
        int minX = 0, maxX = 0, minY = 0, maxY = 0;
        int trueW = 0, trueH = 0;
        
        // 生产背景透明和内容透明的图片
        ImageIcon imageIcon = new ImageIcon(image);
        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR);
        Graphics2D g2D = (Graphics2D) bufferedImage.getGraphics(); // 获取画笔
        g2D.drawImage(imageIcon.getImage(), 0, 0, null); // 绘制Image的图片

        int alpha = 0; // 图片透明度
        // 外层遍历是Y轴的像素
        for (int y = bufferedImage.getMinY(); y < bufferedImage.getHeight(); y++) {
            // 内层遍历是X轴的像素
            for (int x = bufferedImage.getMinX(); x < bufferedImage.getWidth(); x++) {
                int rgb = bufferedImage.getRGB(x, y);
                // 对当前颜色判断是否在指定区间内
                if (colorInRange(rgb)){
                    alpha = 0;
                    
                    minX = minX <= x ? minX : x;
                    minY = minY <= y ? minY : y;
                    maxX = maxX >= x ? maxX : x;
                    maxY = maxY >= y ? maxY : y;
                    
                }else{
                    // 设置为不透明
                    alpha = 255;
                }
                // #AARRGGBB 最前两位为透明度
                rgb = (alpha << 24) | (rgb & 0x00ffffff);
                bufferedImage.setRGB(x, y, rgb);
            }
        }
        
      //输出真实的宽高,无边框的
        trueW = maxX - minX + 1;
        trueH = maxY - minY + 1;

        //输出折算后的宽高
        float[] calImgWH = {0, 0};
        calImgWH = calWH(trueW, trueH);
        float calW = calImgWH[0]; //折算的宽
        float calH = calImgWH[1]; //折算的高
        Color color = new Color(0xFF,0xFF,0xFF,0);
        int rgb = color.getRGB();
        //将图像区域的像素,写到bi2里面
        BufferedImage bi2 = new BufferedImage(trueW, trueH, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = bi2.createGraphics();
        bi2 = g2d.getDeviceConfiguration().createCompatibleImage(trueW, trueH, Transparency.TRANSLUCENT);

        for (int i = 0; i < trueW; i++) {
            for (int j = 0; j < trueH; j++) {
                bi2.setRGB(i, j, bufferedImage.getRGB(minX, minY++));
            }
            minY -= trueH;
            minX++;
        }

        BufferedImage bi3 = changeImg(bi2, (int) calW, (int) calH);
        
        // 绘制设置了RGB的新图片
        g2D.drawImage(bufferedImage, 0, 0, null);

        // 生成图片为PNG
        ImageIO.write(bufferedImage, "png", new File("d:/images/result/1/2.jpg"));
        System.out.println("完成画图");
    }
    
    // 判断是背景还是内容
    public static boolean colorInRange(int color) {
        int red = (color & 0xff0000) >> 16;// 获取color(RGB)中R位
        int green = (color & 0x00ff00) >> 8;// 获取color(RGB)中G位
        int blue = (color & 0x0000ff);// 获取color(RGB)中B位
        // 通过RGB三分量来判断当前颜色是否在指定的颜色区间内
        if (red >= color_range && green >= color_range && blue >= color_range){
            return true;
        };
        return false;
    }
    
  //根据指定的宽高缩放图片
    private static BufferedImage changeImg(BufferedImage bi, int w, int h) throws IOException {

        int bgWidth = 400;
        int bgHeight = 200;

        final int bgW = bgWidth;
        final int bgH = bgHeight;
        int x = (bgW - w) / 2;
        int y = (bgH - h) / 2;
        Color color = new Color(0xFF,0xFF,0xFF,0);
        int rgb = color.getRGB();
        BufferedImage tag = new BufferedImage(bgW, bgH, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = tag.createGraphics();
        tag = g2d.getDeviceConfiguration().createCompatibleImage(bgWidth, bgHeight, Transparency.TRANSLUCENT);

        tag.getGraphics().drawImage(bi, x, y, w, h, null);//按照左上角的坐标x/y,来输出宽高w/h的图片
        return tag;
    }

    //折算图片的宽高
    private static float[] calWH(float w, float h) {

        int bgWidth = 400;
        int bgHeight = 200;

        float[] imgWH = {0, 0};
        final float stardandW = bgWidth;
        final float stardandH = bgHeight;
        float x = 0;

        x = stardandW / w;
        if (w * x <= stardandW && h * x <= stardandH) {
            imgWH[0] = w * x;
            imgWH[1] = h * x;
        }

        x = stardandH / h;
        if (w * x <= stardandW && h * x <= stardandH) {
            imgWH[0] = w * x;
            imgWH[1] = h * x;
        }

        return imgWH;
    }
    
    //色差范围0~255
    public static int color_range = 210;
    
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java ImageIO提供了压缩图片的功能,可以将高分辨率的图片压缩成低分辨率的图片以减少图片的大小。以下是一个示例代码,演示如何使用ImageIO压缩图片: ```java import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; public class ImageCompressor { public static void main(String[] args) throws IOException { File inputFile = new File("input.jpg"); File outputFile = new File("output.jpg"); BufferedImage inputImage = ImageIO.read(inputFile); // 压缩比例 float compressionRatio = 0.5f; // 计算压缩后的尺寸 int newWidth = (int) (inputImage.getWidth() * compressionRatio); int newHeight = (int) (inputImage.getHeight() * compressionRatio); // 创建压缩后的图片 BufferedImage outputImage = new BufferedImage(newWidth, newHeight, inputImage.getType()); // 绘制压缩后的图片 outputImage.createGraphics().drawImage( inputImage.getScaledInstance(newWidth, newHeight, java.awt.Image.SCALE_SMOOTH), 0, 0, null ); // 写入文件 ImageIO.write(outputImage, "jpg", outputFile); } } ``` 在上面的代码中,我们首先读取一个输入图片文件,并指定一个输出图片文件。然后我们计算压缩比例,根据压缩比例计算出新的图片尺寸。接着我们创建一个新的BufferedImage对象,指定新的尺寸和图片类型。最后我们使用`createGraphics()`方法获取到一个Graphics2D对象,并使用`drawImage()`方法将原始图片缩放到新的尺寸上,并绘制到新的BufferedImage对象上。最后我们使用`ImageIO.write()`方法将新的BufferedImage对象写入到输出文件中。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值