java 图片的处理

1.将透明图主体居中


    /**
     * 将透明图主体居中
     * @param file2
     */
    private void imageInit(File file2) {
        try {
            BufferedImage bufferedImage = ImageIO.read(file2);
            int xMin = bufferedImage.getWidth();
            int xMax = 0;
            int yMin = bufferedImage.getHeight();
            int yMax = 0;
            List<Coord> coordList = new ArrayList<>();
            for (int i = 0; i < xMin; i++) {
                for (int j = 0; j < yMin; j++) {
                    //透明底判断
                    if (bufferedImage.getRGB(i, j) >> 24 != 0) {
                        Coord coord = new Coord(i, j);
                        coordList.add(coord);
                    }
                }
            }
            //取出最大和最小的xy(差值就是新图片的宽高)
            for (Coord coord : coordList) {
                int x = coord.x;
                int y = coord.y;
                if (x < xMin)
                    xMin = x;
                if (x > xMax)
                    xMax = x;
                if (y < yMin)
                    yMin = y;
                if (y > yMax)
                    yMax = y;
            }
            //设置透明底
            selectedImage = new BufferedImage(xMax - xMin, yMax - yMin, BufferedImage.TYPE_INT_RGB);
            Graphics2D graphics = selectedImage.createGraphics();
            selectedImage = graphics.getDeviceConfiguration().createCompatibleImage(xMax - xMin, yMax - yMin, Transparency.TRANSLUCENT);
            graphics.dispose();
            //从原图中将像素点拿出来
            for (int i = 0; i < xMax - xMin; i++) {
                for (int j = 0; j < yMax - yMin; j++) {
                    selectedImage.setRGB(i,j,bufferedImage.getRGB(i+xMin,j+yMin));
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

处理前:
在这里插入图片描述

处理后:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值