一
另外
二
/**本代碼在 已使用了 */
public abstract class AbstractImageCreator {
private static Random rnd = new Random(new Date()
//圖片寬度
private int width =
//圖片高度
private int height =
//外框顏色
private Color rectColor;
//背景色
private Color bgColor;
//干擾線數目
private int lineNum =
//圖片格式
private String formatName =
//字體顏色
private Color fontColor = new Color(
//字體名稱
private String fontName =
//字體大小
private int fontSize =
//##### 這裡省略成員變臉的get
/**
* 畫干擾線
*/
private void drawRandomLine(Graphics graph){
for(int i=
//線條的顏色
graph
//線條兩端坐標值
int x
int y
int x
int y
//畫線條
graph
}
}
/**
* 隨機獲取顏色對象
*/
private Color getRandomColor(int base
if((base + range) >
int red = base + rnd
int green = base + rnd
int blue = base + rnd
return new Color(red
}
//該方法內應用了模板方法模式
public void drawImage(String text)throws IOException{
BufferedImage image = new BufferedImage(width
if(rectColor == null) rectColor = new Color(
if(bgColor == null) bgColor = new Color(
//獲取畫布
Graphics graph = image
//畫長方形
graph
graph
//外框
graph
graph
//畫干擾線
drawRandomLine(graph);
//畫字符串
drawString(graph
//執行
graph
//輸出圖片結果
saveImage(image);
}
protected abstract void drawString(Graphics graph
protected abstract void saveImage(BufferedImage image)throws IOException;
}
該類將生成的圖片存儲到一個文件中
Java代碼
public class DefaultImageCreator extends AbstractImageCreator {
private String outputFilePath;
public String getOutputFilePath() {
return outputFilePath;
}
public void setOutputFilePath(String outputFilePath) {
this
}
public DefaultImageCreator(){
}
public DefaultImageCreator(String outputFilePath){
this
}
@Override
protected void drawString(Graphics graph
graph
Font font = new Font(getFontName()
graph
FontMetrics fm = graph
int fontHeight = fm
int offsetLeft =
int rowIndex =
for(int i=
char c = text
int charWidth = fm
//另起一行
if(Character
rowIndex++;
offsetLeft =
}
graph
offsetLeft += charWidth;
}
}
@Override
protected void saveImage(BufferedImage image)throws IOException{
ImageIO
}
}
該類將生成的圖片存儲到一個輸出流中
Java代碼
public class OutputStreamImageCreator extends DefaultImageCreator {
private OutputStream out ;
public OutputStream getOut() {
return out;
}
public void setOut(OutputStream out) {
this
}
public OutputStreamImageCreator(){
}
public OutputStreamImageCreator(OutputStream out){
this
}
@Override
public String getOutputFilePath() {
return null;
}
@Override
public void setOutputFilePath(String outputFilePath) {
outputFilePath = null;
}
@Override
protected void saveImage(BufferedImage image) throws IOException {
if(out!=null) ImageIO
}
}
三
StringBuffer sb = new StringBuffer();
sb
sb
DefaultImageCreator creator = new DefaultImageCreator(
creator
creator
creator
creator
creator
From:http://tw.wingwit.com/Article/program/Java/hx/201311/26622.html