zoukankan      html  css  js  c++  java
  • 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);  

    }

  • 相关阅读:
    第10组 Beta冲刺(4/5)
    第10组 Beta冲刺(5/5)
    第10组 Beta冲刺(3/5)
    第10组 Beta冲刺(2/5)
    第10组 Beta冲刺(1/5)
    第10组 Alpha事后诸葛亮
    第10组 Alpha冲刺(6/6)
    第10组 Alpha冲刺(5/6)
    软工实践个人总结
    第09组 Beta版本演示
  • 原文地址:https://www.cnblogs.com/bigdream6/p/8366248.html
Copyright © 2011-2022 走看看