public void url2bitmap(String url) {
Bitmap bm = null;
try {
URL iconUrl = new URL(url);
URLConnection conn = iconUrl.openConnection();
HttpURLConnection http = (HttpURLConnection) conn;
int length = http.getContentLength();
conn.connect();
// 获得图像的字符流
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is, length);
bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
if (bm != null) {
save2Album(bm,url);
}
} catch (Exception e) {
runOnUiThread(new Runnable() {
@Override
public void run() {
showToastMessage("保存失败");
}
});
e.printStackTrace();
}
}
private void save2Album(Bitmap bitmap, String picUrl) {
File appDir = new File(Environment.getExternalStorageDirectory(), System.currentTimeMillis() + ".png");
if (!appDir.exists()) appDir.mkdir();
String[] str = picUrl.split("/");
String fileName = str[str.length - 1];
File file = new File(appDir, fileName);
try {
FileOutputStream fos = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
onSaveSuccess(file);
} catch (IOException e) {
runOnUiThread(new Runnable() {
@Override
public void run() {
showToastMessage("保存失败");
}
});
e.printStackTrace();
}
}
private void onSaveSuccess(final File file) {
runOnUiThread(new Runnable() {
@Override
public void run() {
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));
showToastMessage("保存成功");
}
});
}
Url 转化为Bitmap
private static Bitmap bitmap;
public static Bitmap getBitmap(final String url) {
new Thread(new Runnable() {
@Override
public void run() {
URL imageurl = null;
try {
imageurl = new URL(url);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
HttpURLConnection conn = (HttpURLConnection)imageurl.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
bitmap = BitmapFactory.decodeStream(is);
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
return bitmap;
}