本文实例讲述了Android开发实现的保存图片到相册功能。分享给大家供大家参考,具体如下:
废话不多说,先上效果:
点击图片 调用savephoto的SaveBitmapFromView(View view);
方法自动保存图片
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
//点击图片保存 imageView.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { String[] PERMISSIONS = { "android.permission.READ_EXTERNAL_STORAGE" , "android.permission.WRITE_EXTERNAL_STORAGE" }; //检测是否有写的权限 int permission = ContextCompat.checkSelfPermission(MainActivity. this , "android.permission.WRITE_EXTERNAL_STORAGE" ); if (permission != PackageManager.PERMISSION_GRANTED) { // 没有写的权限,去申请写的权限,会弹出对话框 ActivityCompat.requestPermissions(MainActivity. this , PERMISSIONS, 1 ); } try { //创建savephoto类保存图片 SavePhoto savePhoto = new SavePhoto(MainActivity. this ); savePhoto.SaveBitmapFromView(imageView); } catch (ParseException e) { e.printStackTrace(); } } }); |
SavePhoto类具体实现
但原博主部分代码有误 我稍加了修改
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
|
public class SavePhoto{ //存调用该类的活动 Context context; public SavePhoto(Context context) { this .context = context; } //保存文件的方法: public void SaveBitmapFromView(View view) throws ParseException { int w = view.getWidth(); int h = view.getHeight(); Bitmap bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888); Canvas c = new Canvas(bmp); view.layout( 0 , 0 , w, h); view.draw(c); // 缩小图片 Matrix matrix = new Matrix(); matrix.postScale( 0 .5f, 0 .5f); //长和宽放大缩小的比例 bmp = Bitmap.createBitmap(bmp, 0 , 0 ,bmp.getWidth(),bmp.getHeight(),matrix, true ); DateFormat format = new SimpleDateFormat( "yyyyMMddHHmmss" ); saveBitmap(bmp,bmp.toString() + ".JPEG" ); } /* * 保存文件,文件名为当前日期 */ public void saveBitmap(Bitmap bitmap, String bitName){ String fileName ; File file ; if (Build.BRAND .equals( "Xiaomi" ) ){ // 小米手机 fileName = Environment.getExternalStorageDirectory().getPath()+ "/DCIM/Camera/" +bitName ; } else { // Meizu 、Oppo Log.v( "qwe" , "002" ); fileName = Environment.getExternalStorageDirectory().getPath()+ "/DCIM/" +bitName ; } file = new File(fileName); if (file.exists()){ file.delete(); } FileOutputStream out; try { out = new FileOutputStream(file); // 格式为 JPEG,照相机拍出的图片为JPEG格式的,PNG格式的不能显示在相册中 if (bitmap.compress(Bitmap.CompressFormat.JPEG, 90 , out)) { out.flush(); out.close(); // 插入图库 MediaStore.Images.Media.insertImage(context.getContentResolver(), file.getAbsolutePath(), bitName, null ); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } // 发送广播,通知刷新图库的显示 context.sendBroadcast( new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse( "file://" + fileName))); } } |
希望本文所述对大家Android程序设计有所帮助。
原文链接:https://blog.csdn.net/qq_43377749/article/details/84325487