一、MySQL存储图片的原理
- TINYBLOB:最大长度255 bytes
- BLOB:最大长度65535 bytes(KB)
- MEDIUMBLOB:最大长度16777215 bytes(16MB)
- LONGBLOB:最大长度4GB
二、Java整合MySQL存储图片步骤
1. 创建数据库表
CREATE TABLE images (
id INT PRIMARY KEY AUTO_INCREMENT,
image_name VARCHAR(255),
image_data LONGBLOB
);
2. Java代码连接MySQL数据库
使用JDBC(Java Database Connectivity)连接MySQL数据库,并获取连接对象。以下是一个示例代码:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class MySQLConnection {
public static Connection getConnection() throws SQLException {
String url = "jdbc:mysql://localhost:3306/your_database?useSSL=false&serverTimezone=UTC";
String user = "root";
String password = "your_password";
return DriverManager.getConnection(url, user, password);
}
}
3. Java代码上传图片
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.io.InputStream;
public class ImageUploader {
public static void uploadImage(String imagePath) throws SQLException {
Connection conn = MySQLConnection.getConnection();
String sql = "INSERT INTO images (image_name, image_data) VALUES (?, ?)";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, imagePath.substring(imagePath.lastIndexOf("/") + 1));
try (InputStream in = new java.io.FileInputStream(imagePath)) {
pstmt.setBlob(2, in);
}
pstmt.executeUpdate();
pstmt.close();
conn.close();
}
}
4. Java代码读取图片
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.io.InputStream;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
public class ImageRetriever {
public static BufferedImage getImage(int imageId) throws SQLException {
Connection conn = MySQLConnection.getConnection();
String sql = "SELECT image_data FROM images WHERE id = ?";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, imageId);
BufferedImage image = null;
try (ResultSet rs = pstmt.executeQuery()) {
if (rs.next()) {
InputStream in = rs.getBinaryStream("image_data");
image = ImageIO.read(in);
}
}
pstmt.close();
conn.close();
return image;
}
}