Android实现保存图片到本地并在相册中显示

Android中拍照保存图片到本地是常见的一种需求,之前碰到了一个问题,就是在4.4中,刷新相册会出现ANR,经过一番百度解决了这个问题。

首先是保存图片到本地

private static final String SAVE_PIC_PATH = Environment.getExternalStorageState().equalsIgnoreCase(Environment.MEDIA_MOUNTED) ? Environment.getExternalStorageDirectory().getAbsolutePath() :
      "/mnt/sdcard";//保存到SD卡
  private static final String SAVE_REAL_PATH = SAVE_PIC_PATH + "/good/savePic";

   //保存的确切位置,根据自己的具体需要来修改

public void saveFile(Bitmap bm,String fileName,String path) throws IOException {
    String subForder = SAVE_REAL_PATH + path;
    File foder = new File(subForder);
    if (!foder.exists()) {
      foder.mkdirs();
    }
    File myCaptureFile = new File(subForder,fileName);
    if (!myCaptureFile.exists()) {
      myCaptureFile.createNewFile();
    }
    BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
    bm.compress(Bitmap.CompressFormat.JPEG,80,bos);
    bos.flush();
    bos.close();
    Toast.makeText(this,"保存成功",Toast.LENGTH_SHORT).show();

以上就是保存图片的方法,保存完毕之后就是要通知相册刷新了,
在4.4中:

MediaScannerConnection.scanFile(this,new String[]{SAVE_REAL_PATH+ "/" + fileName},null,new MediaScannerConnection.OnScanCompletedListener() {
      @Override
      public void onScanCompleted(String path,Uri uri) {
        Log.e( "onScanCompleted: ",path);
        Log.e( "onScanCompleted: ",uri.toString());
      }
    });

在4.4以上的是发送广播来实现:

Intent intent = new Intent(Intent.ACTION_MEDIA_MOUNTED); //这是刷新SD卡
//    Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);  // 这是刷新单个文件
    Uri uri = Uri.fromFile(new File(SAVE_REAL_PATH));
    intent.setData(uri);
    sendBroadcast(intent);

以上两种方式有所区别,刷新SD卡的uri和刷新单个文件的uri的path不同,刷新SD卡的path就是外部存储的根目录,刷新单个文件的path就是你保存图片的具体路径,这是暂时我所遇到的坑,4.4一下还没测试,如果测试出现问题,欢迎评论。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程小技巧。

以上是来客网为你收集整理的Android实现保存图片到本地并在相册中显示全部内容,希望文章能够帮你解决Android实现保存图片到本地并在相册中显示所遇到的程序开发问题。

如果觉得来客网网站内容还不错,欢迎将来客网网站推荐给程序员好友。