Android 保存圖片到本地(親測(cè)有效)

/**
     * 將Bitmap圖片保存到本地相冊(cè)
     */
    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() {
                // 其次把文件插入到系統(tǒng)圖庫(kù)
                try {
                    MediaStore.Images.Media.insertImage(context.getContentResolver(), bitmap,
                            fileName, "測(cè)試 圖集"); // 名字和描述沒(méi)用,系統(tǒng)會(huì)自動(dòng)更改
                    ((Activity) context).runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            ToastUtil.showCenterToast(context, "圖片保存至相冊(cè)");
                        }
                    });
                } catch (Exception e) {
                    ((Activity) context).runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            ToastUtil.showCenterToast(context, "圖片保存失敗");
                        }
                    });
                    LogUtils.e("圖片保存異常:", e);
                }
            }
        }).start();
    }

/**
     * 將圖片保存到本地相冊(cè)
     *
     */
    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;
                    }

                    //把文件插入到系統(tǒng)圖庫(kù)
                      MediaStore.Images.Media.insertImage(context.getContentResolver(),
                              f.getAbsolutePath(), fileName, null);

                    // 通知圖庫(kù)更新
                    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,"圖片保存至相冊(cè)");
                        }
                    });
                } catch (Exception e) {
                    ((Activity) context).runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            ToastUtil.showCenterToast(context,"圖片保存失敗");
                        }
                    });
                    LogUtils.e("圖片保存異常:", e);
                }
            }
        }).start();
    }

其中的getBytes方法如下:

   /**
     * 將InputStream,轉(zhuǎn)換為字節(jié)
     */
    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();
    }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀(guān)點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容