栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

为不同大小的图片添加纯色背景

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

为不同大小的图片添加纯色背景

先看效果

 调用代码:

 File file = new File("需要加背景的图片的全路径");  //比如"D:\Download\test.png"
InputStream in = new FileInputStream(file);
BufferedImage bufferedImage = ImageUtil.reSquareAddBackground(in, 背景图宽, 背景图高, 背景颜色);
//比如 ImageUtil.reSquareAddBackground(in, 1024, 1024, Color.PINK(粉色)/Color.WHITE(白色))
File newFile = new File("生成的新图片的全路径");  //比如"D:\Download\test-pink.png"
ImageIO.write(bufferedImage, "生成图片格式/后缀", newFile);  //比如 "png"

处理前:

处理后:

白色背景不太明显,换个粉色的~

完整代码
    
    public static BufferedImage reSquareAddBackground(InputStream downloadImage, Integer backWidth, Integer backHeight, Color color) throws IOException {
        // 先创建一个纯色背景图
        BufferedImage biNew = new BufferedImage(backWidth, backHeight, BufferedImage.TYPE_INT_RGB);
        Graphics g = biNew.getGraphics();
        g.setColor(color);  //g.setColor(Color.white);
        g.fillRect(0, 0, backWidth, backHeight);   // 矩形填充
        g.dispose();

        BufferedImage bi = ImageIO.read(downloadImage);
        int width = bi.getWidth();
        int height = bi.getHeight();
        int stepH = 0; //上下间隙
        int stepW = 0; //左右间隙
        double ratioW = width * 1.0 / backWidth;
        double ratioH = height * 1.0 / backHeight;
        if (ratioH > ratioW) {
            //按高缩放
            height = backHeight;
            width = (int) (width / ratioH);
            stepW = (backWidth - width) / 2;
            //获取缩放后的Image对象
            bi = getZoomScaleBufferedImage(bi, width, height);
        } else {
            //按宽缩放
            //获取缩放后的长和宽
            width = backWidth;
            height = (int) (height / ratioW);
            stepH = (backHeight - height) / 2;
            //获取缩放后的Image对象
            bi = getZoomScaleBufferedImage(bi, width, height);
        }

        int minX = bi.getMinX();
        int minY = bi.getMinY();
        //遍历长和宽上的每个像素
        for (int i = minX; i < width; i++) {
            for (int j = minY; j < height; j++) {
                //得到指定像素(i,j)上的RGB值,
                int pixel = bi.getRGB(i, j);
                //判断改像素是否有值(也可以通过位运算分别求得RGB值再进行判断)
                if (pixel == -16777216) {
                    continue;
                }
                biNew.setRGB(i + stepW, j + stepH, pixel);
            }
        }
        System.out.println("完成^ ^");
        return biNew;
    }

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/306529.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号