java模拟微信以及钉钉生成群组头像

package cn.smartpilot.yangjiang;

import java.awt.*;

import java.awt.geom.RoundRectangle2D;

import java.awt.image.BufferedImage;

import java.io.*;

import java.net.URL;

import java.net.URLConnection;

import java.util.ArrayList;

import java.util.List;

import java.util.Random;

import java.util.regex.Matcher;

import java.util.regex.Pattern;

import javax.imageio.ImageIO;

/**

* 该类是图片处理类

*

* @author zhoulei

*/

public final class GroupImageUtil {

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

List imgList=new ArrayList();

//        imgList.add("E:/qq/1.jpeg");

//        imgList.add("E:/qq/2.jpg");

//        imgList.add("E:/qq/3.jpeg");

//        imgList.add("E:/qq/4.jpg");

//        createGroupImage(imgList,"E:/qq/","g");

        String name ="于海波";

        createNameImg(name, "E:/qq/", name);

        System.out.println("生成完成");

    }

/**根据传来的头像图片列表组合成群组图片

    * @param files

    * @param outputPath

    * @param outputName

    * @throws Exception

    * @return

    */

    public static void createGroupImage(List files, String outputPath, String outputName)throws Exception{

String filePath = outputPath + File.separator + outputName +".png";

        String[] imageSize =getXy(files.size());

        int width =getWidth(files.size());

        BufferedImage imageNew =new BufferedImage(132,132,BufferedImage.TYPE_INT_ARGB);

        //设置背景为白色

//        for(int m=0;m<132;m++){

//            for(int n=0;n<132;n++){

//                imageNew.setRGB(m, n, 0xFFFFFF);

//            }

//        }

        for(int i=0;i

String size = imageSize[i];

            String[] sizeArr = size.split(",");

            int x = Integer.valueOf(sizeArr[0]);

            int y = Integer.valueOf(sizeArr[1]);

            String f =zoom(files.get(i),"E:\\test",width,width);

            File fileOne =new File(f);

            BufferedImage ImageOne = ImageIO.read(fileOne);

            //从图片中读取RGB

            int[] ImageArrayOne =new int[width*width];

            ImageArrayOne = ImageOne.getRGB(0,0,width,width,ImageArrayOne,0,width);

            imageNew.setRGB(x,y,width,width,ImageArrayOne,0,width);//设置左半部分的RGB

        }

imageNew =makeRoundedCorner(imageNew, 60);

        File outFile =new File(filePath);

        ImageIO.write(imageNew, "png", outFile);//写图片

    }

/**

    * 绘制字体头像

    * 如果是英文名,只显示首字母大写

    * 如果是中文名,只显示最后两个字

    * @param name

    * @param outputPath

    * @param outputName

    * @throws IOException

*/

    public static void createNameImg(String name, String outputPath, String outputName)

throws IOException {

int width =100;

        int height =100;

        int nameLen = name.length();

        String nameWritten;

        // 如果用户输入的姓名少于等于2个字符,不用截取

//        if (nameLen <= 2) {

//            nameWritten = name;

//        } else {

//            // 如果用户输入的姓名大于等于3个字符,截取后面两位

//            String first = name.substring(0, 1);

//            if (isChinese(first)) {

//                // 截取倒数两位汉字

//                nameWritten = name.substring(nameLen - 2);

//            } else {

//                // 截取前面的两个英文字母

//                nameWritten = name.substring(0, 2).toUpperCase();

//            }

//        }

        if (nameLen <=1) {

nameWritten = name;

        }else{

nameWritten = name.substring(0, 1);

        }

String filename = outputPath + File.separator + outputName +".png";

        File file =new File(filename);

        //Font font = new Font("微软雅黑", Font.PLAIN, 30);

        BufferedImage bi =new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        Graphics2D g2 = (Graphics2D) bi.getGraphics();

        g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,

                RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

        g2.setBackground(getRandomColor());

        g2.clearRect(0, 0, width, height);

        g2.setPaint(Color.WHITE);

        Font font =null;

        // 两个字及以上

        if(nameWritten.length() >=2) {

font =new Font("微软雅黑", Font.BOLD, 48);

            g2.setFont(font);

            String firstWritten = nameWritten.substring(0, 1);

            String secondWritten = nameWritten.substring(1, 2);

            // 两个中文 如 张三

            if (isChinese(firstWritten) &&isChinese(secondWritten)) {

g2.drawString(nameWritten, 20, 60);

            }

// 首中次英 如 张S

            else if (isChinese(firstWritten) && !isChinese(secondWritten)) {

g2.drawString(nameWritten, 27, 60);

            }

// 首英,如ZS

            else {

nameWritten = nameWritten.substring(0,1);

            }

}

// 一个字

        if(nameWritten.length() ==1) {

// 中文

            if(isChinese(nameWritten)) {

font =new Font("微软雅黑", Font.PLAIN, 50);

                g2.setFont(font);

                g2.drawString(nameWritten, 25, 70);

            }

// 英文

            else {

font =new Font("微软雅黑", Font.PLAIN, 55);

                g2.setFont(font);

                g2.drawString(nameWritten.toUpperCase(), 33, 67);

            }

}

BufferedImage rounded =makeRoundedCorner(bi, 99);

        ImageIO.write(rounded, "png", file);

    }

