黑马程序员技术交流社区
标题:
Android 图片保存到SDcard中
[打印本页]
作者:
y1787257661
时间:
2015-1-6 10:40
标题:
Android 图片保存到SDcard中
class DownLoadItemImageAsync extends
AsyncTask<TaobaokeItem, Integer, Bitmap> {
private TaobaokeItem item;
@Override
protected Bitmap doInBackground(TaobaokeItem... params) {
item = params[0];
Bitmap bitmap = getBitmap();
if (bitmap != null) {
return bitmap;
}
return getItemPic(item.getPicUrl());
}
@Override
protected void onPostExecute(Bitmap result) {
Drawable drawable = new BitmapDrawable(result);
setProgressBarIndeterminateVisibility(false);
mImageSwitcher.setImageDrawable(drawable);
}
private Bitmap getItemPic(String picUrl) {
URL url = null;
URLConnection conn = null;
InputStream in = null;
Bitmap itemBitmap = null;
try {
url = new URL(picUrl);
conn = url.openConnection();
conn.setConnectTimeout(3 * 1000);
conn.connect();
in = conn.getInputStream();
itemBitmap = BitmapFactory.decodeStream(in);
storeInSD(itemBitmap);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (url != null) {
url = null;
}
if (conn != null) {
conn = null;
}
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return itemBitmap;
}
private void storeInSD(Bitmap bitmap) {
File file = new File(FILE_DIR);
if (!file.exists()) {
file.mkdir();
}
File imageFile = new File(file, item.getNumIid() + ".jpg");
try {
imageFile.createNewFile();
FileOutputStream fos = new FileOutputStream(imageFile);
bitmap.compress(CompressFormat.JPEG, 50, fos);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private Bitmap getBitmap() {
File imageFile = new File(FILE_DIR, item.getNumIid() + ".jpg");
Bitmap bitmap = null;
if (imageFile.exists()) {
try {
bitmap = BitmapFactory.decodeStream(new FileInputStream(
imageFile));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return bitmap;
}
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2