如何在java中将图像转换为字节数组?(不使用缓冲图像)

如何在java中将图像转换为字节数组?(不使用缓冲图像),java,image,byte,bytearray,Java,Image,Byte,Bytearray,大家好,请告诉我如何用java将图像数据转换成字节数组,我正在这样做,我不需要在这里使用缓冲图像 File file = new File("D:/img.jpg"); FileInputStream imageInFile = new FileInputStream(file); byte imageData[] = new byte[(int) file.length()]; imageInFile.read(imageData); 您还可以

大家好,请告诉我如何用java将图像数据转换成字节数组,我正在这样做,我不需要在这里使用缓冲图像

File file = new File("D:/img.jpg");
        FileInputStream imageInFile = new FileInputStream(file);
        byte imageData[] = new byte[(int) file.length()];
        imageInFile.read(imageData);

您还可以使用FileInputStream转换图像数据

File file = new File("D:\\img.jpg");

FileInputStream fis = new FileInputStream(file);
 //Now try to create FileInputStream which obtains input bytes from a file. 
 //FileInputStream is meant for reading streams of raw bytes,in this case its image data. 
 //For reading streams of characters, consider using FileReader.

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] buf = new byte[1024];
        try {
            for (int readNum; (readNum = fis.read(buf)) != -1;) {
                //Now Write to this byte array output stream
                bos.write(buf, 0, readNum); 
                System.out.println("read " + readNum + " bytes,");
            }
        } catch (IOException ex) {
            Logger.getLogger(ConvertImage.class.getName()).log(Level.SEVERE, null, ex);
        }

        byte[] bytes = bos.toByteArray();
或者您可以使用:

Image image = Toolkit.getDefaultToolkit().getImage("D:/img.jpg");
byte[] imageBytes = getImageBytes(image);


private byte[] getImageBytes(Image image) throws IOException {
    try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
        ImageIO.write(image, "bmp", baos);
        baos.flush();
        return baos.toByteArray();
    }
}

如果您希望对图像进行解码,以便访问像素数据,那么通过
缓冲区图像
可以更容易地访问,您能告诉我,字节[]是什么吗?它是从图像中读取的字节吗(就像从任何原始文件中读取字节一样)?或者你想从每个像素中获取字节?直接像上面那样转换图像和将缓冲图像转换为字节数组有什么用。