public static String[]getXy(int size){

String[] s =new String[size];

        int _x =0;

        int _y =0;

        if(size ==1){

_x = _y =6;

            s[0] ="6,6";

        }

if(size ==2){

_x =_y =4;

            s[0] ="4,"+(132/2-60/2);

            s[1] =60+2*_x+","+ (132/2-60/2);

        }

if(size ==3){

_x=_y =4;

            s[0] = (132/2-60/2)+","+_y;

            s[1] = _x+","+(60+2*_y);

            s[2] = (60+2*_y)+","+(60+2*_y);

        }

if(size ==4){

_x=_y =4;

            s[0] = _x+","+_y;

            s[1] = (_x*2 +60)+","+_y;

            s[2] = _x+","+(60+2*_y);

            s[3] = (60+2*_y)+","+(60+2*_y);

        }

if(size ==5){

_x = _y =3;

            s[0] = (132-40*2-_x)/2+","+(132-40*2-_y)/2;

            s[1] = ((132-40*2-_x)/2+40+_x)+","+(132-40*2-_y)/2;

            s[2] = _x+","+((132-40*2-_x)/2+40+_y);

            s[3] = (_x*2+40)+","+((132-40*2-_x)/2+40+_y);

            s[4] = (_x*3+40*2)+","+((132-40*2-_x)/2+40+_y);

        }

if(size ==6){

_x = _y =3;

            s[0] = _x+","+((132-40*2-_x)/2);

            s[1] = (_x*2+40)+","+((132-40*2-_x)/2);

            s[2] = (_x*3+40*2)+","+((132-40*2-_x)/2);

            s[3] = _x+","+((132-40*2-_x)/2+40+_y);

            s[4] = (_x*2+40)+","+((132-40*2-_x)/2+40+_y);

            s[5] = (_x*3+40*2)+","+((132-40*2-_x)/2+40+_y);

        }

if(size ==7){

_x=_y =3;

            s[0] = (132-40)/2+","+_y;

            s[1] = _x+","+(_y*2+40);

            s[2] = (_x*2+40)+","+(_y*2+40);

            s[3] = (_x*3+40*2)+","+(_y*2+40);

            s[4] = _x+","+(_y*3+40*2);

            s[5] = (_x*2+40)+","+(_y*3+40*2);

            s[6] = (_x*3+40*2)+","+(_y*3+40*2);

        }

if(size ==8){

_x=_y =3;

            s[0] = (132-80-_x)/2+","+_y;

            s[1] = ((132-80-_x)/2+_x+40)+","+_y;

            s[2] = _x+","+(_y*2+40);

            s[3] = (_x*2+40)+","+(_y*2+40);

            s[4] = (_x*3+40*2)+","+(_y*2+40);

            s[5] = _x+","+(_y*3+40*2);

            s[6] = (_x*2+40)+","+(_y*3+40*2);

            s[7] = (_x*3+40*2)+","+(_y*3+40*2);

        }

if(size ==9){

_x=_y =3;

            s[0]=_x+","+_y;

            s[1] = _x*2+40+","+_y;

            s[2] = _x*3+40*2 +","+_y;

            s[3] = _x+","+(_y*2+40);

            s[4] = (_x*2+40)+","+(_y*2+40);

            s[5] = (_x*3+40*2)+","+(_y*2+40);

            s[6] = _x+","+(_y*3+40*2);

            s[7] = (_x*2+40)+","+(_y*3+40*2);

            s[8] = (_x*3+40*2)+","+(_y*3+40*2);

        }

return s;

    }

public static int getWidth(int size){

int width =0;

        if(size ==1){

width =120;

        }

if(size>1 && size<=4){

width =60;

        }

if(size>=5){

width =40;

        }

return width;

    }

public static void download(String urlString, String filename,String savePath)throws Exception {

// 构造URL

        URL url =new URL(urlString);

        // 打开连接

        URLConnection con = url.openConnection();

        //设置请求超时为5s

        con.setConnectTimeout(5*1000);

        // 输入流

        InputStream is = con.getInputStream();

        // 1K的数据缓冲

        byte[] bs =new byte[1024];

        // 读取到的数据长度

        int len;

        // 输出的文件流

        File sf=new File(savePath);

        if(!sf.exists()){

sf.mkdirs();

        }

OutputStream os =new FileOutputStream(sf.getPath()+File.separator+filename);

        // 开始读取

        while ((len = is.read(bs)) != -1) {

os.write(bs, 0, len);

        }

// 完毕,关闭所有链接

        os.close();

        is.close();

    }

