how to convert image to byte array in java? [dupli

2019-01-02 18:06发布

This question already has an answer here:

I want to convert an image to byte array and vice versa. Here, the user will enter the name of the image (.jpg) and program will read it from the file and will convert it to a byte array.

9条回答
墨雨无痕
2楼-- · 2019-01-02 18:26

If you are using JDK 7 you can use the following code..

import java.nio.file.Files;
import java.io.File;

File fi = new File("myfile.jpg");
byte[] fileContent = Files.readAllBytes(fi.toPath())
查看更多
时光乱了年华
3楼-- · 2019-01-02 18:30

BufferedImage consists of two main classes: Raster & ColorModel. Raster itself consists of two classes, DataBufferByte for image content while the other for pixel color.

if you want the data from DataBufferByte, use:

public byte[] extractBytes (String ImageName) throws IOException {
 // open image
 File imgPath = new File(ImageName);
 BufferedImage bufferedImage = ImageIO.read(imgPath);

 // get DataBufferBytes from Raster
 WritableRaster raster = bufferedImage .getRaster();
 DataBufferByte data   = (DataBufferByte) raster.getDataBuffer();

 return ( data.getData() );
}

now you can process these bytes by hiding text in lsb for example, or process it the way you want.

查看更多
倾城一夜雪
4楼-- · 2019-01-02 18:37

Using RandomAccessFile would be simple and handy.

RandomAccessFile f = new RandomAccessFile(filepath, "r");
byte[] bytes = new byte[(int) f.length()];
f.read(bytes);
f.close();
查看更多
何处买醉
5楼-- · 2019-01-02 18:38
File fnew=new File("/tmp/rose.jpg");
BufferedImage originalImage=ImageIO.read(fnew);
ByteArrayOutputStream baos=new ByteArrayOutputStream();
ImageIO.write(originalImage, "jpg", baos );
byte[] imageInByte=baos.toByteArray();
查看更多
冷夜・残月
6楼-- · 2019-01-02 18:39

I think the best way to do that is to first read the file into a byte array, then convert the array to an image with ImageIO.read()

查看更多
梦醉为红颜
7楼-- · 2019-01-02 18:41

java.io.FileInputStream is what you're looking for :-)

查看更多
登录 后发表回答