一、創建個圖片生成器類名為ImageCreator
/**
* 模板方法模式應用:圖片生成器
*/
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();
//畫長方形
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;
}
//執行
g.dispose();
//輸出圖片結果
ImageIO.write(image, "JPEG", output);
}
}
二、創建一個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();//創建該類實例時,程序內部會創建一個byte類型數組的緩沖區,
//然后利用BtyeArrayOutputStream和ByteArrayInputStream實例向數組中寫入或讀出Byte型數據。
//ByteArrayOutputStream把所有的變量收集到一起,然后一次性把數據發送出去,捕獲內存緩沖區的數據 轉換成字節數組。
//ByteArrayInputStream 將字節數組轉化成輸入流
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;
}
}
三、在測試類中代碼測試
/* 任務:利用迭代器顯示字節流
*
1,使用方法iterator()要求容器返回一個Iterator.第一次調用Iterator的next()方法時,它返回序列的第一個元素;
2,使用next()獲得序列中的下一個元素;
3,使用hasNext()檢查序列中是否還有元素;
4,使用remove()將迭代器新近返回的元素刪除.
5,HashMap中使用enterySet()返回此映射所包含的映射關系的 Set 視圖 ;也可以說該方法返回一個Map.Entry實例化后的對象集
6,使用Map.Entry類 同一時間內取得map中的key鍵和相應的值。
*/
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());
}