1. 程式人生 > >Android網路URL圖片地址轉Bitmap並且儲存到本地

Android網路URL圖片地址轉Bitmap並且儲存到本地

一、網路URL圖片地址轉Bitmap

 public  Bitmap getBitmap(String imgUrl) {
        InputStream inputStream=null;
        ByteArrayOutputStream outputStream=null;
        URL url = null;
        try {
            url=new URL(imgUrl);
            HttpURLConnection httpURLConnection=(HttpURLConnection) url.openConnection
(); httpURLConnection.setRequestMethod("GET"); httpURLConnection.setReadTimeout(2000); httpURLConnection.connect(); if(httpURLConnection.getResponseCode()==200) { //網路連線成功 inputStream = httpURLConnection.getInputStream(); outputStream =
new ByteArrayOutputStream(); byte buffer[] = new byte[1024 * 8]; int len = -1; while ((len = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, len); } byte[] bu = outputStream.toByteArray
(); Bitmap bitmap = BitmapFactory.decodeByteArray(bu, 0, bu.length); return bitmap; }else { Log.(TAG,"網路連線失敗----"+httpURLConnection.getResponseCode()) } } catch (Exception e) { // TODO: handle exception }finally{ if(inputStream!=null){ try { inputStream.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(outputStream!=null){ try { outputStream.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } return null; }

溫馨提示:這裡需要一個執行緒去訪問

二、儲存圖片到本地

 public void saveImageToGallery(Bitmap bmp) {
        if (bmp==null){
            Log.e(TAG,"bitmap---為空")
            return ;
        }
        String galleryPath= Environment.getExternalStorageDirectory()
                + File.separator + Environment.DIRECTORY_DCIM
                +File.separator+"Camera"+File.separator;
        String fileName = +System.currentTimeMillis() + ".jpg";
        File file = new File(galleryPath, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            //通過io流的方式來壓縮儲存圖片
            boolean isSuccess = bmp.compress(Bitmap.CompressFormat.JPEG, 60, fos);
            fos.flush();
            fos.close();
            //儲存圖片後傳送廣播通知更新資料庫
            Uri uri = Uri.fromFile(file);
            mContext.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
            if (isSuccess) {
               Log.e(TAG,"圖片儲存成功 儲存在:" + file.getPath()));
            } else {
                 Log.e(TAG,"圖片儲存失敗"));
            }
        } catch (IOException e) {
             Log.e(TAG,"儲存圖片找不到資料夾");
            e.printStackTrace();
        }
    }

溫馨提示:
儲存圖片的時候記得加上請求許可權喲

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

大功告成!!!!!