android 在SD卡上保存圖片

首先判斷SD卡是否插入--> public String getSDPath(){             File SDdir=null;             boolean sdCardExist= Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);             if(sdCardExist){                     SDdir=Environment.getExternalStorageDirectory();             }             if(SDdir!=null){                     return SDdir.toString();             }             else{                     return null;             }     } 而後建立文件夾--> public void createSDCardDir(){             if(getSDPath()==null){                     Toast.makeText(PicSharesActivity.this, "未找到SD卡", 1000).show();             }else{                         if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())){                             // 建立一個文件夾對象,賦值爲外部存儲器的目錄                              File sdcardDir =Environment.getExternalStorageDirectory();                            //獲得一個路徑,內容是sdcard的文件夾路徑和名字                              newPath=sdcardDir.getPath()+"/***app/tempImages/";//newPath在程序中要聲明                              File path1 = new File(newPath);                             if (!path1.exists()) {                              //若不存在,建立目錄,能夠在應用啓動的時候建立                              path1.mkdirs();                              System.out.println("paht ok,path:"+newPath);                            }                      }                      else{                       System.out.println("false");                     }             }         } 建立好文件夾以後就能夠保存圖片了--> public void saveMyBitmap(String bitName,int percent) throws IOException {                                 Bitmap bmp = drawable2Bitmap(picView.getDrawable());//這裏的drawable2Bitmap方法是我把 ImageView中 的drawable轉化成bitmap,固然實驗的時候能夠本身建立bitmap             File f = new File(newPath + bitName + ".jpg");             f.createNewFile();             FileOutputStream fOut = null;             try {                     fOut = new FileOutputStream(f);                            } catch (FileNotFoundException e) {                            e.printStackTrace();             }             bmp.compress(Bitmap.CompressFormat.JPEG, percent, fOut);             try {                     fOut.flush();             } catch (IOException e) {                     e.printStackTrace();             }             try {                     fOut.close();             } catch (IOException e) {                     e.printStackTrace();             }     } //附加drawable2Bitmap方法 static Bitmap drawable2Bitmap(Drawable d){             int width=d.getIntrinsicWidth();             int height=d.getIntrinsicHeight();             Bitmap.Config config=d.getOpacity()!=PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888: Bitmap.Config.RGB_565;             Bitmap bitmap=Bitmap.createBitmap(width,height,config);             Canvas canvas=new Canvas(bitmap);             d.setBounds(0, 0, width, height);             d.draw(canvas);             return bitmap;     } 僅供參考,留着之後備用。
相關文章
相關標籤/搜索