将字节数组转换为png

我有一个使用以下代码从图像中获取的字节数组。

String path = "/home/mypc/Desktop/Steganography/image.png"; File file = new File(path); BufferedImage bfimage = ImageIO.read(file); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(bfimage, "png", baos); baos.flush(); byte[] img_in_bytes = baos.toByteArray(); baos.close(); 

然后我使用以下代码将这些字节转换回png图像。

 BufferedImage final_img = ImageIO.read(new ByteArrayInputStream(img_in_bytes)); File output_file = new File("Stegano2.png"); ImageIO.write(final_img, "png", output_file); 

如果我只执行这段代码就完全没问题。 但是,如果我尝试修改其中的一些字节,请这样说:

  Insert_number_to_image(image_in_bytes, 10); 

我的方法“Inset_number_to_image”是这样的:

 static void Insert_number_to_image(byte[] image, int size){ byte[] size_in_byte = new byte[4]; size_in_byte[0] = (byte)(size >>> 0); size_in_byte[1] = (byte)(size >>> 8); size_in_byte[2] = (byte)(size >>> 16); size_in_byte[3] = (byte)(size >>> 24); byte temp; int count = 0; for(int i=0; i<4; i++) { for(int j=0; j>> j); temp = (byte)(temp & 1); if(temp == 1) { image[count] = (byte)(image[count] | 1); } else if(temp == 0) { image[count] = (byte)(image[count] & (byte)(~(1))); } count++; } } } 

然后,当我使用上面提到的相同代码将修改后的字节数组保存为png图像时,我收到此错误:

 Exception in thread "main" java.lang.IllegalArgumentException: image == null! at javax.imageio.ImageTypeSpecifier.createFromRenderedImage(ImageTypeSpecifier.java:925) at javax.imageio.ImageIO.getWriter(ImageIO.java:1591) at javax.imageio.ImageIO.write(ImageIO.java:1520) at Steganography.main(Steganography.java:211) 

您正在使用的是PNG图像的原始字节流。 PNG是一种压缩格式 ,其中字节流不直接反映任何像素值,甚至更改一个字节可能会不可逆转地破坏文件。

你想要的是将像素数据提取到一个字节数组

 byte[] pixels = ((DataBufferByte) img.getRaster().getDataBuffer()).getData(); 

现在您可以根据需要修改像素值。 当您准备将其保存回文件时, 将像素字节数组转换为BufferedImage,方法是将像素数组放入DataBufferByte对象并将其传递给WriteableRaster ,然后用于创建BufferedImage

您的方法适用于原始字节流直接表示像素的格式,例如BMP 。 但是,即使这样,您也必须跳过前几个字节以避免损坏标头。