標籤:amp 建構函式 exception print 實現 col pix erb als
BufferedImage對象中最重要的兩個組件是Raster與ColorModel,分別用於儲存映像的像素資料和顏色資料。
1、Raster對象的作用與像素儲存
BufferedImage支援從Raster對象中擷取任意位置(x,y)點的像素值p(x,y)
image.getRaster().getDataElements(x,y,width,height,pixels)
x,y表示開始的像素點,width和height表示像素資料的寬度和高度,pixels數組用來存放擷取到的像素資料,image是一個BufferedImage的執行個體化引用。
2、映像類型與ColorModel
其實作類別為IndexColorModel,IndexColorModel的建構函式有五個參數:分別為
Bits:表示每個像素所佔的位元,對RGB來說是8位
Size:表示顏色組件數組長度,對應RGB取值範圍為0~255,值為256
r[]:位元組數組r表示顏色組件的RED值數組
g[]:位元組數組g表示顏色組件的GREEN值數組
b[]:位元組數組b表示顏色組件的BLUE值數組
3、BufferedImage對象的建立與儲存
(1)建立一個全新的BufferedImage對象,直接調用BufferedImage的建構函式
BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY)
其中width表示映像的寬度,height表示映像的高度,最後一個參數表示映像位元組灰階映像
(2)根據已經存在的BufferedImage對象來建立一個相同的copy體
public BufferedImage createBufferedImage(BufferedImage src){
ColorModel cm = src.getColorModel();
BufferedImage image = new BufferedImage(cm,
cm.creatCompatibleWritableRaster(
src.getWidth(),
src.getHeight()),
cm.isAlphaPremultiplied(), null);
return image;
}
(3)通過建立ColorModel 和Raster對象實現BufferedImage 對象的執行個體化
public BufferedImage createBufferedImage(int width , int height, byte[] pixels){
ColorModel cm = getColorModel();
SampleModel sm = getIndexSampleModel((IndexColorModel)cm, width,height);
DataBuffer db = new DataBufferByte(pixels, width*height,0);
WritableRaster raster = Raster.creatWritableRaster(sm, db,null);
BufferedImage image = new BufferedImage (cm, raster,false, null);
return image;
}
(4)讀取一個影像檔
public BufferedImage readImageFile(File file)
{
try{
BufferedImage image = ImageIo.read(file);
return image;
}catch(IOException e){
e.printStrackTrace();
}
return null;
}
(5)儲存BufferedImage 對象為影像檔
public void writeImageFile(BufferedImage bi) throws IOException{
File outputfile = new File("save.png");
ImageIO.write(bi,"png",outputfile);
}
Java——BufferedImage對象