java 在图片上添加文字或图片

项目中碰到一个问题,需要生成带头像和分数的一个整数,分数和头像都是根据不同的用户来生成的。简单说下实现的思路,头像的替换可以直接用新的头像覆盖到原图,用户的分数背景都用一样的,然后写上去。
以下是代码:

public static void main(String[] args) {
        try {
            //A.jpg是背景图
            InputStream is = new FileInputStream("C:/Users/Desktop/A.jpg");
            //通过JPEG图象流创建JPEG数据流解码器
            JPEGImageDecoder jpegDecoder = JPEGCodec.createJPEGDecoder(is);
            //解码当前JPEG数据流,返回BufferedImage对象
            BufferedImage buffImg = jpegDecoder.decodeAsBufferedImage();
            //得到画笔对象
            Graphics g = buffImg.getGraphics();
            //创建你要附加的图象。
            //新的头像的路径
            ImageIcon imgIcon = new ImageIcon("C:/Users/Desktop/head.jpg");
            //得到Image对象。
            Image img = imgIcon.getImage();
            //将小图片绘到大图片上。
            //5,300 .表示你的小图片在大图片上的位置。
            g.drawImage(img, 400, 15, null);
            //设置颜色。
            g.setColor(Color.BLACK);
            //最后一个参数用来设置字体的大小
            Font f = new Font("宋体", Font.PLAIN, 50);
            Color mycolor = Color.BLACK;//new Color(0, 0, 255);
            g.setColor(mycolor);
            g.setFont(f);
            //10,20 表示这段文字在图片上的位置(x,y) .第一个是你设置的内容。
            g.drawString("你好", 100, 135);
            g.dispose();
            //最后一个参数用来设置字体的大小
            Font scoreFont = new Font("宋体", Font.PLAIN, 25);
            Color scoreColor = Color.BLACK;//new Color(0, 0, 255);
            g.setColor(scoreColor);
            g.setFont(scoreFont);
            //10,20 表示这段文字在图片上的位置(x,y) .第一个是你设置的内容。
            g.drawString("80", 200, 135);
            g.dispose();
            OutputStream os;
            //os = new FileOutputStream("d:/union.jpg");
            String shareFileName = "C:/Users/Desktop/" + System.currentTimeMillis() + ".jpg";
            os = new FileOutputStream(shareFileName);
            //创键编码器,用于编码内存中的图象数据。
            JPEGImageEncoder en = JPEGCodec.createJPEGEncoder(os);
            en.encode(buffImg);
            is.close();
            os.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (ImageFormatException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

代码比较简单,在main方法中就可以做测试,记录一下


版权声明:本文为weixin_43470118原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。