java+pgsql实现保存图片到数据库,以及读取数据库存储的图片;java将图片保存到本地、保存到数据库、java将图片保存到本地并保存到数据库、java从数据库postgresql读取图片
java将图片保存到本地;
pom.xml
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.4.7</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
java类-将图片直接保存到本地
String fileUrl = "http://image.nmc.cn/assets/img/w/40x40/3/0.png";
//将文件下载后保存在E盘,返回结果为下载文件大小
long size = HttpUtil.downloadFile(fileUrl, FileUtil.file("e:/"));
System.out.println("Download size: " + size);
java类-将图片直接保存到数据库
HttpResponse maiImg = HttpRequest.get("http://image.nmc.cn/assets/img/w/40x40/3/0.png").execute();
InputStream maiImgInpuStream = maiImg.bodyStream(); //图片转换成流
jdbc往数据库汇总插入数据
//pstmt.setString(2, mai.getFileName());
//pstmt.setString(3, mai.getUrl());
pstmt.setBinaryStream(4, maiImgInpuStream, maiImgInpuStream.available());
java类将图片下载到本地,并将图片保存到数据库
逻辑:运用方法一,把图片下载到本地,在从本地读取图片为流的格式,然后把图片保存到数据库
String fileUrl = "http://image.nmc.cn/assets/img/w/40x40/3/0.png";
//将文件下载后保存在E盘,返回结果为下载文件大小
long size = HttpUtil.downloadFile(fileUrl, FileUtil.file("e:/"));
System.out.println("Download size: " + size);
try {
FileInputStream fis = new FileInputStream(new File("e://3.png"));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
//jdbc插入数据
pstmt.setBinaryStream(3,fis,fis.avaliable())
java类从数据库中读取图片
// 读取数据库中图片
public static void readDBImage() {
String targetPath = "D:/image/1.png";
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = JdbcUtil.getConn();
String sql = "select * from photo where id =?";
ps = conn.prepareStatement(sql);
ps.setInt(1,1);
rs = ps.executeQuery();
while (rs.next()) {
InputStream in = rs.getBinaryStream("photo");
ImageUtil.readBinImage(in, targetPath);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
DBUtil.closeConn(conn);
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (ps != null) {
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
public class ImageUtil {
// 读取本地图片获取输入流
public static FileInputStream readImage(String path) throws IOException {
return new FileInputStream(new File(path));
}
// 读取表中图片获取输出流
public static void readBinImage(InputStream in, String targetPath) {
File file = new File(targetPath);
String path = targetPath.substring(0, targetPath.lastIndexOf("/"));
if (!file.exists()) {
new File(path).mkdir();
}
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
int len = 0;
byte[] buf = new byte[1024];
while ((len = in.read(buf)) != -1) {
fos.write(buf, 0, len);
}
fos.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != fos) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
还没有评论,来说两句吧...