1、绘制图形,并转成byte[]

    public static  byte[] createAvatar(String s) throws IOException {
        int width = 200;
        int height = 200;
        int fontSize = 80;
        
        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        
        Graphics2D g2d = bufferedImage.createGraphics();
        
        bufferedImage = g2d.getDeviceConfiguration().createCompatibleImage(width, height, Transparency.TRANSLUCENT);
        g2d = bufferedImage.createGraphics();
        
        g2d.setColor(Color.orange);
        g2d.fillOval(0, 0, width, height);
        
        g2d.setFont(new Font("文泉驿正黑", Font.PLAIN, fontSize));
        g2d.setColor(Color.white);
        g2d.drawString(s, width/2-fontSize*s.length()/2, height/2+fontSize/3);
        
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        ImageIO.write(bufferedImage, "png", stream);
        
        return stream.toByteArray();
    }

2、构建image/png返回

    @Path("image")
    @GET
    @Produces("image/png")
    public Response image() throws IOException{
        byte[] ib = ImageUtil.createAvatar("灿琳");
        return Response.ok(ib).build();
   }

3、关于字体的问题

这里使用的是开源字体“文泉驿正黑”,下载地址 http://wenq.org/wqy2/index.cgi 。下载后将文件复制到 $JAVA_HOME/jre/lib/fonts 。别忘了重启你的服务(比如:tomcat,jetty)

By charlie

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注