嗨,有人可以解释一下如何将图像数据转换为java中的字节数组我正在尝试这样做。我不需要在这里使用缓冲图像。
File file = new File("D:/img.jpg");
FileInputStream imageInFile = new FileInputStream(file);
byte imageData[] = new byte[(int) file.length()];
imageInFile.read(imageData);
答案 0 :(得分:0)
您也可以使用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();
答案 1 :(得分:0)
或者您可以使用:
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();
}
}