简体   繁体   中英

byte[] to jpg image?

I have the following code, that transforms an Image into a byte[]:

BufferedImage image = ImageIO.read(new File("Path/To/Custom/image.jpg"));
ByteArrayOutputStream baos=new ByteArrayOutputStream(1000);
ImageIO.write(image, "jpg", baos);
byte[] imageBytes = baos.toByteArray();

This code works totally fine, at least I get a byte array containing different values. But now comes the difficult part: The byte[] has to be reconstructed into am image again. The following code does not work, ImageIO.read(...) returns null. I read the documentation, but still I can not find out what to change so that the code functions in the way I want it to.

ByteArrayInputStream ba = new ByteArrayInputStream(imageBytes);
BufferedImage image = ImageIO.read(ba);
//image is always null, no matter what the stream or the byte values are.
import java.io.ByteArrayOutputStream;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
public class ByteArrayToImage {
   public static void main(String args[]) throws Exception {
      BufferedImage bImage = ImageIO.read(new File("sample.jpg"));
      ByteArrayOutputStream bos = new ByteArrayOutputStream();
      ImageIO.write(bImage, "jpg", bos );
      byte [] data = bos.toByteArray();
      ByteArrayInputStream bis = new ByteArrayInputStream(data);
      BufferedImage bImage2 = ImageIO.read(bis);
      ImageIO.write(bImage2, "jpg", new File("output.jpg") );
      System.out.println("image created");
   }
}

Modify this to your needs.

Try reading an ByteArrayInputStream on ImageIO.read() not an ByteArrayOutputstream .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM