如何在 Java 中将 ImageInputStream 转换为 BufferedImage?
How to convert ImageInputStream to BufferedImage in Java?
我正在尝试从 mysql 数据库中检索图像 blob 并将其转换回图像文件。迭代 mysql 结果集为:
while(rs.next())
{
byte[] byteArray=rs.getBytes("image_blob");
InputStream in=new ByteArrayInputStream(byteArray);
ImageInputStream is = ImageIO.createImageInputStream(in);
BufferedImage image_Bf=ImageIO.read(is);
ImageIO.write(image_Bf, "png",new File("images/"+rs.getString("name")));
}
当我编译 运行 我的 java class 时它给我错误:
java.lang.IllegalArgumentException: image == null!
我该如何解决这个问题?
ImageIO.read(is);
returns 对你无效。 Javadoc 说这意味着它找不到合适的 ImageReader
,这似乎是输入无效的标志。
实际上,您的错误在这个字符串中:rs.getBytes("name");
。您没有将图像内容发送到 byteArray
,而是以字节形式发送图像 name,因此 ImageIO.read
失败。
编辑:
如果仍然失败并出现同样的错误,那么您将不得不进行调试。尝试将字节缓冲区直接输出到文件。这样你能得到有效的图像吗?我很确定 ImageIO
需要正确的图像来操作并转换为 PNG。
while(rs.next())
{
byte[] byteArray=rs.getBytes("image_blob");
FileOutputStream fos = new FileOutputStream("images/"+rs.getString("name"));
fos.write(byteArray);
fos.close();
}
成功解决这个issue.Here是从数据库中检索图像的正确代码
while (rs.next())
{
Blob image_blob=rs.getBlob("image_100x100");
int blobLength = (int) image_blob.length();
byte[] blobAsBytes = image_blob.getBytes(1, blobLength);
InputStream in=new ByteArrayInputStream( blobAsBytes );
BufferedImage image_bf = ImageIO.read(in);
ImageIO.write(image_bf, "PNG", new File(folder_path+"/"+rs.getString("name")));
}
我正在尝试从 mysql 数据库中检索图像 blob 并将其转换回图像文件。迭代 mysql 结果集为:
while(rs.next())
{
byte[] byteArray=rs.getBytes("image_blob");
InputStream in=new ByteArrayInputStream(byteArray);
ImageInputStream is = ImageIO.createImageInputStream(in);
BufferedImage image_Bf=ImageIO.read(is);
ImageIO.write(image_Bf, "png",new File("images/"+rs.getString("name")));
}
当我编译 运行 我的 java class 时它给我错误:
java.lang.IllegalArgumentException: image == null!
我该如何解决这个问题?
ImageIO.read(is);
returns 对你无效。 Javadoc 说这意味着它找不到合适的 ImageReader
,这似乎是输入无效的标志。
实际上,您的错误在这个字符串中:rs.getBytes("name");
。您没有将图像内容发送到 byteArray
,而是以字节形式发送图像 name,因此 ImageIO.read
失败。
编辑:
如果仍然失败并出现同样的错误,那么您将不得不进行调试。尝试将字节缓冲区直接输出到文件。这样你能得到有效的图像吗?我很确定 ImageIO
需要正确的图像来操作并转换为 PNG。
while(rs.next())
{
byte[] byteArray=rs.getBytes("image_blob");
FileOutputStream fos = new FileOutputStream("images/"+rs.getString("name"));
fos.write(byteArray);
fos.close();
}
成功解决这个issue.Here是从数据库中检索图像的正确代码
while (rs.next())
{
Blob image_blob=rs.getBlob("image_100x100");
int blobLength = (int) image_blob.length();
byte[] blobAsBytes = image_blob.getBytes(1, blobLength);
InputStream in=new ByteArrayInputStream( blobAsBytes );
BufferedImage image_bf = ImageIO.read(in);
ImageIO.write(image_bf, "PNG", new File(folder_path+"/"+rs.getString("name")));
}