gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 14:50:08 25 4
gpt4 key购买 nike

大家好,请解释一下如何在 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();

关于java - 如何在java中将图像转换为字节数组?(不使用bufferedimage),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23883383/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com