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

时间:2025-03-12 09:47:01
public static void main(String[] args) { try { //是背景图 InputStream is = new FileInputStream("C:/Users/Desktop/"); //通过JPEG图象流创建JPEG数据流解码器 JPEGImageDecoder jpegDecoder = JPEGCodec.createJPEGDecoder(is); //解码当前JPEG数据流,返回BufferedImage对象 BufferedImage buffImg = jpegDecoder.decodeAsBufferedImage(); //得到画笔对象 Graphics g = buffImg.getGraphics(); //创建你要附加的图象。 //新的头像的路径 ImageIcon imgIcon = new ImageIcon("C:/Users/Desktop/"); //得到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:/"); 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(); } }