java:从sRGB字节流(byte[])创建BufferedImage

有时候我们需要从字节流byte[]创建一个BufferedImage对象,比如将jni层返回的图像数据转为BufferedImage对象并显示出来。BufferedImage类中的BufferedImage(java.awt.image.ColorModel, WritableRaster, boolean, java.util.Hashtable)构造函数可以满足这个要求。
不过你看到这个构造函数,所要求的参数完全不是byte[],所以需要做一些对象创建的工作才能达到我们的目的。
以RGB格式的图像矩阵数据为例,首先要构造 sRGB标准的ColorModel对象,然后再从存储图像矩阵的字节数组(byte[])构造WritableRaster。做完这两步就可以调用BufferedImage(java.awt.image.ColorModel, WritableRaster, boolean, java.util.Hashtable)构造生成 BufferedImage对象了。
下面是完整的代码:

package test;

import java.awt.Transparency;
import java.awt.color.ColorSpace;
import java.awt.image.BufferedImage;
import java.awt.image.ComponentColorModel;
import java.awt.image.DataBuffer;
import java.awt.image.DataBufferByte;
import java.awt.image.Raster;
import java.awt.image.WritableRaster;

public class RGBtoBufferedImage {
    /** * 根据指定的参数创建一个RGB格式的BufferedImage * @param matrixRGB RGB格式的图像矩阵 * @param width 图像宽度 * @param height 图像高度 * @return * @see DataBufferByte#DataBufferByte(byte[], int) * @see ColorSpace#getInstance(int) * @see ComponentColorModel#ComponentColorModel(ColorSpace, boolean, boolean, int, int) * @see Raster#createInterleavedRaster(DataBuffer, int, int, int, int, int[], java.awt.Point) * @see BufferedImage#BufferedImage(java.awt.image.ColorModel, WritableRaster, boolean, java.util.Hashtable) */
    public static BufferedImage createRGBImage(byte[] matrixRGB,int width,int height){
        // 检测参数合法性
        if(null==matrixRGB||matrixRGB.length!=width*height*3)
            throw new IllegalArgumentException("invalid image description");
        // 将byte[]转为DataBufferByte用于后续创建BufferedImage对象
        DataBufferByte dataBuffer = new DataBufferByte(matrixRGB, matrixRGB.length);
        // sRGB色彩空间对象
        ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_sRGB);
        int[] nBits = {8, 8, 8};
        int[] bOffs = {0, 1, 2};
        ComponentColorModel colorModel = new ComponentColorModel(cs, nBits, false, false,
                                             Transparency.OPAQUE,
                                             DataBuffer.TYPE_BYTE);        
        WritableRaster raster = Raster.createInterleavedRaster(dataBuffer, width, height, width*3, 3, bOffs, null);
        BufferedImage newImg = new BufferedImage(colorModel,raster,false,null);
       /* try { //写入文件测试查看结果 ImageIO.write(newImg, "bmp", new File(System.getProperty("user.dir"),"test.bmp")); } catch (IOException e) { e.printStackTrace(); }*/
        return  newImg;     
    }
}

如果你的图像数据是Gray或ARGB格式的,如何构造一个BufferedImage对象呢?
其实也差不多,
可以参照BufferedImage中构造函数BufferedImage(int width, int height, int imageType)的源码,耐心研究一下就明白了。

你可能感兴趣的:(java)