如何在安卓相册中保存图片

25
我试图将图片保存到WathsappIMG文件夹中,但当我前往安卓的图库时,我找不到这张图片。然而,从ES文件浏览器中可以看到该目录下的图片。

我试图将图片保存到WathsappIMG文件夹中,但当我前往安卓的图库时,我找不到这张图片。然而,从ES文件浏览器中可以看到该目录下的图片。

OutputStream output;
       // Find the SD Card path
        File filepath = Environment.getExternalStorageDirectory();

      // Create a new folder in SD Card
     File dir = new File(filepath.getAbsolutePath()
              + "/WhatSappIMG/");
        dir.mkdirs(); 

     // Retrieve the image from the res folder
        BitmapDrawable drawable = (BitmapDrawable) principal.getDrawable();
        Bitmap bitmap1 = drawable.getBitmap();

        // Create a name for the saved image
        File file = new File(dir, "Wallpaper.jpg" );

        try {

            output = new FileOutputStream(file);

            // Compress into png format image from 0% - 100%
            bitmap1.compress(Bitmap.CompressFormat.JPEG, 100, output);
            output.flush();
            output.close();

        }

        catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

这个文件夹里有没有一个名叫“.nomedia”的文件?可以用ES文件浏览器来检查,你可能需要从ES文件浏览器的滑动菜单中启用显示隐藏文件选项。 - KickAss
没有人没有.nomedia。 - Gatiko06
9个回答

79

画廊不一定显示来自外部存储的文件。

这是一个常见的错误。

画廊显示存储在媒体存储提供程序上的图像

您可以使用此方法将图像文件存储在媒体存储提供程序中:

public static void addImageToGallery(final String filePath, final Context context) {

    ContentValues values = new ContentValues();

    values.put(Images.Media.DATE_TAKEN, System.currentTimeMillis());
    values.put(Images.Media.MIME_TYPE, "image/jpeg");
    values.put(MediaStore.MediaColumns.DATA, filePath);

    context.getContentResolver().insert(Images.Media.EXTERNAL_CONTENT_URI, values);
}

1
将此方法添加到您的代码中,并在“output.close();”之后添加此行:addImageToGallery(file.getAbsolutePath(), YourActivity.this); - Tal Kanel
您提供的代码是否在Activity类中实现?如果是,则YourActivity是您的活动的名称。 - Tal Kanel
如果你问这个问题,那么你可能不仅是在Android上的新手,也是在Java上的新手。 - Tal Kanel
我可以在Skype或其他聊天工具上和你聊天吗?xD - Gatiko06
嗯...是的!但现在要等10分钟。我现在要离开10分钟。我的Skype ID是“talkanel”。 - Tal Kanel
显示剩余4条评论

12

当您要保存图片到画廊时,这是您应该输入的内容

MediaStore.Images.Media.insertImage(getContentResolver(), yourBitmap, yourTitle , yourDescription);

那段代码将在图库末尾添加该图片。因此,请检查您的图库图片以确保。


我可以确定专辑的名称吗? - Daniel Reyhanian
@DanielReyhanian 的路径是:sdcard=>Pictures - sak

7

尝试添加以下内容:

MediaStore.Images.Media.insertImage(getContentResolver(), yourBitmap, yourTitle , yourDescription);

填写yourBitmapyourTitleyourDescription的详细信息,或将其保留为空字符串""


这个工作可以在摄像头拍摄图像时将图像保存在我的目录“:/”。 - Gatiko06

3
你需要在保存图像到相册的函数中添加一个MediaScannerConnection类。这个类会扫描与你的应用程序相关联的相册中的新文件和文件夹。将以下类添加到扫描新保存的图像文件或新添加的图像目录到相册中,或者下载源代码
        MediaScannerConnection.scanFile(this, new String[]{file.toString()}, null,
                new MediaScannerConnection.OnScanCompletedListener() {
                    public void onScanCompleted(String path, Uri uri) {
                        Log.i("ExternalStorage", "Scanned " + path + ":");
                        Log.i("ExternalStorage", "-> uri=" + uri);
                    }
                });

阅读更多


2

对于 Xamarin 同行:

