Unity Get Image From Gallery Android
Hello everyone, want to get image from gallery in android. But there are plugins that are paid. Do not worry. We are here to help you. From below code, you can pick image from gallery in Android. Remember that this script only work on Android device. Make sure you have enabled storage permission in AndroiManifiest.xml
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Now create a c# script GalleryManager.cs
using UnityEngine; using System.Collections; public class GalleryManager : MonoBehaviour { // This is the code that will be executed when the user picks an image void OnImagePicked(string imagePath) { // Do something with the image path (e.g. load it into a texture) Debug.Log("Image picked: " + imagePath); } // This function will be called when the user clicks a button to open the gallery public void OpenGallery() { // Get the current activity AndroidJavaClass unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer"); AndroidJavaObject currentActivity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity"); // Create an intent to open the gallery AndroidJavaObject intent = new AndroidJavaObject("android.content.Intent"); intent.Call<AndroidJavaObject>("setType", "image/*"); intent.Call<AndroidJavaObject>("setAction", "android.intent.action.GET_CONTENT"); // Start the activity and wait for a result currentActivity.Call("startActivityForResult", intent, 0); } // This function will be called by Unity when the activity result is received void OnActivityResult(int requestCode, int resultCode, AndroidJavaObject data) { // Check if the result is OK if (resultCode == -1) { // Get the URI of the selected image AndroidJavaObject uri = data.Call<AndroidJavaObject>("getData"); string imagePath = uri.Call<string>("getPath"); // Call the OnImagePicked function to handle the selected image OnImagePicked(imagePath); } } }
Now in OnImagePicked method you can get the url of picked image.