1.如果是网络图片,需要得到图片地址url,还有要显示的ImageView。
new Thread(new Runnable() {
public void run() {
try {
HttpURLConnection conn = (HttpURLConnection) new URL(imgurl).openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(is);
FileOutputStream fos = new FileOutputStream(
new File(Environment.getExternalStorageDirectory() + "/" + saveurl + ".jpg"));
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}).start();
Toasts("图片保存成功! " + Environment.getExternalStorageDirectory() + "/" + saveurl + ".jpg");
这里saveurl是将图片地址进行了截取,以保证每次的图片地址不一样。
2、对于本地图片,直接保存ImageView里面的图片,不用耗费流量。有多种方法选择。
(1) 开启缓存保存图片,适用于所有view。但是这种方式保存的图片有个致命的缺
点,所见即所得,比如ImageView的缩放类型为ScaleType.CENTER_CROP,此时保存
的也是缩放过后的图片,这种效果可能有时无法满足我们的实际需求。但也不是一无是
处,在截屏介绍中,这种方法非常强大。
public static void saveBitmap(View view, String filePath){
view.setDrawingCacheEnabled(true);//开启绘制缓存
Bitmap imageBitmap = view.getDrawingCache();
FileOutputStream outStream = null;
File file=new File(filePath);
if(file.isDirectory()){//如果是目录不允许保存
return;
}
try {
outStream = new FileOutputStream(file);
imageBitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if(outStream!=null){
outStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
imageBitmap.recycle();
view.setDrawingCacheEnabled(false);//关闭绘制缓存
}
}
(2)上面的方式无法保存一张完整的图片,所以可能无法满足实际工作需求,这时就需
要用到下面这种方法,这种方法可以获取整个图片,但是只适用于ImageView。其他
view只能使用getBackground来获得Drawable对象,不满足实际需求,而且
Background也不一定是BitmapDrawable
public static void saveBitmap(ImageView view, String filePath) {
Drawable drawable = view.getDrawable();
if (drawable == null) {
return;
}
FileOutputStream outStream = null;
File file = new File(filePath);
if (file.isDirectory()) {// 如果是目录不允许保存
return;
}
try {
outStream = new FileOutputStream(file);
Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
outStream.flush();
outStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
(3)这种方式适用于所有的view,可以将view里的全部内容绘制成bitmap并保存。
public static void saveBitmap(View view, String filePath){
// 创建对应大小的bitmap
Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(),
Bitmap.Config.RGB_565);
Canvas canvas = new Canvas(bitmap);
view.draw(canvas);
//存储
FileOutputStream outStream = null;
File file=new File(filePath);
if(file.isDirectory()){//如果是目录不允许保存
return;
}
try {
outStream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
bitmap.recycle();
if(outStream!=null){
outStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}