一、背景:
1.1):前台界面将图片存储到数据
1.2):前台界面根据数据库存储的图片信息进行显示处理
二、实现方法:
JDBC 方式实现图片代码的存储读取。
注意:sql server 图片字段的类型定义为 IMAGE
三:具体事项
3.1):图片存储表 test_Img
CREATE TABLE test_Img
(
CFCarNumber [VARCHAR](44) NOT NULL,
CFCarImg IMAGE
)
数据库存储的样例:
3.2):用户前台界面
3.3):相关代码
服务端代码:
/**
* 图片插入
*/
@Override
public void saveImg(Context ctx) throws BOSException {
super.saveImg(ctx);
Connection conn = null;
try {
conn = DBUtils.getConnection(ctx);
String sql = "insert into test_Img (CFCarNumber,CFCarImg) values (?,?) ";
PreparedStatement pstmt=conn.prepareStatement(sql);
FileInputStream fi=new FileInputStream("D:\\temp\\马斯顿丁1.jpg");
pstmt.setString(1, "trt_003");
pstmt.setBinaryStream(2,fi,fi.available());
pstmt.execute();
} catch (SQLException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 图片读取
*/
@Override
public Icon readImg(Context ctx, String code) throws BOSException,
EASBizException {
ImageIcon icon = null;
Connection conn = null;
try {
conn = DBUtils.getConnection(ctx);
PreparedStatement ps = conn.prepareStatement("select CFCarImg from test_Img where CFCarNumber='"+code+"' ");
ResultSet rs = ps.executeQuery();
while(rs.next()){
InputStream in = rs.getBinaryStream("CFCarImg");
FileOutputStream out = new FileOutputStream("D:\\temp\\new.jpg");
byte[] b = new byte[1024];
int len = 0;
while ((len = in.read(b)) != -1) {
out.write(b, 0, len);
out.flush();
}
}
Image img = ImageIO.read(new File("D:\\temp\\new.jpg"));
icon=new ImageIcon(img);
return icon;
} catch (SQLException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return icon;
}
客户端代码:
@Override
public void onLoad() throws Exception {
super.onLoad();
readImg();
}
/**
* @Title: readImg
* @Description: TODO(读取图片)
* @param:
* @return: void
* @throws
*/
private void readImg() {
KDLable.setBounds(new Rectangle(520, 75, 526, 361));
kDLabel1.setBounds(new Rectangle(614, 420, 100, 19));
try {
Icon icon = CarInfrormactionFactory.getRemoteInstance().readImg(txtNumber.getText());
KDLable.setIcon(icon);
KDLable.setText(null);
kDLabel1.setText("第1页/共5页");
} catch (EASBizException e) {
e.printStackTrace();
} catch (BOSException e) {
e.printStackTrace();
}
}
@Override
public void actionSubmit_actionPerformed(ActionEvent e) throws Exception {
super.actionSubmit_actionPerformed(e);
CarInfrormactionFactory.getRemoteInstance().saveImg();
}
注意:
此贴代码为Demo,很多代码都是直接写死的,仅供参考,具体情况根据实际业务考虑。