java:从sRGB字节流(byte[])创建BufferedImage
2016-07-10 16:44
393 查看
有时候我们需要从字节流
不过你看到这个构造函数,所要求的参数完全不是
以RGB格式的图像矩阵数据为例,首先要构造 sRGB标准的
下面是完整的代码:
如果你的图像数据是Gray或ARGB格式的,如何构造一个
其实也差不多,
可以参照
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对世界各个时区(TimeZone)的通用转换处理方法(转载)
- java-注解annotation
- java-模拟tomcat服务器
- java-用HttpURLConnection发送Http请求.
- java-WEB中的监听器Lisener
- 使用C++实现JNI接口需要注意的事项
- Android IPC进程间通讯机制
- Android Native 绘图方法
- Android java 与 javascript互访(相互调用)的方法例子
- 介绍一款信息管理系统的开源框架---jeecg
- 聚类算法之kmeans算法java版本
- java实现 PageRank算法
- PropertyChangeListener简单理解
- c++11 + SDL2 + ffmpeg +OpenAL + java = Android播放器
- 插入排序
- 冒泡排序