java怎么生成带用户微信头像的图片,并把这张图片发送给用户。

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java怎么生成带用户微信头像的图片,并把这张图片发送给用户。相关的知识,希望对你有一定的参考价值。

类似于这样的。

1、下载生成二维码所需要的jar包qrcode.jar;2、直接上生成二维码的java代码 //需要导入的包import java.awt.Color;import java.awt.Graphics2D;import java.awt.Image;import java.awt.image.BufferedImage;import java.io.File;import javax.imageio.ImageIO;import com.swetake.util.Qrcode; /** * 生成二维码(QRCode)图片 * @param content 二维码图片的内容 * @param imgPath 生成二维码图片完整的路径 * @param ccbpath 二维码图片中间的logo路径 */ public static int createQRCode(String content, String imgPath,String ccbPath) try Qrcode qrcodeHandler = new Qrcode(); qrcodeHandler.setQrcodeErrorCorrect('M'); qrcodeHandler.setQrcodeEncodeMode('B'); qrcodeHandler.setQrcodeVersion(7); // System.out.println(content); byte[] contentBytes = content.getBytes("gb2312"); //构造一个BufferedImage对象 设置宽、高 BufferedImage bufImg = new BufferedImage(140, 140, BufferedImage.TYPE_INT_RGB); Graphics2D gs = bufImg.createGraphics(); gs.setBackground(Color.WHITE); gs.clearRect(0, 0, 140, 140); // 设定图像颜色 > BLACK gs.setColor(Color.BLACK); // 设置偏移量 不设置可能导致解析出错 int pixoff = 2; // 输出内容 > 二维码 if (contentBytes.length > 0 && contentBytes.length < 120) boolean[][] codeOut = qrcodeHandler.calQrcode(contentBytes); for (int i = 0; i < codeOut.length; i++) for (int j = 0; j < codeOut.length; j++) if (codeOut[j][i]) gs.fillRect(j * 3 + pixoff, i * 3 + pixoff, 3, 3); else System.err.println("QRCode content bytes length = " + contentBytes.length + " not in [ 0,120 ]. "); return -1; Image img = ImageIO.read(new File(ccbPath));//实例化一个Image对象。 gs.drawImage(img, 55, 55, 30, 30, null); gs.dispose(); bufImg.flush(); // 生成二维码QRCode图片 File imgFile = new File(imgPath); ImageIO.write(bufImg, "png", imgFile); catch (Exception e) e.printStackTrace(); return -100; return 0;

来自网友 孤独青鸟的博客
参考技术A 如果只是说图片怎么来的,只需要通过 awt 画就行,选张背景图,在背景图的基础上往里画变量 参考技术B

这个是要一个图片中嵌套另外一张图片

你可以试试下面这段代码

import java.awt.Color;  
import java.awt.Font;  
import java.awt.Graphics2D;  
import java.awt.image.BufferedImage;  
import java.io.File;  
import java.io.IOException;  
import java.net.URL;  
  
import javax.imageio.ImageIO;  
  
/** 
 * 把两张图片合并 
 * @author lizhiyong  
 * @version $Id: Pic.java, v 0.1 
        2015-6-3 下午3:21:23 1111 Exp $ 
 */  
public class Pic   
    private Font       font     = new Font("宋体", Font.PLAIN, 12); // 添加字体的属性设置    
  
    private Graphics2D g        = null;  
  
    private int        fontsize = 0;  
  
    private int        x        = 0;  
  
    private int        y        = 0;  
  
    /**  
     * 导入本地图片到缓冲区  
     */  
    public BufferedImage loadImageLocal(String imgName)   
        try   
            return ImageIO.read(new File(imgName));  
         catch (IOException e)   
            System.out.println(e.getMessage());  
          
        return null;  
      
  
    /**  
     * 导入网络图片到缓冲区  
     */  
    public BufferedImage loadImageUrl(String imgName)   
        try   
            URL url = new URL(imgName);  
            return ImageIO.read(url);  
         catch (IOException e)   
            System.out.println(e.getMessage());  
          
        return null;  
      
  
    /**  
     * 生成新图片到本地  
     */  
    public void writeImageLocal(String newImage, BufferedImage img)   
        if (newImage != null && img != null)   
            try   
                File outputfile = new File(newImage);  
                ImageIO.write(img, "jpg", outputfile);  
             catch (IOException e)   
                System.out.println(e.getMessage());  
              
          
      
  
    /**  
     * 设定文字的字体等  
     */  
    public void setFont(String fontStyle, int fontSize)   
        this.fontsize = fontSize;  
        this.font = new Font(fontStyle, Font.PLAIN, fontSize);  
      
  
    /**  
     * 修改图片,返回修改后的图片缓冲区(只输出一行文本)  
     */  
    public BufferedImage modifyImage(BufferedImage img, Object content, int x, int y)   
  
        try   
            int w = img.getWidth();  
            int h = img.getHeight();  
            g = img.createGraphics();  
            g.setBackground(Color.WHITE);  
            g.setColor(Color.orange);//设置字体颜色    
            if (this.font != null)  
                g.setFont(this.font);  
            // 验证输出位置的纵坐标和横坐标    
            if (x >= h || y >= w)   
                this.x = h - this.fontsize + 2;  
                this.y = w;  
             else   
                this.x = x;  
                this.y = y;  
              
            if (content != null)   
                g.drawString(content.toString(), this.x, this.y);  
              
            g.dispose();  
         catch (Exception e)   
            System.out.println(e.getMessage());  
          
  
        return img;  
      
  
    /**  
     * 修改图片,返回修改后的图片缓冲区(输出多个文本段) xory:true表示将内容在一行中输出;false表示将内容多行输出  
     */  
    public BufferedImage modifyImage(BufferedImage img, Object[] contentArr, int x, int y,  
                                     boolean xory)   
        try   
            int w = img.getWidth();  
            int h = img.getHeight();  
            g = img.createGraphics();  
            g.setBackground(Color.WHITE);  
            g.setColor(Color.RED);  
            if (this.font != null)  
                g.setFont(this.font);  
            // 验证输出位置的纵坐标和横坐标    
            if (x >= h || y >= w)   
                this.x = h - this.fontsize + 2;  
                this.y = w;  
             else   
                this.x = x;  
                this.y = y;  
              
            if (contentArr != null)   
                int arrlen = contentArr.length;  
                if (xory)   
                    for (int i = 0; i < arrlen; i++)   
                        g.drawString(contentArr[i].toString(), this.x, this.y);  
                        this.x += contentArr[i].toString().length() * this.fontsize / 2 + 5;// 重新计算文本输出位置    
                      
                 else   
                    for (int i = 0; i < arrlen; i++)   
                        g.drawString(contentArr[i].toString(), this.x, this.y);  
                        this.y += this.fontsize + 2;// 重新计算文本输出位置    
                      
                  
              
            g.dispose();  
         catch (Exception e)   
            System.out.println(e.getMessage());  
          
  
        return img;  
      
  
    /**  
     * 修改图片,返回修改后的图片缓冲区(只输出一行文本)  
     *   
     * 时间:2007-10-8  
     *   
     * @param img  
     * @return  
     */  
    public BufferedImage modifyImageYe(BufferedImage img)   
  
        try   
            int w = img.getWidth();  
            int h = img.getHeight();  
            g = img.createGraphics();  
            g.setBackground(Color.WHITE);  
            g.setColor(Color.blue);//设置字体颜色    
            if (this.font != null)  
                g.setFont(this.font);  
            g.drawString("www.hi.baidu.com?xia_mingjian", w - 85, h - 5);  
            g.dispose();  
         catch (Exception e)   
            System.out.println(e.getMessage());  
          
  
        return img;  
      
  
    public BufferedImage modifyImagetogeter(BufferedImage b, BufferedImage d)   
  
        try   
            int w = b.getWidth();  
            int h = b.getHeight();  
  
            g = d.createGraphics();  
            g.drawImage(b, 100, 20, w, h, null);  
            g.dispose();  
         catch (Exception e)   
            System.out.println(e.getMessage());  
          
  
        return d;  
      
  
    public static void main(String[] args)   
  
        Pic tt = new Pic();  
  
        BufferedImage d = tt.loadImageLocal("\\\\ploanshare\\\\2\\\\11.jpg");  
        BufferedImage b = tt.loadImageLocal("\\\\ploanshare\\\\2\\\\22.png");    
        //往图片上写文件    
        //tt.writeImageLocal("E:\\\\ploanshare\\\\2\\\\22.jpg", tt.modifyImage(d, "000000", 90, 90));  
  
        tt.writeImageLocal("\\\\ploanshare\\\\2\\\\cc.jpg", tt.modifyImagetogeter(b, d));    
        //将多张图片合在一起    
        System.out.println("success");  
      

