从网络得到图片数据保存到手机中,

之前我是想把图片以blob的形式全部存数据库的,试了好几种方法都不行,暂时先存文件了,主要是sql语句不支持数组形式存

从网络中下载图片放到手机中,urlpath图片的网络地址,

这个方法是得到图片的二进制数据

public byte[] getImage(String urlpath) throws Exception {

URL url = new URL(urlpath);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
LogWrapper.i(TAG, "urlpath = " + urlpath);
conn.setRequestMethod("GET");
conn.setConnectTimeout(6 * 1000);


if (conn.getResponseCode() == 200) {
InputStream inputStream = conn.getInputStream();
return readStream(inputStream);
}
LogWrapper.i(TAG, "getImage(), return null");
return null;
}

//读取二进制数据
public byte[] readStream(InputStream inStream) throws Exception {
ByteArrayOutputStream outstream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = -1;
while ((len = inStream.read(buffer)) != -1) {
outstream.write(buffer, 0, len);
}
outstream.close();
inStream.close();
LogWrapper.i(TAG,
"outstream.toByteArray().length = "
+ outstream.toByteArray().length);
return outstream.toByteArray();

}

//imagePath网络前缀,即服务器放置图片的地址,json.getString("myface")网络解析的图片名称

byte[] data = getImage(imagePath + json.getString("myface"));
bm = BitmapFactory.decodeByteArray(data, 0, data.length);
String iconPath = json.getString("myface");

//以"/"截取图片名称,这样就不用建新的文件夹目录,
iconPath = iconPath.substring(iconPath.lastIndexOf("/")+1);
LogWrapper.i(TAG,"imagFilePath = "+imagFilePath);
File f = new File(imagFilePath,"icon"+iconPath); //创建图片新文件
//if(f.exists()){
//f.delete();
//}
if (!f.exists()) {
f.createNewFile();
FileOutputStream out = new FileOutputStream(f); 
bm.compress(Bitmap.CompressFormat.PNG, 100, out); 
out.flush(); 
out.close(); 
Log.i(TAG, "已经保存图片"); 
}
bm = null;
data = null;

在BaseAdapter中读取,我是把图片路径存数据库的,故是如下处理

String path = list.get(position).getImg();
String iconPath = context.getFilesDir().getAbsolutePath()+"/";//图片路径放在了程序的安装目录下
iconPath += path;

         File mfile=new File(iconPath);
         Bitmap bm = null;
    if (mfile.exists()) {//若该文件存在
        bm = BitmapFactory.decodeFile(iconPath);
    }
    Drawable drawab = null;
    if(null != bm){
   drawab = new BitmapDrawable(bm);
    }
    
if(null != path){
if(null == drawab){
holder.qcb.setImageResource(R.drawable.icos6);//路径不存在放一张默认的
}else{
holder.qcb.setBackgroundDrawable(drawab);
}
}

 

posted @ 2013-08-06 18:25  jlins  阅读(299)  评论(0编辑  收藏  举报