【问题标题】:How to retrieve image file from database using java如何使用java从数据库中检索图像文件
【发布时间】:2016-10-17 20:52:26
【问题描述】:

我可以将图像文件存储到数据库,但是如何将图像作为文件获取并使用 java 进行预览,这就像 quikr 图像上传

【问题讨论】:

  • 你试过什么?你得到什么?图片是如何保存在数据库中的,base 64?
  • 图像保存为二进制,我可以将其转换为图像文件

标签: java


【解决方案1】:

Image 转换为Bytes,保存到数据库或从数据库恢复以字节为单位

检查this answer 以转换为字节 或this answer 这就像你的问题

检查this 的字节到图像操作

【讨论】:

  • 如何将字节转为图片并预览?
【解决方案2】:

以下代码将存储和检索图像到 MySql DB。

将图像存储到数据库中

 public static void main(String args[]){
    try{
    // DB connection
        Class.forName("com.mysql.jdbc.Driver");
        Connection con=DriverManager.getConnection("jdbc:mysql://localhost/your db name","root","root");

        File file=new File("E:\\sample_image.png");
        FileInputStream fis=new FileInputStream(file);

    //Insert image into db
        PreparedStatement ps=con.prepareStatement("insert into image_table (name,image) values(?,?)"); 
        ps.setString(1,"image 1");
        ps.setBinaryStream(2,fis,(int)file.length());
        ps.executeUpdate();

        ps.close();
        fis.close();
        con.close();
    }catch(Exception e){
        e.printStackTrace();
    }
}

将图像检索到数据库中

以下代码将从数据库中检索图像并将其保存在@位置“E:\sample_image.png”。

public static void main(String args[]){
    try{
    // DB connection
        Class.forName("com.mysql.jdbc.Driver");
        Connection con=DriverManager.getConnection("jdbc:mysql://localhost/your db name","root","root");

        File file=new File("E:\\sample_image.png");
        FileOutputStream fos=new FileOutputStream(file);
        byte b[];
        Blob blob;

        PreparedStatement ps=con.prepareStatement("select * from image_table"); 
        ResultSet rs=ps.executeQuery();

        while(rs.next()){
            blob=rs.getBlob("image");
            b=blob.getBytes(1,(int)blob.length());
            fos.write(b);
        }

        ps.close();
        fis.close();
        con.close();
    }catch(Exception e){
        e.printStackTrace();
    }
}

【讨论】:

  • 它是网络应用程序,我不想保存在本地内存中,我想恢复字节并将其转换为图像文件。但不保存在本地内存中
猜你喜欢
  • 2019-11-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-01
  • 2013-03-17
  • 2014-02-28
  • 2013-01-08
相关资源
最近更新 更多