java 邀请卡生成工具,微信嵌入头像(圆角),图片,文字

public class InvitationCardUtil {

    private static final int QR_X = 240;
    private static final int QR_Y = 50;

    private static final int TEXT_X = 530;
    private static final int TEXT_Y = 1040;

    private static final int HEAD_X = 550;
    private static final int HEAD_Y = 985;

    private static final int COURSE_TEXT_X = 460;
    private static final int COURSE_TEXT_Y = 900;

    private static final int COURSE_HEAD_X = 330;
    private static final int COURSE_HEAD_Y = 950;


    private static final int COURSE_QR_X = 240;
    private static final int COURSE_QR_Y = 240;


    private static final int COURSE_X = 85;//越大越靠近left
    private static final int COURSE_Y = 280; //越大越靠近top

    private static final String FILE_EXT = "PNG";


    /**
     * @param cardType     邀请卡模板枚举
     * @param qrUrl        二维码url(微信)
     * @param nickname     微信昵称
     * @param headImgUrl   微信头像url(微信)
     * @param courseImgUrl 课程图片Url(oss)
     * @return 生成好的模板文件Url(oss)
     * @throws IOException
     */
    public static String createInvitationCard(InvitationCardType cardType, String qrUrl, String nickname, String headImgUrl, String courseImgUrl) throws IOException {

        if (null == cardType || !StringUtils.isNoneBlank(qrUrl, nickname, headImgUrl)) {
            return null;
        }

        if (InvitationCardType.COURSE == cardType && StringUtils.isBlank(courseImgUrl)) {
            return null;
        }

        //生成后的文件名
        String fileName = UUID.randomUUID().toString();
        //读取模板文件
        Image src = ImageIO.read(cardType.getCard());
        int width = src.getWidth(null);
        int height = src.getHeight(null);
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics g = image.createGraphics();
        g.drawImage(src, 0, 0, width, height, null);

        // 嵌入二维码
        Image read = handleQR(qrUrl);
        int readWidth = read.getWidth(null);
        int readHeight = read.getHeight(null);
        g.drawImage(read, width - readWidth - (InvitationCardType.COURSE == cardType ? COURSE_QR_X : QR_X), height - readHeight - (InvitationCardType.COURSE == cardType ? COURSE_QR_Y : QR_Y), readWidth, readHeight, null);

        // 嵌入头像
        Image headRead = handleHead(headImgUrl);
        int headReadWidth = headRead.getWidth(null);
        int headReadHeight = headRead.getHeight(null);
        g.drawImage(headRead, width - headReadWidth - (InvitationCardType.COURSE == cardType ? COURSE_HEAD_X : HEAD_X), height - headReadHeight - (InvitationCardType.COURSE == cardType ? COURSE_HEAD_Y : HEAD_Y), headReadWidth, headReadHeight, null);

        if (InvitationCardType.COURSE == cardType) {
            // 嵌入课程图片
            Image courseRead = handleCourse(courseImgUrl);
            int courseReadWidth = courseRead.getWidth(null);
            int courseReadHeight = courseRead.getHeight(null);
            g.drawImage(courseRead, width - courseReadWidth - COURSE_X, height - courseReadHeight - COURSE_Y, courseReadWidth, courseReadHeight, null);
        }

        // 昵称
        g.setColor((InvitationCardType.COURSE == cardType ? Color.BLACK : Color.WHITE));
        g.setFont(new Font("PingFangSC-Medium", Font.BOLD, 25));
        g.drawString(nickname, width - (InvitationCardType.COURSE == cardType ? COURSE_TEXT_X : TEXT_X), height - 25 / 2 - (InvitationCardType.COURSE == cardType ? COURSE_TEXT_Y : TEXT_Y));
        g.dispose();

        String key = "invite-cd/" + fileName + "." + FILE_EXT;
        return AliOSSUtil.writeImage(key, image);
    }

    /**
     * 处理头像
     *
     * @param headImgUrl
     * @return
     */
    private static Image handleHead(String headImgUrl) throws IOException {
        return getCircularImage(urlToImage(headImgUrl), 100);
    }


    /**
     * 处理二维码
     *
     * @param qrUrl
     * @return
     */
    private static Image handleQR(String qrUrl) throws IOException {
        return getResizeImage(urlToImage(qrUrl), 250);
    }

    /**
     * 处理课程图片
     *
     * @param qrUrl
     * @return
     */
    private static Image handleCourse(String qrUrl) throws IOException {
        return getResizeImage(urlToImage(qrUrl), 233);
    }

