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();
                }
            }
        }
    }
}

 

  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要将图片上传到 PostgreSQL 数据库中,你需要做以下几个步骤: 1. 创建数据库表格:创建一个表格来存储图片信息,包括图片名称、图片类型以及二进制数据字段。 2. 创建 Java 应用程序:创建一个 Java 应用程序,用于将图片转换为二进制数据并将其插入到数据库中。 3. 读取图片:使用 Java 应用程序读取要上传的图片文件。 4. 转换为二进制数据:使用 Java 应用程序将读取图片文件转换为二进制数据。 5. 连接到数据库:使用 Java 应用程序连接到 PostgreSQL 数据库。 6. 插入数据:将二进制数据插入到数据库表格中的二进制数据字段中。 下面是一个简单的 Java 代码示例,可以将图片上传到 PostgreSQL 数据库中: ```java import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; public class ImageUpload { public static void main(String[] args) { String url = "jdbc:postgresql://localhost:5432/dbname"; String username = "username"; String password = "password"; try { Class.forName("org.postgresql.Driver"); Connection conn = DriverManager.getConnection(url, username, password); File imageFile = new File("image.jpg"); // Read image file InputStream inputStream = new FileInputStream(imageFile); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); byte[] buffer = new byte[4096]; int bytesRead = -1; while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } byte[] imageBytes = outputStream.toByteArray(); // Insert image into database String sql = "INSERT INTO images(name, type, data) VALUES(?, ?, ?)"; PreparedStatement statement = conn.prepareStatement(sql); statement.setString(1, imageFile.getName()); statement.setString(2, "image/jpeg"); statement.setBytes(3, imageBytes); statement.executeUpdate(); System.out.println("Image uploaded successfully."); conn.close(); } catch (Exception e) { e.printStackTrace(); } } } ``` 你需要将上述代码中的 `dbname`、`username` 和 `password` 替换为实际的值,并将 `image.jpg` 替换为要上传的图片文件名。这个示例假设数据库表格的名称为 `images`,并且包含三个字段:`name`、`type` 和 `data`。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值