【发布时间】:2016-10-17 20:52:26
【问题描述】:
我可以将图像文件存储到数据库,但是如何将图像作为文件获取并使用 java 进行预览,这就像 quikr 图像上传
【问题讨论】:
-
你试过什么?你得到什么?图片是如何保存在数据库中的,base 64?
-
图像保存为二进制,我可以将其转换为图像文件
标签: java
我可以将图像文件存储到数据库,但是如何将图像作为文件获取并使用 java 进行预览,这就像 quikr 图像上传
【问题讨论】:
标签: java
【讨论】:
以下代码将存储和检索图像到 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();
}
}
【讨论】: