ImageView的保存方式和其它View稍微有些不一样
ImageView
大概思路:获取到ImageView的bitmap数据,将bitmap数据压缩为图片并输出,关闭输出流
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath(),"image1.png");
BitmapDrawable bitmapDrawable = (BitmapDrawable) imageView.getDrawable(); Bitmap bitmap = bitmapDrawable.getBitmap();
if (bitmap != null){
try {
FileOutputStream fileOutputStream = new FileOutputStream(file); bitmap.compress(Bitmap.CompressFormat.PNG,100,fileOutputStream); fileOutputStream.flush(); } catch (IOException e) { e.printStackTrace(); } finally { if (file.exists()){ Toast.makeText(getContext(),"保存成功",Toast.LENGTH_SHORT).show(); } else { Toast.makeText(getContext(),"保存失败",Toast.LENGTH_SHORT).show(); } } } else { Toast.makeText(getContext(),"保存失败",Toast.LENGTH_SHORT).show(); }
|
其它View
其它View无法像ImageView那样通过getDrawable获取drawable并强转为bitmapDrawable,然后再转换为bitmap并保存;必须给View创建一个bitmap,然后将画面绘制在bitmap中
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath(),"image2.png");
int w = pagerView.getWidth(); int h = pagerView.getHeight(); Bitmap bitmap = Bitmap.createBitmap(w,h, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap); canvas.drawColor(Color.WHITE); pagerView.layout(0,0,w,h); pagerView.draw(canvas);
try { FileOutputStream fileOutputStream = new FileOutputStream(file); bitmap.compress(Bitmap.CompressFormat.PNG,100,fileOutputStream); fileOutputStream.flush(); } catch (IOException e) { e.printStackTrace(); } finally { if (file.exists()){ Toast.makeText(getContext(),"保存成功",Toast.LENGTH_SHORT).show(); } else { Toast.makeText(getContext(),"保存失败",Toast.LENGTH_SHORT).show(); } }
|
不要忘记赋予储存读写权限
附,Android文件复制
读取后直接写入,读多少,写多少,简单粗暴
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| File file1 = new File(Environment.getExternalStorageDirectory().getAbsolutePath(),"image2.png"); File file2 = new File(Environment.getExternalStorageDirectory().getAbsolutePath(),"image3.png"); FileInputStream fileInputStream = null; FileOutputStream fileOutputStream = null; try { fileInputStream = new FileInputStream(file1); fileOutputStream = new FileOutputStream(file2);
byte[] bytes = new byte[1024]; int len; while ((len = fileInputStream.read(bytes)) > 0){ fileOutputStream.write(bytes,0,len); } fileOutputStream.flush(); } catch (IOException e) { e.printStackTrace(); } finally { if (file2.exists()){ Toast.makeText(getContext(),"复制成功",Toast.LENGTH_SHORT).show(); } else { Toast.makeText(getContext(),"复制失败",Toast.LENGTH_SHORT).show(); }
if (fileInputStream != null || fileOutputStream != null){ try { fileInputStream.close(); fileOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } } }
|