Graphics2D文字转换无背景文字图片
功能目标
实现将字符串转换成一个无背景的图片
实现效果图:
代码实现:
/**
* 工具类
**/
public static void main(String[] args) {
HashMap<String, String> dto=new HashMap<String, String>();
// 将文本转为图片
String name = "哈哈哈哈 @少年";
// 生成图片名称
String fileName = System.currentTimeMillis() + "suyin.jpg";
// 这是代表你生成图片后图片保存的路径 /Users/tp/ 是mac的路径地址,win系统的自行更换
String path = "/Users/tp/"+fileName;
textToPicture(name, path);
}
/**
* 文字转图片
* name 需要转换的文字
* path 转换完成后保存的地址路径
*/
public static void textToPicture(String name,String path){
boolean rs;
String content = name;
int length = content.length();
//300;
// 宽
int width = length * 45;
// 高
int height = 100;
//23;
int lineLength = 47;
//24;
int lineLength2 = 47;
String content1 = content;
String content2 = "";
String content3 = "";
int cnLineLength = lineLength;
for (int i = 0;i < content.length();i++) {
char ca = content.charAt(i);
if ((ca < '0' || ca > '9') && ca != '-' && ca != ':' && ca != '(' && ca != ')' && ca != '.' && ca != ',' && ca != ' ') {
cnLineLength = cnLineLength - 1;
}
if (i >= cnLineLength){
break;
}
}
if (content.length() > cnLineLength) {
content1 = content.substring(0, cnLineLength);
content2 = content.substring(cnLineLength);
String line2 = content2;
int cnLineLength2 = lineLength2;
for (int i = 0;i < line2.length();i++) {
char ca = line2.charAt(i);
if ((ca < '0' || ca > '9') && ca != '-' && ca != ':' && ca != '(' && ca != ')' && ca != '.' && ca != ',' && ca != ' ') {
cnLineLength2 = cnLineLength2 - 1;
}
if (i >= cnLineLength2){
break;
}
}
if (line2.length() > cnLineLength2) {
content2 = line2.substring(0, cnLineLength2);
content3 = line2.substring(cnLineLength2);
}
}
BufferedImage bi = null;
Graphics2D g2 = null;
OutputStream outPutStream = null;
try{
bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
g2 = (Graphics2D) bi.getGraphics();
// 增加下面代码使得背景透明
bi = g2.getDeviceConfiguration().createCompatibleImage(width, height, Transparency.TRANSLUCENT);
g2.dispose();
g2 = (Graphics2D) bi.getGraphics();
g2.setColor(new Color(255, 255, 255));
g2.setStroke(new BasicStroke(1f));
g2.fillRect(128, 128, width, height);
Font font = new Font("宋体", Font.BOLD, 40);
g2.setFont(font);
g2.drawString(content1, 10, 70);
g2.drawString(content2, 10, 300);
g2.drawString(content3, 10, 400);
outPutStream = new FileOutputStream(path);
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(outPutStream);
encoder.encode(bi);
rs = true;
} catch (Exception e) {
e.printStackTrace();
rs = false;
} finally {
if (g2 != null){
g2.dispose();
}
if (outPutStream != null) {
try {
outPutStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
ps
:一个开发界的小学生,一直在学习从未敢停止