【问题标题】:how to convert image to byte array in java?(With out using buffered image)如何在java中将图像转换为字节数组?(不使用缓冲图像)
【发布时间】:2014-07-16 00:14:21
【问题描述】:

您好,谁能解释一下如何在java中将图像数据转换为字节数组,我正在尝试这样。我不需要在这里使用缓冲图像。

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

【问题讨论】:

  • 如果您想解码图像以便访问像素数据,通过BufferedImage 更容易
  • 你能告诉我,byte[] 是什么?是从图像中读取的字节吗(就像您想从任何普通文件中读取字节一样)?还是你想从每个像素中获取字节?

标签: java image byte bytearray


【解决方案1】:

或者你可以使用:

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();
    }
}

【讨论】:

    【解决方案2】:

    您也可以使用 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();
    

    【讨论】:

    • 像上面一样直接转换图像并将缓冲图像转换为字节数组有什么用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多