Android 安卓將網絡圖片保存到相冊

Android 安卓將網絡圖片保存到相冊

封裝了一個工具類!

請先加上讀寫權限:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

如果是Android6.0之後,加上權限後再動態申請權限

if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
	if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
		ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
	}
}

使用方法:

//示例1:保存網絡圖片
SaveNetPhotoUtils.savePhoto(this, "https://profile.csdnimg.cn/5/F/3/3_qq_40881680");

//示例2:保存網絡圖片並且給圖片命名
SaveNetPhotoUtils.savePhoto(this, "https://profile.csdnimg.cn/5/F/3/3_qq_40881680", "photoName.jpg");

該類所帶工具:

SaveNetPhotoUtils.savePhoto(上下文, 網絡圖片url);
SaveNetPhotoUtils.savePhoto(上下文, 網絡圖片url, 圖片名字 + 後綴);

工具類:

/**
 * @author ThirdGoddess
 * @email [email protected]
 * @Github https://github.com/ThirdGoddess
 * @date :2020-03-14 10:11
 */
public class SaveNetPhotoUtils {

    private static Context contexts;
    private static String photoUrls;
    private static Bitmap bitmap;
    private static String mSaveMessage = "failed";

    //自定義名字
    private static String photoNames;

    /**
     * 保存圖片,無須自定義名字
     *
     * @param context
     * @param photoUrl
     */
    public static void savePhoto(Context context, String photoUrl) {
        contexts = context;
        photoUrls = photoUrl;
        new Thread(saveFileRunnable).start();
    }

    /**
     * 定義圖片名字保存到相冊
     *
     * @param context
     * @param photoUrl
     * @param photoName 圖片名字,定義格式 name.jpg/name.png/...
     */
    public static void savePhoto(Context context, String photoUrl, String photoName) {
        contexts = context;
        photoUrls = photoUrl;
        photoNames = photoName;
        new Thread(saveFileRunnable2).start();
    }

    private static Runnable saveFileRunnable = new Runnable() {
        @Override
        public void run() {
            try {
                if (!TextUtils.isEmpty(photoUrls)) {
                    URL url = new URL(photoUrls);
                    InputStream inputStream = url.openStream();
                    bitmap = BitmapFactory.decodeStream(inputStream);
                    inputStream.close();
                }
                saveFile(bitmap);
                mSaveMessage = "success!";
            } catch (IOException e) {
                mSaveMessage = "failed";
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
            messageHandler.sendMessage(messageHandler.obtainMessage());
        }
    };

    private static Runnable saveFileRunnable2 = new Runnable() {
        @Override
        public void run() {
            try {
                if (!TextUtils.isEmpty(photoUrls)) {
                    URL url = new URL(photoUrls);
                    InputStream inputStream = url.openStream();
                    bitmap = BitmapFactory.decodeStream(inputStream);
                    inputStream.close();
                }
                saveFile(bitmap, photoNames);
                mSaveMessage = "success!";
            } catch (IOException e) {
                mSaveMessage = "failed";
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
            messageHandler.sendMessage(messageHandler.obtainMessage());
        }
    };

    /**
     * 保存成功和失敗通知
     */
    @SuppressLint("HandlerLeak")
    private static Handler messageHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            Toast.makeText(contexts, mSaveMessage, Toast.LENGTH_SHORT).show();
        }
    };

    /**
     * 保存圖片
     *
     * @param bm
     * @throws IOException
     */
    public static void saveFile(Bitmap bm) throws IOException {
        File dirFile = new File(Environment.getExternalStorageDirectory().getPath());
        if (!dirFile.exists()) {
            dirFile.mkdir();
        }

        //圖片命名
        String fileName = UUID.randomUUID().toString() + ".jpg";
        File myCaptureFile = new File(Environment.getExternalStorageDirectory().getPath() + "/DCIM/Camera/" + fileName);
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
        bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);
        bos.flush();
        bos.close();

        //廣播通知相冊有圖片更新
        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        Uri uri = Uri.fromFile(myCaptureFile);
        intent.setData(uri);
        contexts.sendBroadcast(intent);
    }

    /**
     * 保存圖片
     *
     * @param bm
     * @param photoName 圖片命名
     * @throws IOException
     */
    public static void saveFile(Bitmap bm, String photoName) throws IOException {
        File dirFile = new File(Environment.getExternalStorageDirectory().getPath());
        if (!dirFile.exists()) {
            dirFile.mkdir();
        }

        //圖片命名後保存到相冊
        File myCaptureFile = new File(Environment.getExternalStorageDirectory().getPath() + "/DCIM/Camera/" + photoName);
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
        bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);
        bos.flush();
        bos.close();

        //廣播通知相冊有圖片更新
        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        Uri uri = Uri.fromFile(myCaptureFile);
        intent.setData(uri);
        contexts.sendBroadcast(intent);
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章