[英]getting a bufferedImage from a bytearray
I am trying to get back a bufferedImage
from array of bytes
, but I am getting an error saying bufferedimage is null
. 我试图从
array of bytes
取回bufferedImage
,但是却收到一条错误消息,说bufferedimage is null
。 I actually tried several ways, everything ended up in the same way. 我实际上尝试了几种方法,所有操作都以相同的方式结束。 Here goes my code:
这是我的代码:
1) 1)
byte[] arr = Base64.decode(base64String);
BufferedImage bImageFromConvert =ImageIO.read(new ByteArrayInputStream(arr));
2) 2)
InputStream in = new ByteArrayInputStream(arr);
BufferedImage bImageFromConvert = ImageIO.read(in);
I am pretty sure my byte array contains data and I think ImageIO.read()
is where my code goes wrong. 我很确定我的字节数组包含数据,并且我认为
ImageIO.read()
是我的代码出问题的地方。
Try this code.Maybe it works. 试试这个代码,也许行得通。 It worked for me.
它为我工作。
byte[] aByteArray = {};
int width = ;
int height = ;
DataBuffer buffer = new DataBufferByte(aByteArray, aByteArray.length);
WritableRaster raster = Raster.createInterleavedRaster(buffer, width, height, 3 * width, 3, new int[] {0, 1, 2}, (Point)null);
ColorModel cm = new ComponentColorModel(ColorModel.getRGBdefault().getColorSpace(), false, true, Transparency.OPAQUE, DataBuffer.TYPE_BYTE);
BufferedImage image = new BufferedImage(cm, raster, true, null);
Just add the byte, width and height to code and customize it. 只需在代码中添加字节,宽度和高度并对其进行自定义即可。
The error is in your BufferedImage
to Base64
encode method as you have posted in the comments. 如注释中所述,该错误出在
BufferedImage
to Base64
编码方法中。
You are never writing the BufferedImage
to the ByteArrayOutputStream
. 您永远不会将
BufferedImage
写入ByteArrayOutputStream
。 Therefore the Base64 string is empty, and reading the empty string produces a null
BufferedImage
. 因此,Base64字符串为空,读取空字符串会生成一个
null
BufferedImage
。
You should use this code to encode your image: 您应该使用以下代码对图像进行编码:
BufferedImage originalImage = ImageIO.read(new File("G:\\a.jpg"));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write( originalImage, "jpg", baos );
String base64String=Base64.encode(baos.toByteArray());
To decode the image use this code: 要解码图像,请使用以下代码:
byte[] arr = Base64.decode(base64String);
BufferedImage bImageFromConvert =ImageIO.read(new ByteArrayInputStream(arr));
System.out.println(bImageFromConvert.getWidth());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.