Java——BufferedImage對象


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);  

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM