Unity save image to gallery android / ios

11,105
    AndroidJavaClass classPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
    AndroidJavaObject objActivity = classPlayer.GetStatic<AndroidJavaObject>("currentActivity");
    AndroidJavaClass classMedia = new AndroidJavaClass("android.media.MediaScannerConnection");
    classMedia.CallStatic("scanFile", new object[4] { objActivity,
        new string[] { _path },
        new string[] { "image/png" },
        null  });

Try the code above, since you have already saved the image. Just replace the _path with your myScreenshotLocation. Note this will only works with android KitKat 4.4 above.

Share:
11,105
Jenny
Author by

Jenny

Updated on June 04, 2022

Comments

  • Jenny
    Jenny almost 2 years

    I am trying to save my screenshot to the image gallery of my device. It works fine but it won't show up in the gallery.

    This is what I do

    selfie= new Texture2D(Screen.width, Screen.height, TextureFormat.RGB24, false);
    selfie.ReadPixels(new Rect(0, 0,Screen.width, Screen.height), 0, 0,false);
    
    selfie.Apply ();
    byte[] bytes = selfie.EncodeToPNG();
    string filename = "Screenshot.png";
    
    fileLocation = Path.Combine( Application.persistentDataPath, filename );
    File.WriteAllBytes(fileLocation, bytes );
    
    string myFolderLocation = "/mnt/sdcard/DCIM/Camera/";
    myScreenshotLocation = myFolderLocation + filename;
    
    System.IO.File.Move(fileLocation, myScreenshotLocation);
    

    It saves the image on the right place. If I look it up on the sdcard, it is there. But in the gallery it is not showing up. So I tried this after File.move, to refresh the gallery.

    //REFRESHING THE ANDROID PHONE PHOTO GALLERY IS BEGUN
        AndroidJavaClass classPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
        AndroidJavaObject objActivity = classPlayer.GetStatic<AndroidJavaObject>("currentActivity");        
        AndroidJavaClass classUri = new AndroidJavaClass("android.net.Uri");        
        AndroidJavaObject objIntent = new AndroidJavaObject("android.content.Intent", new object[2]{"android.intent.action.MEDIA_MOUNTED", classUri.CallStatic<AndroidJavaObject>("parse", "file://" + myScreenshotLocation)});        
        objActivity.Call ("sendBroadcast", objIntent);
    //REFRESHING THE ANDROID PHONE PHOTO GALLERY IS COMPLETE
    

    But this is doing nothing. I am working with the latest Unity version 5.3 and it should work on all android and ios devices. Any ideas how to get this working and show up anywhere in the galler?

    Thank you!