<span style="white-space:pre"> </span>String imageFile="E:/Penguins.jpg";
// String imageFile="E:/aa.gif";
File file = new File(imageFile);
byte[] bytes = null;
if(file!=null)
{
InputStream is = new FileInputStream(file);
int length = (int) file.length();
if(length>Integer.MAX_VALUE) //当文件的长度超过了int的最大值
{
System.out.println("this file is max ");
}
bytes = new byte[length];
int offset = 0;
int numRead = 0;
while(offset<bytes.length&&(numRead=is.read(bytes,offset,bytes.length-offset))>=0)
{
offset+=numRead;
}
//如果得到的字节长度和file实际的长度不一致就可能出错了
if(offset<bytes.length)
{
System.out.println("file length is error");
}
is.close();
}
System.out.println(bytes);
下面就是进行转换成Image
FileOutputStream fout=new FileOutputStream("D://");
fout.write(bytes);
fout.close();

本文介绍如何使用Java代码读取本地图片文件到字节数组,并将该字节数组写入新的文件中。通过FileInputStream读取文件,并检查文件长度是否超过int类型的最大值。此外,还展示了如何验证读取的字节数组长度与原始文件长度的一致性。
1508

被折叠的 条评论
为什么被折叠?



