第一种:採用系统的api直接使用:
ContentResolver cr = getContentResolver(); String url = MediaStore.Images.Media.insertImage(cr, bmp, String.valueOf(System.currentTimeMillis()), "");
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"+ Environment.getExternalStorageDirectory())));
另外一种:直接採用文件流进行保存到相冊
File tempFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getPath() + "/" + String.valueOf(System.currentTimeMillis()) + ".png"); if(tempFile.exists()){ tempFile.delete(); } try { tempFile.createNewFile(); } catch (IOException e) { e.printStackTrace(); } FileOutputStream fOut = null; try { fOut = new FileOutputStream(tempFile); } catch (FileNotFoundException e) { e.printStackTrace(); } bmp.compress(Bitmap.CompressFormat.PNG, 100, fOut); try { fOut.flush(); fOut.close(); } catch (IOException e) { // TODO: handle exception e.printStackTrace(); }
最后把整个方法贴出来:
/** * 將ImageView中的圖片保存到系统相冊 */ private void SaveImageToSysAlbum() { if (FileUtil.isSdCardExist()) { BitmapDrawable bmpDrawable = (BitmapDrawable)mFullImageView.getDrawable(); Bitmap bmp = bmpDrawable.getBitmap(); if (bmp != null) { try { /*ContentResolver cr = getContentResolver(); String url = MediaStore.Images.Media.insertImage(cr, bmp, String.valueOf(System.currentTimeMillis()), "");*/ File tempFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getPath() + "/" + String.valueOf(System.currentTimeMillis()) + ".png"); if(tempFile.exists()){ tempFile.delete(); } try { tempFile.createNewFile(); } catch (IOException e) { e.printStackTrace(); } FileOutputStream fOut = null; try { fOut = new FileOutputStream(tempFile); } catch (FileNotFoundException e) { e.printStackTrace(); } bmp.compress(Bitmap.CompressFormat.PNG, 100, fOut); try { fOut.flush(); fOut.close(); } catch (IOException e) { // TODO: handle exception e.printStackTrace(); } Toast.makeText(this, getString(R.string.save_succ), Toast.LENGTH_SHORT).show(); } catch (Exception e) { e.printStackTrace(); } }else { Toast.makeText(this, getString(R.string.no_iamge_save_fail), Toast.LENGTH_SHORT).show(); } }else { Toast.makeText(this, getString(R.string.no_sdcard_save_fail), Toast.LENGTH_SHORT).show(); } String release = android.os.Build.VERSION.RELEASE; String tempID = release.substring(0, 3); if(Double.parseDouble(tempID) >= 4.4){//安卓4.4以上版本号的时候使用这个。下面的使用else语句里面的 MediaScannerConnection.scanFile(this,new String[]{Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getPath() + "/" }, null,null); }else { sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"+ Environment.getExternalStorageDirectory()))); MediaScannerConnection.scanFile(this,new String[]{Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getPath() + "/" }, null,null); } }
原文:http://www.cnblogs.com/yxwkf/p/5133106.html