javax.imageio包 图片嵌入

        //区分普通/avatar头像
        String type = "avatar";
        //目标文件(嵌入图片)
        String pressImg = "https://image.fprice.cn/boot-admin/api/common/view/static/icon_mini_logo.png";
        //主图片
        String targetImg = "C:\\Users\\Administrator\\Desktop\\img\\199ba2abb7a0f7af1c4bcd79bc4b0802.jpeg";
        int x = 66 ;
        int y = 766;
        //x轴偏移距离
        int xOffset = 0;
        //y轴偏移距离
        int yOffset = 40;
        //宽度
        int pressImgW = 124;
        //高度
        int pressImgH = 124;
        try {
            //目标文件
            File _file = new File(targetImg);
            Image src = ImageIO.read(_file);
            int width = src.getWidth(null);
            int height = src.getHeight(null);
            BufferedImage image = new BufferedImage(width, height,
                    BufferedImage.TYPE_INT_RGB);
            Graphics2D g = image.createGraphics();
            g.drawImage(src, 0, 0, width, height, null);

            //水印文件
            Image src_biao = null;
            if (pressImg.indexOf("http") > -1) {
                URL url = new URL(pressImg);
                src_biao = ImageIO.read(url);
            } else {
                File _filebiao = new File(pressImg);
                src_biao = ImageIO.read(_filebiao);
            }

            int width_biao = pressImgW > 0 ? pressImgW : src_biao.getWidth(null);
            int height_biao = pressImgH > 0 ? pressImgH : src_biao.getHeight(null);
            int xx = x > 0 ? x : (width - width_biao) / 2 - xOffset;
            int yy = y > 0 ? y : (height - height_biao) / 2 - yOffset;
            if (type.equals("avatar")) {
                g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                //留一个像素的空白区域,这个很重要,画圆的时候把这个覆盖
                int border = 1;
                //图片是一个圆型
                Ellipse2D.Double shape = new Ellipse2D.Double(xx, yy, width_biao - border * 2, height_biao - border * 2);
                //需要保留的区域
                g.setClip(shape);
            }
            g.drawImage(src_biao, xx, yy, width_biao, height_biao, null);
            //水印文件结束
            g.dispose();
//            FileOutputStream out = new FileOutputStream(targetImg);
//            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
//            encoder.encode(image);
//            out.close();
            String formatName = targetImg.substring(targetImg.lastIndexOf(".") + 1);
            //覆盖原图
            ImageIO.write(image, formatName, new File(targetImg));
        } catch (Exception e) {
            e.printStackTrace();
        }

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值