2016年07月26日 14:57:46 阅读数:166更多
个人分类: android笔记
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/fought_feng/article/details/52035790
根据图片url获取bitmap对象
public static Bitmap returnBitmap(String url) {
URL fileUrl = null;
Bitmap bitmap = null;
try {
fileUrl = new URL(url);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
HttpURLConnection conn = (HttpURLConnection) fileUrl
.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
bitmap = BitmapFactory.decodeStream(is);
is.close();
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
}
- 1
- 2
- 3
有了图片bitmap,我们就可以通过setImageBitmap()设置图片了。
ImageView.setImageBitmap(bitmap);
将bitmap保存为图片文件
这里返回的是URI,我们也可以通过setImageURI()设置图片。
ImageView..setImageURI(uri);;
public static Uri saveImageBitmap(Context context, Bitmap bitmap,String imgname) {
String state = Environment.getExternalStorageState();
if (state.equals(Environment.MEDIA_MOUNTED)) {
File dir = new File(Environment.getExternalStorageDirectory()+"/Images");
if (!dir.exists())
dir.mkdirs();
file = new File(dir, imgname);
try {
FileOutputStream fos = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.flush();
fos.close();
return Uri.fromFile(file);
} catch (Exception e) {
e.printStackTrace();
return null;
}
} else {
Toast.makeText(context, "请确认已经插入SD卡", Toast.LENGTH_SHORT).show();
}
return null;
}