public static Stringzoom(String sourcePath,String targetPath,int width,int height)throws IOException{

File imageFile =new File(sourcePath);

        if(!imageFile.exists()){

throw new IOException("Not found the images:"+sourcePath);

        }

if(targetPath==null || targetPath.isEmpty()) targetPath = sourcePath;

        String format = sourcePath.substring(sourcePath.lastIndexOf(".")+1,sourcePath.length());

        BufferedImage image = ImageIO.read(imageFile);

        image =zoom(image,width,height);

        ImageIO.write(image, format, new File(targetPath));

        return targetPath;

    }

private static BufferedImagezoom(BufferedImage sourceImage, int width, int height){

BufferedImage zoomImage =new BufferedImage(width, height, sourceImage.getType());

        Image image = sourceImage.getScaledInstance(width, height, Image.SCALE_SMOOTH);

        Graphics gc = zoomImage.getGraphics();

        gc.setColor(Color.WHITE);

        gc.drawImage( image, 0, 0, null);

        return zoomImage;

    }

/**

    * 生成圆角图标

    * @param image

    * @param cornerRadius 圆角半径

    * @return

    */

    public static BufferedImagemakeRoundedCorner(BufferedImage image, int cornerRadius) {

int w = image.getWidth();

        int h = image.getHeight();

        BufferedImage output =new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);

        Graphics2D g2 = output.createGraphics();

        g2.setComposite(AlphaComposite.Src);

        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        g2.setColor(Color.WHITE);

        g2.fill(new RoundRectangle2D.Float(0, 0, w, h, cornerRadius, cornerRadius));

        g2.setComposite(AlphaComposite.SrcAtop);

        g2.drawImage(image, 0, 0, null);

        g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 0f)); // 1.0f为透明度 ,值从0-1.0,依次变得不透明

        g2.dispose();

        return output;

    }

/**

    * 判断字符串是否为中文

    * @param str

    * @return

    */

    public static boolean isChinese(String str) {

String regEx ="[\\u4e00-\\u9fa5]+";

        Pattern p = Pattern.compile(regEx);

        Matcher m = p.matcher(str);

        if (m.find())

return true;

else

return false;

    }

/**

    * 获得随机颜色

    * @return

    */

    private static ColorgetRandomColor() {

String[] beautifulColors =

new String[]{"232,221,203", "205,179,128", "3,101,100", "3,54,73", "3,22,52",

                        "237,222,139", "251,178,23", "96,143,159", "1,77,103", "254,67,101", "252,157,154",

                        "249,205,173", "200,200,169", "131,175,155", "229,187,129", "161,23,21", "34,8,7",

                        "118,77,57", "17,63,61", "60,79,57", "95,92,51", "179,214,110", "248,147,29",

                        "227,160,93", "178,190,126", "114,111,238", "56,13,49", "89,61,67", "250,218,141",

                        "3,38,58", "179,168,150", "222,125,44", "20,68,106", "130,57,53", "137,190,178",

                        "201,186,131", "222,211,140", "222,156,83", "23,44,60", "39,72,98", "153,80,84",

                        "217,104,49", "230,179,61", "174,221,129", "107,194,53", "6,128,67", "38,157,128",

                        "178,200,187", "69,137,148", "117,121,71", "114,83,52", "87,105,60", "82,75,46",

                        "171,92,37", "100,107,48", "98,65,24", "54,37,17", "137,157,192", "250,227,113",

                        "29,131,8", "220,87,18", "29,191,151", "35,235,185", "213,26,33", "160,191,124",

                        "101,147,74", "64,116,52", "255,150,128", "255,94,72", "38,188,213", "167,220,224",

                        "1,165,175", "179,214,110", "248,147,29", "230,155,3", "209,73,78", "62,188,202",

                        "224,160,158", "161,47,47", "0,90,171", "107,194,53", "174,221,129", "6,128,67",

                        "38,157,128", "201,138,131", "220,162,151", "137,157,192", "175,215,237", "92,167,186",

                        "255,66,93", "147,224,255", "247,68,97", "185,227,217"};

        int len = beautifulColors.length;

        Random random =new Random();

        String[] color = beautifulColors[random.nextInt(len)].split(",");

        return new Color(Integer.parseInt(color[0]), Integer.parseInt(color[1]),

                Integer.parseInt(color[2]));

    }

/**

    * 将BufferedImage转换为InputStream

    * @param image

    * @return

    */

    public static InputStreambufferedImageToInputStream(BufferedImage image){

ByteArrayOutputStream os =new ByteArrayOutputStream();

        try {

ImageIO.write(image, "png", os);

            InputStream input =new ByteArrayInputStream(os.toByteArray());

            return input;

        }catch (IOException e) {

e.printStackTrace();

        }

return null;

    }

}

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 218,525评论 6 507
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,203评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,862评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,728评论 1 294
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,743评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,590评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,330评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,244评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,693评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,885评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,001评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,723评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,343评论 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,919评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,042评论 1 270
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,191评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,955评论 2 355

推荐阅读更多精彩内容