Java——BufferedImage對象

來源:互聯網
上載者:User

標籤: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對象

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.