一、創(chuàng)建個(gè)圖片生成器類名為ImageCreator
/**
* 模板方法模式應(yīng)用:圖片生成器
*/
public class ImageCreator {
//圖片寬度
private int width = 200;
//圖片高度
private int height = 80;
//外框顏色
private Color rectColor;
//背景色
private Color bgColor;
public void generateImage(String text,ByteArrayOutputStream output)throws IOException{
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
if(rectColor == null) rectColor = new Color(0, 0, 0);
if(bgColor == null) bgColor = new Color(240, 251, 200);
//獲取畫布
Graphics2D g = (Graphics2D)image.getGraphics();
//畫長(zhǎng)方形
g.setColor(bgColor);
g.fillRect(0, 0, width, height);
//外框
g.setColor(rectColor);
g.drawRect(0, 0, width-1, height-1);
//畫字符串
g.setColor(new Color(0, 0, 0));//字體顏色
Font font = new Font("宋體", Font.PLAIN, 15);
g.setFont(font);
FontMetrics fm = g.getFontMetrics(font);
int fontHeight = fm.getHeight(); //字符的高度
int offsetLeft = 0;
int rowIndex = 1;
for(int i=0;i<text.length();i++){
char c = text.charAt(i);
int charWidth = fm.charWidth(c); //字符的寬度
//另起一行
if(Character.isISOControl(c) || offsetLeft >= (width-charWidth)){
rowIndex++;
offsetLeft = 0;
}
g.drawString(String.valueOf(c), offsetLeft, rowIndex * fontHeight);
offsetLeft += charWidth;
}
//執(zhí)行
g.dispose();
//輸出圖片結(jié)果
ImageIO.write(image, "JPEG", output);
}
}
二、創(chuàng)建一個(gè)ImageHashMap類
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class ImageHashMap {
public Map<Integer,byte[]> createMap()throws IOException
{
Map<Integer,byte[]> map=new HashMap<Integer,byte[]>();
ByteArrayOutputStream op =new ByteArrayOutputStream();//創(chuàng)建該類實(shí)例時(shí),程序內(nèi)部會(huì)創(chuàng)建一個(gè)byte類型數(shù)組的緩沖區(qū),
//然后利用BtyeArrayOutputStream和ByteArrayInputStream實(shí)例向數(shù)組中寫入或讀出Byte型數(shù)據(jù)。
//ByteArrayOutputStream把所有的變量收集到一起,然后一次性把數(shù)據(jù)發(fā)送出去,捕獲內(nèi)存緩沖區(qū)的數(shù)據(jù) 轉(zhuǎn)換成字節(jié)數(shù)組。
//ByteArrayInputStream 將字節(jié)數(shù)組轉(zhuǎn)化成輸入流
for(int i=1;i<=5;i++)
{
ImageCreator a=new ImageCreator();
a.generateImage(""+i, op);
byte[] bt=op.toByteArray();
map.put(i, bt);
}
return map;
}
}
三、在測(cè)試類中代碼測(cè)試
/* 任務(wù):利用迭代器顯示字節(jié)流
*
1,使用方法iterator()要求容器返回一個(gè)Iterator.第一次調(diào)用Iterator的next()方法時(shí),它返回序列的第一個(gè)元素;
2,使用next()獲得序列中的下一個(gè)元素;
3,使用hasNext()檢查序列中是否還有元素;
4,使用remove()將迭代器新近返回的元素刪除.
5,HashMap中使用enterySet()返回此映射所包含的映射關(guān)系的 Set 視圖 ;也可以說該方法返回一個(gè)Map.Entry實(shí)例化后的對(duì)象集
6,使用Map.Entry類 同一時(shí)間內(nèi)取得map中的key鍵和相應(yīng)的值。
*/
ImageHashMap imap=new ImageHashMap();
Map map = new HashMap();
Iterator iter=map.entrySet().iterator();//獲取map映射來的set視圖,返回迭代器
while(iter.hasNext())
{
Map.Entry entry=(Map.Entry)iter.next();
System.out.print(entry.getKey()+" ");
System.out.println(entry.getValue());
}