package com.kadang.designer.web.action;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontFormatException;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.font.TextLayout;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import javax.imageio.ImageIO;

import org.apache.commons.lang.StringUtils;

public class DrawImageDemo {

public static void main(String[] args) {
        String fileName = "STLITI.ttf";// 楷体
        int bold = 0; // 是否加粗
        int italic = 0; // 是否斜体
        int size = 100;
         String text = "春眠不觉晓,\n处处闻啼鸟。\n夜来风雨声,\n花落知多少。";
        //String text = "我送检单是\naab,,xxxb\n接口的零啊11食 ";
        // String text = "花夜处春\n落来处眠\n知风闻不\n多雨啼觉\n少声鸟晓\n。,。,";
        // String text = "夜   \n中\n的\n时\n大\nA\n懂\n禁\n小";
        // String text = "啊";
        // String text = "春a";
        int rgb = 125; // 颜色
        // 设置字体
        Font font = getFont(fileName);
        font = deriveFont(font, bold, italic, size);
        // generate font image
        // BufferedImage img = CreateFontImgWithGraphics(text, rgb, grid, font,
        // (int)rect.getWidth(), (int)rect.getHeight());
        BufferedImage img = CreateFontImgWithGraphics(text, rgb, true, font);
        // 图片生成路径
        File file = new File("F:\\test.jpg");
        try {
            ImageIO.write(img, "JPEG", file);
            // Iterator iter = ImageIO.getImageWritersByFormatName("PNG");
            // ImageWriter writer = (ImageWriter) iter.next();
            // ImageWriteParam iwp = writer.getDefaultWriteParam();
            // iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
            // iwp.setCompressionQuality(1); // best quality
            // FileImageOutputStream output = new FileImageOutputStream(file);
            // writer.setOutput(output);
            // IIOImage image = new IIOImage(img, null, null);
            // writer.write(null, image, iwp);
            // writer.dispose();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

private static Font deriveFont(Font font, int bold, int italic, int size) {
        int style = Font.PLAIN;
        if (bold > 0) {
            style = style | Font.BOLD;
        }
        if (italic > 0) {
            style = style | Font.ITALIC;
        }
        return font.deriveFont(style, size);
    }

// 获取字体
    private static Font getFont(String fileName) {
        File file = new File("Z:\\font\\" + fileName);
        InputStream fi = null;
        BufferedInputStream fb = null;
        Font nf = null;
        try {
            // 字体文件
            fi = new FileInputStream(file);
            fb = new BufferedInputStream(fi);
            // 生成字体
            nf = Font.createFont(Font.TRUETYPE_FONT, fb);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (FontFormatException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return nf;
    }

private static BufferedImage CreateFontImgWithGraphics(String text, int rgb, boolean isVertical, Font font) {
        // 字体大小
        int fontSize = font.getSize();
        // 高、宽比例
        float radio = 1.4f;
        // 文字图片边框
        float border = (float) (fontSize * 0.1);
        // 设置每行的固定高度,用于横排
        int line_height = Math.round(fontSize * radio);
        // 设置每行的固定宽度度,用于竖排
        int line_width = Math.round(fontSize * radio);
        // 文字
        String lines[] = text.split("\n");
        String line;
        TextLayout layout;
        // 计算图片的width,height
        BufferedImage tmp = new BufferedImage(1, 1, BufferedImage.TYPE_4BYTE_ABGR);
        Graphics2D gtmp = (Graphics2D) tmp.getGraphics();
        // dwh用于根据实际文件来计算图片某一边的长度,dx用于对图片水平方向的空白补齐,dy用于对图片垂直方向的空白补齐
        float dwh = 0, dx = 0, dy = 0;
        for (int i = 0; i < lines.length; i++) {
            line = lines[i];
            if (StringUtils.isNotBlank(line)) {
                layout = new TextLayout(line, font, gtmp.getFontRenderContext());
                dwh = Math.max(layout.getAdvance(), dwh);
                dy = (float) Math.min(-((isVertical ? fontSize : line_height) - layout.getBounds().getHeight()) / 2, dy);
            }
        }
        // 横排文字:width不固定,height固定; 竖排文字:width固定,height不固定
        // 文字图片的宽
        int width = Math.round((isVertical ? line_width * lines.length : dwh) + 2 * border);
        // 文字图片的高
        int height = Math.round((isVertical ? dwh : line_height * lines.length) + 2 * border);
        // 创建文字图片
        BufferedImage image = new BufferedImage(width < 1 ? 1 : width, // width
                height < 1 ? 1 : height, // height
                BufferedImage.TYPE_4BYTE_ABGR);// RGB mode
        // get graphics context
        Graphics2D g = (Graphics2D) image.getGraphics();
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g.setColor(new Color(rgb));
        g.setFont(font);
        // 初始化第一个字的坐标
        float xpos = isVertical ? width : border + dx, ypos = border + dy;
        // 每行字
        for (int i = 0; i < lines.length; i++) {
            line = lines[i];
            if (isVertical) {
                xpos -= line_width;
                ypos = border + dy;
            } else {
                xpos = border + dx;
                ypos += line_height;
            }
            // 如果该行为空行,直接跳过
            if (StringUtils.isBlank(lines[i])) {
                continue;
            }
            // 每个字符
            for (int j = 0; j < line.length(); j++) {
                char c = line.charAt(j);
                // 用于获取字的该advance
                layout = new TextLayout(String.valueOf(c), font, g.getFontRenderContext());
                g.scale(1.0, 1.0); // 比例
                if (c > 32 && c < 126 && isVertical) {
                    g.rotate(Math.PI / 2, xpos, ypos + layout.getAdvance());
                    g.drawString(String.valueOf(c),   xpos  , ypos+ layout.getAdvance());
                    g.rotate(-Math.PI / 2, xpos, ypos + layout.getAdvance());
                } else {
                    g.drawString(String.valueOf(c), xpos, isVertical ? ypos + layout.getAdvance() : ypos);
                }
                System.out.println(c + ", xy:xpos =" + xpos + ",ypos=" + (ypos + layout.getAdvance()));

if (isVertical) {
                    ypos += layout.getAdvance();
                } else {
                    xpos += layout.getAdvance();
                }
            }
        }
        g.drawString(String.valueOf("a"), 160, 81);
        System.out.println("width:" + width + ", height:" + height);
        // g.setStroke(new BasicStroke(4.0f));// 线条粗细
        // g.setColor(Color.blue);// 线条颜色
        // g.drawLine(440, 0, 440, 580);// 线条起点及终点位置
        // g.setStroke(new BasicStroke(4.0f));// 线条粗细
        // g.setColor(Color.red);// 线条颜色
        // g.drawLine(0, 110, 620, 110);// 线条起点及终点位置
        g.dispose();
        return image;
    }

static class Rect {
        private float height;
        private float width;

public Rect() {
        }

public Rect(float height, float width) {
            super();
            this.height = height;
            this.width = width;
        }

public float getHeight() {
            return height;
        }

public void setHeight(float height) {
            this.height = height;
        }

public float getWidth() {
            return width;
        }

public void setWidth(float width) {
            this.width = width;
        }

}
}

java生成竖排文字图片的更多相关文章

  1. Java生成动态GIF图片

    写selenium自动化时,为了查看运行效果,后给浏览器截图,想到可以生成gif图片来快速预览.看到已经有人实现了,直接拿过来. 共涉及到三个java文件,分别是NeuQuant.java,LZWEn ...

  2. java生成简单验证码图片

    概要 最近项目需要用java实现输出随机验证码图片到前台,正好有机会接触下java的绘图类,完成需求后也有时间做个总结,写篇随笔记录下也希望能帮助到有同样需求的人! 需求流程图 1.生成随机数 在ja ...

  3. java生成随机验证码图片

    import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; i ...

  4. java 生成透明背景图片

    //开始绘图 graphics2d.setBackground(Color.WHITE); graphics2d.clearRect(0, 0, width, height); graphics2d. ...

  5. Java 实现word 中写入文字图片的解决方案

    JAVA生成WORD文件的方法目前有以下两种方式: 一种是jacob 但是局限于windows平台 往往许多JAVA程序运行于其他操作系统 在此不讨论该方案; 一种是poi但是他的excel处理很程序 ...

  6. asp.net生成缩略图、文字图片水印

    /// <summary> /// 会产生graphics异常的PixelFormat /// </summary> private static PixelFormat[] ...

  7. C#一些常用的图片操作方法:生成文字图片 合并图片等

    生成文字图片: /// <summary> /// 生成文字图片 /// </summary> /// <param name="text">& ...

  8. java图片裁剪和java生成缩略图

    一.缩略图 在浏览相冊的时候.可能须要生成相应的缩略图. 直接上代码: public class ImageUtil { private Logger log = LoggerFactory.getL ...

  9. php生成文字图片效果

    php生成文字图片效果最近看到php的GD功能,试着做了一个基本生成文字图片效果的代码: 显示文字图片页面:demo.php<?php$str = $_REQUEST['str'] ? $_RE ...

随机推荐

  1. java实现smtp邮件发送

    一.准备工作 首先你需要已一个发送邮箱,一般的邮箱都有SMTP.POP3服务,比如QQ邮箱,登陆QQ邮箱开启SMTP服务,开启是服务器会提示你设置独立密码,这个密码是跟邮箱正常登陆的密码不同的,这个是 ...

  2. ios SourceTree中添加git项目工程文件

    1.创建远程git仓库 2.复制远程仓库地址,最好选择http的地址. 3.在自己的电脑上下载一个SourceTree,然后在自己的电脑上建立链接. 点击左上角的+号桶开始添加,弄好点击Clone 4 ...

  3. sbt的assembly插件使用(打包所有依赖)

    1.sbt是什么 对于sbt 我也是小白, 为了搞spark看了一下scala,学习scala时指定的构建工具就是sbt(因为sbt也是用scala开发的嘛),起初在我眼里就是一个maven(虽然ma ...

  4. python数据处理相关的一些知识点(学习点)

    自己总结了一下就是存储,消息处理(异步,阻塞,队列,消息中间件) 参考岗位需求 数据爬虫工程师的岗位职责:1.分布式网络爬虫研发:不断完善现有抓取系统,通过对抓取.解析.调度.存储等模块的拆分与优化, ...

  5. Vrapper-Eclipse的vim插件安装方法

    Vrapper是一款Eclipse的插件,使在Eclipse下编辑文档时可以像使用Vim一样. 它有两种安装方法,在线安装和安装包安装: 在线安装: 打开Eclipse,Help->Instal ...

  6. html5 文件上传 带进度条

    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/ ...

  7. Hive安装与部署集成mysql

    前提条件: 1.一台配置好hadoop环境的虚拟机.hadoop环境搭建教程:稍后补充 2.存在hadoop账户.不存在的可以新建hadoop账户安装配置hadoop. 安装教程: 一.Mysql安装 ...

  8. Duang的成长——使用造字程序输入生僻字

    使用造字程序输入生僻字 最近,一个字突然间火了起来,那就是——duang! (图片来自网络) 那么,问题来了!造字程序哪家强?(此处有掌声) 其实,微软早就考虑到各国文字的博大精深,在系统中集成了一个 ...

  9. [ASE][Daily Scrum]11.13

    今天的计划如下: View Shilin Liu 修复残缺地图下的行进问题           Client Jiafan Zhu(回学校了) 和服务器端对接测试 Yiming Liao       ...

  10. bootstrap中实现外层DIV自适应,内层DIV宽度固定且居中的布局

    <!DOCTYPE html><html> <head> <link rel="stylesheet" href="css/bo ...