java+mysql(blob类型)图片存取

本文详细介绍使用Java和MySQL进行图片存储与检索的过程。通过代码示例,展示如何将图片文件转换为字节流并存入数据库的BLOB字段,以及如何从数据库中读取字节流并将其转换回图片文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

java+mysql将图片存到数据库blob类型字段,并取出成文件。
直接上代码吧。

代码

package wfb.testImage;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class imageTest {
	private String className = "com.mysql.jdbc.Driver";
	private String url = "jdbc:mysql://ip地址:3306/数据库名";
	private String user = "数据库用户名";
	private String password = "对应密码";
	private Connection conn = null;
	@Before
	public void before() throws Exception {
		Class.forName(className);
		conn = DriverManager.getConnection(url, user, password);
	}
	@After
	public void after() throws Exception{
		conn.close();
	}
	
	@Test
	public void test() throws Exception {//将图片存到数据库
		File file = new File("E:\\图片\\辉夜姬.jpg");
		FileInputStream fis = new FileInputStream(file);
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		int len = -1;
		byte[] buf = new byte[1024];
		while((len = fis.read(buf)) != -1) {//汇总字节流到内存
			baos.write(buf, 0, len);
		}
		baos.close();
		fis.close();
		byte[] bytes = baos.toByteArray();//从内存取出字节流数组
		Blob pic = conn.createBlob();
		pic.setBytes(1, bytes);//把字节流设置给blob类
		String sql = "insert into images(image) values (?)";
		PreparedStatement ppst = conn.prepareStatement(sql);
		ppst.setBlob(1, pic);
		ppst.execute();
		ppst.close();
	}

	@Test
	public void test2() throws Exception {//从数据库取出图片成图片
		String sql = "select image from images where id = 1";
		ResultSet rs = conn.createStatement().executeQuery(sql);
		if(rs.next()) {
			Blob pic = rs.getBlob(1);
			InputStream is = pic.getBinaryStream();
			int len = -1;
			byte[] buf = new byte[1024];
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			while((len = is.read(buf)) != -1) {
				baos.write(buf, 0, len);
			}
			is.close();
			baos.close();
			byte[] bytes = baos.toByteArray();
			File file = new File("E:\\waster\\辉夜姬.jpg");
			FileOutputStream fos = new FileOutputStream(file);
			fos.write(bytes);
			fos.close();
		}
	}
}

如果有错误的地方,欢迎指正。虽然,应该也没人看2333

数据库字段

id主键自增,image是blob类型

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值