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

发布于 2022-3-1 11:10
浏览
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();
    }

标签
1
收藏
回复
举报
回复
添加资源
添加资源将有机会获得更多曝光,你也可以直接关联已上传资源 去关联
    相关推荐