位图到文件,未显示在默认库应用程序中

时间:2014-07-06 06:02:37

标签: android android-bitmap

我有这个片段,它是从视图创建图像。文件可以在文件管理器中看到并可以通过代码访问,但是默认的android gallery app没有显示它们。

Bitmap returnedBitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(),Bitmap.Config.ARGB_8888);

Canvas canvas = new Canvas(returnedBitmap);

view.draw(canvas);


ByteArrayOutputStream bytes = new ByteArrayOutputStream();
returnedBitmap.compress(Bitmap.CompressFormat.PNG, 100, bytes);

Date now = new Date();      
String path = Environment.getExternalStorageDirectory() + File.separator + "Download" + File.separator +now.getTime()+".png";

File f = new File(path);
try {
    f.createNewFile();
    FileOutputStream fo = new FileOutputStream(f);
    fo.write(bytes.toByteArray());
    fo.close();
} catch (Exception e) {
}

2 个答案:

答案 0 :(得分:0)

您需要将文件添加到图库。请从开发者的网站上试用此代码:

  private void galleryAddPic(String path) {
      Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
      File f = new File(path);//your file path
      Uri contentUri = Uri.fromFile(f);
      mediaScanIntent.setData(contentUri);
      this.sendBroadcast(mediaScanIntent);
  }

注意请确保您没有保存在应用的私人记忆中。

答案 1 :(得分:0)

我的经验是,使用MediaScanner更好,你可以获得存储在媒体数据库中的内容的URI。

static final class PicScanner implements MediaScannerConnectionClient {
        @SuppressWarnings("unused")
        private static PicScanner mInstance;
        private String mFilename;
        private String mMimetype;
        private MediaScannerConnection mConn;

        public static void scan(Context ctx, File file, String mimetype) {
            mInstance = new PicScanner (ctx, file, mimetype);
        }

        private PicScanner (Context ctx, File file, String mimetype) {
            this.mFilename = file.getAbsolutePath();
            mConn = new MediaScannerConnection(ctx, this);
            mConn.connect();
        }

        @Override
        public void onMediaScannerConnected() {
            mConn.scanFile(mFilename, mMimetype);
        }

        @Override
        public void onScanCompleted(String path, Uri uri) {
            mConn.disconnect();
            mInstance = null;
            //notifyNewPicSavedLocally(path, uri);
        }
    }

用法示例:

PicScanner.scan(mContext, picFile, "image/jpeg"); //picFile should be access-able for other process