Blankj大神写的 Android开发人员不得不收集的代码(持续更新中)
// ## 图片Url转Bitmap ##
public static Bitmap getBitmap(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();// 关闭流
} catch (Exception e) {
e.printStackTrace();
}
return bm;
}
需要权限:
<uses-permission android:name="android.permission.INTERNET" />
// ## bitmap保存到本地 ##
public static void saveBitmap(Bitmap bitmap, String imageName) {
File file = new File(MyApplication.apkdownload_path, imageName);
if (file.exists()) {
file.delete();
}
try {
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
Log.i(TAG, "已经保存");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
需要权限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
记录自己的代码,提高开发效率