如何在图库中显示保存到手机中的图像?

时间:2018-11-29 05:24:52

标签: android android-gallery file-manager

我使用以下code在手机内存中创建一个文件夹,并将位图保存到该文件夹​​中。该代码工作正常,并且位图已存储为JPEG。但是问题是我无法在Gallery应用程序中看到该图像,就像其他应用程序(如Whatsapp,Instagram等)中的图像一样。我必须转到File Manager应用程序才能看到它。为什么它没有显示在图库中? 这是我的代码:

saveButton.setOnClickListener(new View.OnClickListener() {
       @Override
       public void onClick(View v)
       {
            String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
            String imageFileName = "JPEG_" + timeStamp + ".jpg";
            CreateDirectoryAndSaveFile(mainImageBitmap, imageFileName);
       }
});

private void CreateDirectoryAndSaveFile(Bitmap imageToSave, String fileName)
    {
        File direct = new File(Environment.getExternalStorageDirectory() + "/" + getString(R.string.app_name));

        if (!direct.exists()) {
            File wallpaperDirectory = new File("/sdcard/" + getString(R.string.app_name) + "/");
            wallpaperDirectory.mkdirs();
        }

        File file = new File(new File("/sdcard/" + getString(R.string.app_name) + "/"), fileName);
        if (file.exists()) {
            file.delete();
        }
        try {
            FileOutputStream out = new FileOutputStream(file);
            imageToSave.compress(Bitmap.CompressFormat.JPEG, 100, out);
            out.flush();
            out.close();
            Toast.makeText(getActivity(), "Image saved to Gallery successfully", Toast.LENGTH_SHORT).show();
        } catch (Exception e)
        {
            Toast.makeText(getActivity(), "Error", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }
    }

1 个答案:

答案 0 :(得分:0)

将图像保存到文件中后,您将需要告诉媒体商店扫描文件。

为此用途:

MediaScannerConnection.scanFile(String path, String mimeType)

MediaScannerConnection.scanFile(Context context, String[] paths, String[] mimeTypes,
        OnScanCompletedListener callback) 

JPEG图像的MIME类型为"image/jpeg".