    /**
     * 圆形图片
     *
     * @param source
     * @param size
     * @return
     */
    private static Image getCircularImage(BufferedImage source, int size) {
        BufferedImage circularImg = new BufferedImage(size, size, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2 = circularImg.createGraphics();
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2.setColor(Color.WHITE);
        g2.fill(new RoundRectangle2D.Float(0, 0, size, size, 360, 360));
        g2.setComposite(AlphaComposite.SrcAtop);
        g2.drawImage(source, 0, 0, size, size, null);
        g2.dispose();
        return circularImg;
    }

    /**
     * 等比压缩图片
     *
     * @param source
     * @param size
     * @return
     */
    private static Image getResizeImage(BufferedImage source, int size) {
        int type = source.getType();
        BufferedImage target;
        double sx = (double) size / source.getWidth();
        double sy = (double) size / source.getHeight();
        // 这里想实现在targetW,targetH范围内实现等比缩放。如果不需要等比缩放
        // 则将下面的if else语句注释即可
        if (sx < sy) {
            sx = sy;
            size = (int) (sx * source.getWidth());
        } else {
            sy = sx;
            size = (int) (sy * source.getHeight());
        }
        if (type == BufferedImage.TYPE_CUSTOM) { // handmade
            ColorModel cm = source.getColorModel();
            WritableRaster raster = cm.createCompatibleWritableRaster(size,
                    size);
            boolean alphaPremultiplied = cm.isAlphaPremultiplied();
            target = new BufferedImage(cm, raster, alphaPremultiplied, null);
        } else {
            target = new BufferedImage(size, size, type);
        }
        Graphics2D g = target.createGraphics();
        g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                RenderingHints.VALUE_INTERPOLATION_BICUBIC);
        g.drawRenderedImage(source, AffineTransform.getScaleInstance(sx, sy));
        g.dispose();
        return target;
    }

    /**
     * url -> Image
     *
     * @param urlStr
     * @return
     * @throws IOException
     */
    private static BufferedImage urlToImage(String urlStr) throws IOException {
        URL url = new URL(urlStr);
        URLConnection con = url.openConnection();
        //超时
        con.setConnectTimeout(5000);

        //缓存
        con.setUseCaches(true);
        con.setDefaultUseCaches(true);
        InputStream is = con.getInputStream();

        //先读入内存
        ByteArrayOutputStream buf = new ByteArrayOutputStream(8192);
        byte[] b = new byte[1024];
        int len;
        while ((len = is.read(b)) != -1) {
            buf.write(b, 0, len);
        }
        //读图像
        return ImageIO.read(new ByteArrayInputStream(buf.toByteArray()));
    }

    /**
     * emoji表情替换
     *
     * @param source  原字符串
     * @param slipStr emoji表情替换成的字符串
     * @return 过滤后的字符串
     */
    public static String filterEmoji(String source, String slipStr) {
        if (StringUtils.isNotBlank(source)) {
            return source.replaceAll("[\\ud800\\udc00-\\udbff\\udfff\\ud800-\\udfff]", slipStr);
        } else {
            return source;
        }
    }


    public static void main(String[] args) throws IOException {

        String qrUrl = "http://mmbiz.qpic.cn/mmbiz_jpg/Ok5g79kcQL182Ba4CCZHCUPB24DsYYsGpzicBQ34nKP5qWljLFBat1ic8UCrsrKIe7I9GM8PJCpo320bKBKvDnhw/0";

        String nickname = "Aperson’s狂欢\uD83C\uDF02";

        //大图
        String headImgUrl ="";
        //小图
        String headImgUrlMin = "";

        String courseImgUrl = "http://hbb-deploy.oss-cn-beijing.aliyuncs.com/hpc_banner/GeNm8DHfpd.png";

        //String invitationCard = createInvitationCard(InvitationCardType.COURSE, qrUrl, nickname, headImgUrlMin, courseImgUrl); 直接测试路径不一样

        //System.out.println("生成的模板绝对路径: " + invitationCard);

    }
}

以上是关于java怎么生成带用户微信头像的图片,并把这张图片发送给用户。的主要内容,如果未能解决你的问题,请参考以下文章

怎么生成中间有图像的二维码

java 微信海报的实现

java 微信海报的实现

微信换头像显示上传失败怎么办

QQ空间别人发的图片为啥显示自己的网名?怎么弄的

怎样自己制作微信二维码带字图片