OOLY BLOG

柳絮纷飞
hey!

Java实现多图片和文字编辑合成一张图片

由于业务中需要将多张图片和自定义的文字用程序生成一张海报,所以今天写了一个公共的方法来处理多张图片拼接海报,相关文字贴入到图片中的问题!

1.准备素材--两张图片,一张背景图,一张需要覆盖到某个位置的图

public static void main(String[] args) {
        String backgroundPath = "D:\\workspace\\moban\\chezhuli\\src\\main\\resources\\static\\img\\b3.png";
  String qrCodePath = "D:\\workspace\\moban\\chezhuli\\src\\main\\resources\\static\\img\\qt.png";
  String message01 ="扫描下方二维码,欢迎大家添加我的淘宝返利机器人";
  String message02 = "居家必备,省钱购物专属小秘书!";
  String outPutPath="D:\\files\\end.png";
  overlapImage(backgroundPath,qrCodePath,message01,message02,outPutPath);

  }

    public static String overlapImage(String backgroundPath,String qrCodePath,String message01,String message02,String outPutPath){
        try {
            //设置图片大小
  BufferedImage background = resizeImage(320,352, ImageIO.read(new File(backgroundPath)));
  BufferedImage qrCode = resizeImage(144,144,ImageIO.read(new File(qrCodePath)));
  //在背景图片中添加入需要写入的信息,例如:扫描下方二维码,欢迎大家添加我的淘宝返利机器人,居家必备,省钱购物专属小秘书!
  Graphics2D g = background.createGraphics();
  background = g.getDeviceConfiguration().createCompatibleImage(320, 352, Transparency.TRANSLUCENT);
  g.setColor(Color.white);
  //String message = "扫描下方二维码,欢迎大家添加我的淘宝返利机器人,居家必备,省钱购物专属小秘书!";
//            g.setFont(new Font("微软雅黑",Font.BOLD,20));
//            g.drawString(message01,530 ,190);
//            g.drawString(message02,530 ,220);
 //在背景图片上添加二维码图片

  g = background.createGraphics();
  g.drawImage(ImageIO.read(new File(backgroundPath)), 0, 0, null);

  g.drawImage(qrCode, 90, 106, qrCode.getWidth(), qrCode.getHeight(), null);

  g.dispose();
  ImageIO.write(background, "png", new File(outPutPath));
  }catch (Exception e){
            e.printStackTrace();
  }
        return null;
  }

    public static BufferedImage resizeImage(int x, int y, BufferedImage bfi){
        BufferedImage bufferedImage = new BufferedImage(x, y, BufferedImage.TYPE_INT_RGB);
  bufferedImage.getGraphics().drawImage(
                bfi.getScaledInstance(x, y, Image.SCALE_SMOOTH), 0, 0, null);
 return bufferedImage;
  }
转载文章请注明出处 | 当前页面:OOLY BLOG » Java实现多图片和文字编辑合成一张图片

评论

captcha
请输入验证码