mysql 存储 读取图片_mysql数据库blob图片的存储和读取

1.首先对应于数据库boy表创建持久化类Boy (使用hibernate 逆向生成)

mysql表结构:表名:boy

id : 主键 integer

name: varchar(20)

image: blob

public class Boy  implements java.io.Serializable {

// Fields

private Integer id;

private String name;

private byte[] image;

// Constructors

/** default constructor */

public Boy() {

}

/** minimal constructor */

public Boy(Integer id) {

this.id = id;

}

/** full constructor */

public Boy(Integer id, String name, byte[] image) {

this.id = id;

this.name = name;

this.image = image;

}

// Property accessors

public Integer getId() {

return this.id;

}

public void setId(Integer id) {

this.id = id;

}

public String getName() {

return this.name;

}

public void setName(String name) {

this.name = name;

}

public byte[] getImage() {

return this.image;

}

public void setImage(byte[] image) {

this.image = image;

}

2.Boy.hbm.xml 文件配置如下

3.测试类  测试向表中存入图片 (图片名 : 2.png  位置 src/image/2.png)  TestBoyInput

public class TestBoyInput {

public static void main(String[] args) throws IOException {

// TODO Auto-generated method stub

Boy boy= new Boy();

boy.setId(16);

boy.setName("xiaoming");

try {

Session session= HibernateSessionFactory.getSession();

LobHelper lHelper= session.getLobHelper();

FileInputStream fis = new FileInputStream("src/image/2b.jpg");

byte[] buffer=new byte[fis.available()];

fis.read(buffer);

boy.setImage(buffer);

Transaction ts=session.beginTransaction();

session.save(boy);

ts.commit();

} catch (FileNotFoundException exception) {

exception.printStackTrace();

}

}

}

4.测试类 测试图片的读取和转存 TestBoyOutput 输出路径设为F盘根目录  名字为test.png

public class TestBoyOutPut {

public static void main(String[] args) throws SQLException, IOException {

// TODO Auto-generated method stub

Session session= HibernateSessionFactory.getSession();

Transaction tran = session.beginTransaction();

Boy boy  =(Boy)session.get(Boy.class, 16);

tran.commit();

session.close();

BufferedOutputStream bos = null;

FileOutputStream fos = null;

File file = null;

String filePath = "F:";//图片输出路径

String fileName = "test.png";//图片输出名字

try {

file = new File(filePath+"\\"+fileName);

fos = new FileOutputStream(file);

bos = new BufferedOutputStream(fos);

bos.write(boy.getImage());

} catch (Exception e) {

e.printStackTrace();

} finally {

if (bos != null) {

try {

bos.close();

} catch (IOException e1) {

e1.printStackTrace();

}

}

if (fos != null) {

try {

fos.close();

} catch (IOException e1) {

e1.printStackTrace();

}

}

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值