public static void SaveToTheGalley(this string filePath, Context context)
{
    var values = new ContentValues();
    values.Put(MediaStore.Images.Media.InterfaceConsts.DateTaken, Java.Lang.JavaSystem.CurrentTimeMillis());
    values.Put(MediaStore.Images.Media.InterfaceConsts.MimeType, "image/jpeg");
    values.Put(MediaStore.MediaColumns.Data, filePath);
    context.ContentResolver.Insert(MediaStore.Images.Media.ExternalContentUri, values);
}

不要忘记关于android.permission.WRITE_EXTERNAL_STORAGE权限。



我觉得你的回答没有得到足够的赞赏。非常感谢,你为我节省了大量时间,我的代码完美运行。同时,看到人们也关心使用Xamarin的人感到很高兴。 - Daniel Reyhanian

2

As

MediaStore.MediaColumns.Data

并且

MediaStore.Images.Media.insertImage

现在已经过时了,这里是我使用位图的方法

fun addImageToGallery(
    fileName: String,
    context: Context,
    bitmap: Bitmap
) {

        val values = ContentValues()
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            values.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis())
        }
        values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg")
        values.put(MediaStore.Images.ImageColumns.DISPLAY_NAME, fileName)
        values.put(MediaStore.Images.ImageColumns.TITLE, fileName)

        val uri: Uri? = context.contentResolver.insert(
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
            values
        )
        uri?.let {
            context.contentResolver.openOutputStream(uri)?.let { stream ->
                val oStream =
                    BufferedOutputStream(stream)
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, oStream)
                oStream.close()
            }
        }

}

1

请参考我使用过的这段代码:

public static boolean saveImageToGallery(Context context, Bitmap bmp) {
    // First save the picture
    String storePath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "dearxy";
    File appDir = new File(storePath);
    if (!appDir.exists()) {
        appDir.mkdir();
    }
    String fileName = System.currentTimeMillis() + ".jpg";
    File file = new File(appDir, fileName);
    try {
        FileOutputStream fos = new FileOutputStream(file);
        //Compress and save pictures by io stream
        boolean isSuccess = bmp.compress(Bitmap.CompressFormat.JPEG, 60, fos);
        fos.flush();
        fos.close();

        //Insert files into the system Gallery
        //MediaStore.Images.Media.insertImage(context.getContentResolver(), file.getAbsolutePath(), fileName, null);

        //Update the database by sending broadcast notifications after saving pictures
        Uri uri = Uri.fromFile(file);
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
        if (isSuccess) {
            return true;
        } else {
            return false;
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return false;
}

1

你应该修改这段代码 -

try {
        output = new FileOutputStream(file);

        // Compress into png format image from 0% - 100%
        bitmap1.compress(Bitmap.CompressFormat.JPEG, 100, output);
        output.flush();
        output.close();
        String url = Images.Media.insertImage(getContentResolver(), bitmap1,
        "Wallpaper.jpg", null);
    }

    catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

这会压缩图像并改变图像的大小。 - Shajeel Afzal

0
使用以下代码使您的图像在画廊中可见。
    public void saveImageToGallery(Context context, Uri path) {
        // Create image from the Uri for storing it in the preferred location
        Bitmap bmp = null;
        ContentResolver contentResolver = getContentResolver();
        try {
            if(Build.VERSION.SDK_INT < 28) {
                bmp = MediaStore.Images.Media.getBitmap(contentResolver, path);
            } else {
                ImageDecoder.Source source = ImageDecoder.createSource(contentResolver, path);
                bmp = ImageDecoder.decodeBitmap(source);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        // Store image to internal storage/ImagePicker directory
        String storePath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "ImagePicker";
        File appDir = new File(storePath);
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        String fileName = System.currentTimeMillis() + ".jpg";
        File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            boolean isSuccess = bmp.compress(Bitmap.CompressFormat.JPEG, 60, fos);
            fos.flush();
            fos.close();
            
            // Broadcast the image & make it visible in the gallery
            Uri uri = Uri.fromFile(file);
            context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
            if (isSuccess) {
                Toast.makeText(context, "File saved to gallery", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(context, "Failed to save", Toast.LENGTH_SHORT).show();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接