您的位置:首页 > Web前端

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

2016-07-10 16:44 393 查看
有时候我们需要从字节流
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 RGB Image jni