簡體   English   中英

如何使用java從數據庫中檢索圖像文件

[英]How to retrieve image file from database using java

我可以將圖像文件存儲到數據庫中,但是如何將圖像作為文件獲取並使用 java 進行預覽,就像 quikr 圖像上傳

以下代碼將圖像存儲和檢索到 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();
    }
}

將圖像檢索到數據庫中

下面的代碼將從數據庫中檢索圖像並將其保存在@ location "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();
    }
}

Image轉換為Bytes ,保存到 db 或從 db 恢復以字節為單位

檢查此答案以轉換為字節或此答案就像您的問題

檢查字節到圖像操作

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM