byte[] 到 jpg 图片?
byte[] to jpg image?
我有以下代码,将图像转换为字节[]:
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();
这段代码工作得很好,至少我得到了一个包含不同值的字节数组。但现在困难的部分来了:byte[] 必须再次重建为图像。以下代码不起作用,ImageIO.read(...)
returns null。我阅读了文档,但仍然找不到要更改的内容以使代码按照我想要的方式运行。
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");
}
}
根据您的需要进行修改。
尝试阅读 ImageIO.read()
上的 ByteArrayInputStream
而不是 ByteArrayOutputstream
。
我有以下代码,将图像转换为字节[]:
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();
这段代码工作得很好,至少我得到了一个包含不同值的字节数组。但现在困难的部分来了:byte[] 必须再次重建为图像。以下代码不起作用,ImageIO.read(...)
returns null。我阅读了文档,但仍然找不到要更改的内容以使代码按照我想要的方式运行。
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");
}
}
根据您的需要进行修改。
尝试阅读 ImageIO.read()
上的 ByteArrayInputStream
而不是 ByteArrayOutputstream
。