Unity save image to android / ios gallery

I am trying to save my screenshot in the image gallery of my device. It works great, but it will not appear 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);

Saves the image in the right place. If I look at the SD card, it is. But he does not appear in the gallery. So I tried this after File.move to update 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 it does nothing. I work with the latest version of Unity version 5.3 and should work on all Android and ios devices. Any ideas how to make this work and appear anywhere in the gallery?

Thanks!

+5
source share
4 answers
    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  });

, . _path myScreenshotLocation. , KitKat 4.4 .

+2

.

, , "REFRESHING ANDROID PHONE PHOTO GALLERY" ( Android 4.4+, ?).

0

, WRITE_PERMISSIOS_EXTERNAL Android.

There is a plugin for handling Native Gallery in Unity called "Native Gallery Assist" that will help you with such functionality. We used it for users in a social application / game so that users can take pictures with their help and share them with each other. ( https://www.assetstore.unity3d.com/en/#!/content/60922 )

We had the same problem before we added write permissions.

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<!--- Thomas: Needed by Native Gallery Assist to be able to save images to the album  -->
-1
source

Source: https://habr.com/ru/post/1623919/


All Articles