首先定義用到的數據類型
Icon icon;//聲明一個圖標類
Image?image;
ImageIcon?icon;//使用ImageIcon類創建一個圖標
BufferedImage?bi;
byte[]?bytes;
Blob?blob;
String?fileName;
一、ImageIcon類
構造函數
icon?=?new?ImageIcon(fileName);
icon?=?new?ImageIcon(bytes);
icon?=?new?ImageIcon(image);
實用方法
int?getIconHeight();
int?getIconWidth();
void?setImage(Image?image);
Image?getImage();
小結
ImageIcon與Image間的轉換比較方便,更偏向于應用方面,主要是控件中的setIcon(ImageIcon)方法。
二、Image類
實用方法
1.縮放圖片大小,其中hints通常用Image.SCALE_SMOOTH
Image?getScaledInstance(int?width,?int?height,?int?hints);
2.獲取圖片長寬值
int?getHeight(null);
int?getWidth(null);
小結
Image更像一個過渡類,將圖形轉換成別的圖形類,如ImageIcon、BufferedImage等。
三、BufferedImage類
構造函數
bi?=?new?BufferedImage(int?width,?int?height,?int?imageType);
這里的imageType我習慣用BufferedImage.TYPE_INT_ARGB,構造出來的BufferedImage更像是一個模式,需要往里面加數據。
關于BufferedImage的一些用法
1.Image寫入BufferedImage
bi.getGraphics().drawImage(Image?img,?int?x,?int?y,?int?width,?int?height,?ImageObserver?observer)
2.BufferedImage轉換到bytes[]或文件
bi?=?ImageIO.read(new?File(fileName));
//放縮到36*36
image=?bi.getScaledInstance?(36,36,Image.SCALE_SMOOTH);
double?wRatio?=?36.0/bi.getWidth();
double?hRatio?=?36.0/bi.getHeight();
//AffineTransformOp.TYPE_BICUBIC?表示3次方放縮
AffineTransformOp?op?=?new?AffineTransformOp(AffineTransform.getScaleInstance(wRatio,?hRatio),AffineTransformOp.TYPE_BICUBIC);
bi?=?op.filter(bi,?null);
ByteArrayOutputStream?out?=?new?ByteArrayOutputStream();
ImageIO.write(bi,?"jpg",?out);
bytes?=?out.toByteArray();
這里用到的ImageIO.write方法參數為(RenderedImage?im,?String?formatName,?ImageOutputStream?output),其中參數output是圖形的輸出流,可以定向到文件流new?FileOutputStream()實現將圖象寫入到文件。
3.以上兩個用法綜合使用可以將Image寫入到byte[]和文件。
四、byte[]和Blob的轉換
圖像在MySql中用BLOB數據類型(Binary?Large?Object)存儲
1.byte[]到Blob轉換
blob?=?new?SerialBlob(bytes);
blob.setBytes(long?pos,?byte[]?bytes);
2.Blob到byte[]轉換
bytes?=?blob.getBytes(long?pos,?int?length);
這里需要注意的一點是存儲圖形到MySql數據庫時使用Blob類型,從MySql取出圖形的Object應轉換到byte[]