美文网首页
Android 保存图片到本地(亲测有效)

Android 保存图片到本地(亲测有效)

作者: 谁动了我的代码QAQ | 来源:发表于2019-04-08 10:57 被阅读0次
    /**
         * 将Bitmap图片保存到本地相册
         */
        public static void savePhotoToGallery(final Context context, final Bitmap bitmap) {
    
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                AndPermission.with((Activity) context)
                        .requestCode(200)
                        .permission(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        .start();
            }
    
    
            if (bitmap == null) {
                ToastUtil.showCenterToast(context, "未获取到图片");
                return;
            }
    
            new Thread(new Runnable() {
                @Override
                public void run() {
                    // 其次把文件插入到系统图库
                    try {
                        MediaStore.Images.Media.insertImage(context.getContentResolver(), bitmap,
                                fileName, "测试 图集"); // 名字和描述没用,系统会自动更改
                        ((Activity) context).runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                ToastUtil.showCenterToast(context, "图片保存至相册");
                            }
                        });
                    } catch (Exception e) {
                        ((Activity) context).runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                ToastUtil.showCenterToast(context, "图片保存失败");
                            }
                        });
                        LogUtils.e("图片保存异常:", e);
                    }
                }
            }).start();
        }
    
    /**
         * 将图片保存到本地相册
         *
         */
        public static void savePhotoToGallery(final Context context, final String imgUrl) {
            if (TextUtils.isEmpty(imgUrl)) {
                ToastUtil.showCenterToast(context,"未获取到图片");
                return;
            }
    
            new Thread(new Runnable() {
                @Override
                public void run() {
                    String fileName = "test_" + System.currentTimeMillis() + ".jpg";
                    String sdCardDir = SDCardUtils.getDiskDir() + "DCIM/";
                    File appDir = new File(sdCardDir, "text");
                    if (!appDir.exists()) {
                        appDir.mkdir();
                    }
                    File f = new File(appDir, fileName);
    
                    try {
                        // 保存图片
                        URL url = new URL(imgUrl);
                        HttpURLConnection con = (HttpURLConnection) url.openConnection();
                        con.setRequestMethod("GET");
                        con.setConnectTimeout(1000 * 6);
                        if (con.getResponseCode() == 200) {
                            InputStream inputStream = con.getInputStream();
                            byte[] b = FileUtils.getBytes(inputStream);
                            FileOutputStream fileOutputStream = new FileOutputStream(f);
                            fileOutputStream.write(b);
                            fileOutputStream.close();
                        } else {
                            ToastUtil.showCenterToast(context,"图片保存失败");
                            return;
                        }
    
                        //把文件插入到系统图库
                          MediaStore.Images.Media.insertImage(context.getContentResolver(),
                                  f.getAbsolutePath(), fileName, null);
    
                        // 通知图库更新
                        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(new File(f.getPath()))));
    
                        ((Activity) context).runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                ToastUtil.showCenterToast(context,"图片保存至相册");
                            }
                        });
                    } catch (Exception e) {
                        ((Activity) context).runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                ToastUtil.showCenterToast(context,"图片保存失败");
                            }
                        });
                        LogUtils.e("图片保存异常:", e);
                    }
                }
            }).start();
        }
    

    其中的getBytes方法如下:

       /**
         * 将InputStream,转换为字节
         */
        public static byte[] getBytes(InputStream inputStream) throws Exception {
            byte[] b = new byte[1024];
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            int len = -1;
            while ((len = inputStream.read(b)) != -1) {
                byteArrayOutputStream.write(b, 0, len);
            }
            byteArrayOutputStream.close();
            inputStream.close();
            return byteArrayOutputStream.toByteArray();
        }
    

    相关文章

      网友评论

          本文标题:Android 保存图片到本地(亲测有效)

          本文链接:https://www.haomeiwen.com/subject/ypquiqtx.html