JavaSE-向数据库保存图片并且读取

本文介绍了一个使用JavaSE进行数据库图片存储与读取的例子。通过SqlDemo类实现了向数据库中插入图片数据,并通过MainImage类展示从数据库读取的图片。此过程涉及到了文件流操作、SQL语句的准备及执行。

JavaSE-向数据库保存图片并且读取


这里写图片描述


SqlDemo.java

package com.xieth.sql;

import java.io.File;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class SqlDemo {

    private Connection conn = null;
    private PreparedStatement ps = null;

    public SqlDemo() throws ClassNotFoundException, SQLException {
        String driverClass = "com.mysql.jdbc.Driver";
        String jdbcUrl = "jdbc:mysql:///person";// localhost可以省略
        String user = "root";
        String password = "12345";

        Class.forName(driverClass); // 注册加载驱动

        conn = DriverManager.getConnection(jdbcUrl, user, password);

        System.out.println(conn); // 获取数据库连接
    }

    private void insertData() throws SQLException {
        String path = "image/Head.jpg";

        FileInputStream input = null;
        byte[] buffer = null;

        // 定义缓冲区
        try {
            input = new FileInputStream(new File(path));
            // 构建文件输入流对象
            buffer = new byte[input.available()];
            // 构建缓冲区
            input.read(buffer);
            // 将图标读入缓冲区
        } catch (Exception e) {
        } finally {
            if (input != null) {
                try {
                    input.close(); // 关闭文件输入流
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        String sql = "insert into user(img)" + "values(?)";

        ps = conn.prepareStatement(sql);

        ps.setBytes(1, buffer);

        int count = ps.executeUpdate();

        if (count > 0)
            System.out.println("成功");
        else
            System.out.println("失败");

    }


    private byte[] getImage() throws SQLException{
        byte[] buffer = null;

        String sql = "select img from user";

        ps = conn.prepareStatement(sql);

        ResultSet rs = ps.executeQuery();

        if (rs.next())
            buffer = rs.getBytes("img");

        return buffer;
    }

    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        SqlDemo s = new SqlDemo();
        byte[] b = s.getImage();
        new MainImage(b);
    }

}

MainImage.java

package com.xieth.sql;

import java.awt.*;
import javax.swing.*;

public class MainImage extends JFrame {

    private JLabel label = null;
    private JPanel panel = null;
    private byte[] buffer = null;

    public MainImage(byte[] buffer) {
        super("Image");
        this.buffer = buffer;
        panel = new JPanel();
        init();
    }

    private void init() {
        this.setSize(540, 390); // 设置长度和宽度
        this.setLayout(null); // 自定义布局
        this.setLocationRelativeTo(this.getOwner()); // 设置窗体的相对位置
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        panel.setSize(540, 400);
        label = new JLabel(new ImageIcon(buffer));
        panel.add(label);
        add(panel);
        this.setVisible(true);

    }

}

数据库里面的数据:

这里写图片描述


运行效果:
成功读取数据库里面的图片
这里写图片描述


可以使用zxing库生成二维码,再将二维码图片转化为字节数组,存入数据库中。 下面给出一个简单的示例代码: 1. 添加依赖 在pom.xml中添加以下依赖: ```xml <dependency> <groupId>com.google.zxing</groupId> <artifactId>core</artifactId> <version>3.4.0</version> </dependency> <dependency> <groupId>com.google.zxing</groupId> <artifactId>javase</artifactId> <version>3.4.0</version> </dependency> ``` 2. 编写生成二维码的方法 ```java public static byte[] generateQRCode(String content) throws WriterException, IOException { int width = 200; // 二维码图片宽度 int height = 200; // 二维码图片高度 // 设置二维码参数 Map<EncodeHintType, Object> hints = new HashMap<>(); hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); hints.put(EncodeHintType.MARGIN, 1); // 生成二维码 BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints); // 将BitMatrix转换为BufferedImage BufferedImage image = MatrixToImageWriter.toBufferedImage(bitMatrix); // 将BufferedImage转换为字节数组 ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ImageIO.write(image, "png", outputStream); byte[] bytes = outputStream.toByteArray(); return bytes; } ``` 3. 在Controller中调用方法并保存数据库 ```java @Controller public class QRCodeController { @Autowired private QRCodeService qrCodeService; @RequestMapping("/generateQRCode") public String generateQRCode(Model model, @RequestParam String content) { try { byte[] bytes = QRCodeUtil.generateQRCode(content); qrCodeService.saveQRCode(bytes); } catch (Exception e) { e.printStackTrace(); } return "success"; } } ``` ```java @Service public class QRCodeServiceImpl implements QRCodeService { @Autowired private QRCodeMapper qrCodeMapper; @Override public void saveQRCode(byte[] bytes) { QRCode qrCode = new QRCode(); qrCode.setBytes(bytes); qrCodeMapper.insert(qrCode); } } ``` 4. 在页面中显示二维码 在页面中使用img标签,并将src属性设置为一个servlet或controller的路径,通过读取数据库中的二维码字节数组生成二维码图片并显示。 ```html <img src="${pageContext.request.contextPath}/showQRCode?id=${qrCode.id}"> ``` ```java @Controller public class QRCodeController { @Autowired private QRCodeService qrCodeService; @GetMapping("/showQRCode") public void showQRCode(HttpServletRequest request, HttpServletResponse response, Long id) { try { QRCode qrCode = qrCodeService.getQRCodeById(id); byte[] bytes = qrCode.getBytes(); response.setContentType("image/png"); ServletOutputStream outputStream = response.getOutputStream(); outputStream.write(bytes); outputStream.flush(); outputStream.close(); } catch (Exception e) { e.printStackTrace(); } } } ``` ```java public interface QRCodeMapper { void insert(QRCode qrCode); QRCode selectById(Long id); } ``` ```java public class QRCode { private Long id; private byte[] bytes; // getter/setter方法 } ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值