从mysql数据库检索图像以使用java存储在本地磁盘上的问题

时间:2015-12-16 19:53:53

标签: java mysql ubuntu-14.04

我将图像转换为<form action="https://google.com/search" method="GET"> <input name="q" type="text"/> <input type="submit" value="Submit Google" onclick="this.form.action='https://google.com/search'"/> <input type="submit" value="Submit Bing" onclick="this.form.action='https://bing.com/search'"/> </form> 然后bytes[]后使用java将图像保存到mysql数据库。图片格式为Blob 尝试从mysql数据库中检索图像并将其转换为图像文件以保存在本地磁盘上。

将mysql Resultset迭代为:

png

但它给了我错误:

while(rs.next())
{
ByteArrayInputStream bis = new ByteArrayInputStream(rs.getBytes("image"));

Iterator<?> readers = ImageIO.getImageReadersByFormatName("png");
ImageReader reader = (ImageReader) readers.next();
Object source = bis; 

ImageInputStream iis = ImageIO.createImageInputStream(source); 
reader.setInput(iis, true);
ImageReadParam param = reader.getDefaultReadParam();

Image image= reader.read(0, param);
BufferedImage bufferedImage = new BufferedImage(image1.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_RGB);

Graphics2D g2 = bufferedImage.createGraphics();
g2.drawImage(image, null, null);

File imageFile = new File(rs.getInt("id")+".png");
ImageIO.write(bufferedImage, "png", imageFile);
}

由于:

导致
javax.imageio.IIOException: I/O error reading PNG header!

我是java的新手。我用Google搜索但没有找到任何令人满意的解决方案。 任何人都可以帮我解决它或任何其他更好的解决方案从数据库检索图像和存储在本地磁盘???

1 个答案:

答案 0 :(得分:0)

我找到了解决方案。问题在我的代码中。这是正确的代码,我用来从数据库中获取图像并存储为图像文件

sql="select * from image_data where image_id="+image_id;        
        rs = this.runSimpleQuery(sql);
        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"))); 
        }