首页 > 代码库 > 图片以BLOB存储在后台数据库中,Android客户端要进行读取显示
图片以BLOB存储在后台数据库中,Android客户端要进行读取显示
解决方法:
1:在后台以InputStream的方式将图片从数据库中读出:
public static InputStream getPicInputStream(){ String id = "f304733361e243779b2340afe20e62bf"; Connection conn = JdbcUtil.getConnection(); PreparedStatement ps = null; ResultSet rs = null; InputStream is = null; String sql = "select zp from pic_test where id= ?"; try { ps = conn.prepareStatement(sql); ps.setString(1, id); rs = ps.executeQuery(); if(rs.next()){ is = rs.getBlob("zp").getBinaryStream(); } } catch (SQLException ex) { Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex); }finally{ try { if(null!=ps){ ps.close(); } } catch (SQLException ex) { Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex); } try { if(null!=rs){ rs.close(); } } catch (SQLException ex) { Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex); } JdbcUtil.release(conn); } return is; }
2:在Servlet中直接生成图片:
response.setContentType("image/jpeg"); InputStream is = Test.getPicInputStream(); if(null!=is){ OutputStream os = response.getOutputStream(); int len; byte buf[] = new byte[1024]; while((len=is.read(buf))!=-1){ os.write(buf, 0, len); } is.close(); os.close(); }
3:Android客户端的处理
public class MainActivity extends Activity { ImageView imgView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); imgView = (ImageView)findViewById(R.id.imgView); new ImgViewAsyncTask().execute(""); } class ImgViewAsyncTask extends AsyncTask<String,String,String>{ Bitmap bitmap = null; @Override protected void onPreExecute() { } @Override protected String doInBackground(String... strings) { InputStream is = null; String result = ""; try { URL picURL = new URL("http://192.168.0.165:8084/wisdompm/PicServlet"); HttpURLConnection conn = (HttpURLConnection)picURL.openConnection(); conn.setConnectTimeout(10000); conn.connect(); is = conn.getInputStream(); if(null!=is){ bitmap = BitmapFactory.decodeStream(is); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally { try { if(null!=is){ is.close(); } } catch (IOException e) { e.printStackTrace(); } } return result; } @Override protected void onPostExecute(String s) { if(null!=bitmap && null!=imgView){ imgView.setImageBitmap(bitmap); } } }}
测试结果:
图片以BLOB存储在后台数据库中,Android客户端要进行读取显示
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。