String picUrl=”http://img2.3lian.com/2014/f3/82/68.jpg”;//要保存的图片Url
Bitmap bitmap = getPicBitmap(picUrl);
savePicture(bitmap);// 保存图片到SD卡中的指定目录
1、根据图片的URL获取图片getPicBitmap(url);
/**
* 从网络获取图片
*
* @param url
* @return
*/
public Bitmap getPicBitmap(String url) {
Bitmap bitmap = null;
try {
URL pictureUrl = new URL(url);
InputStream in = pictureUrl.openStream();
bitmap = BitmapFactory.decodeStream(in);
in.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
}
2、把图片保存到本地(自己指定目录)
@SuppressLint("SdCardPath")
public void savePicture(Bitmap bitmap) {
String temps = Environment.getExternalStorageDirectory() + "/ceshi/";//文件目录名字
String pictureName = temps + "ceshi" + bitmap.getGenerationId()
+ ".jpg";//文件名
File tempFiles = new File(temps);
// 判断某个文件是否存在
if (!tempFiles.exists()) {
tempFiles.mkdir();
}
File file = new File(pictureName);
FileOutputStream out;
try {
out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
toShowPic(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
3、本地图片保存之后发广播,更新图片(若不发广播更新,只能在文件管理中查看)
/**
* 发广播更新图库
* @param file
*/
private void toShowPic(File file) {
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri uri = Uri.fromFile(file);
intent.setData(uri);
ShowBigPicActivity.this.sendBroadcast(intent);
}
注意:获取网络图片过程不要在主线程中执行,否则程序会出现错误。