I need to take a picture from the game camera (screenshot) and save the image in VR.
Take a screenshot I got it in several ways.
The biggest problem is saving the image in VR.
A screenshot only appears when I run it in Unity game mode.
I did a test in Start() and passing a sprite just to try to save in VR based on this tutorial but without success:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
public class ScreenAndroid : MonoBehaviour
{
//public AndroidExtensions Screen1 = new AndroidExtensions();
public Texture2D Imagem;
public string title;
public string description;
private void Start()
{
AndroidExtensions.SaveImageToGallery(Imagem, title, description);
var appName = Application.identifier;
var fileName = $"{appName}-{DateTime.Now:yyMMdd-hhmmss}";
#if UNITY_ANDROID
AndroidExtensions.SaveImageToGallery(Imagem, fileName, "Some description");
#endif
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[SerializeField]
public class AndroidExtensions
{
private static AndroidJavaObject _activity;
private static AndroidJavaObject Activity
{
get
{
if (_activity != null) return _activity;
var unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
_activity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity");
return _activity;
}
}
private const string MediaStoreImagesMediaClass = "android.provider.MediaStore$Images$Media";
public static string SaveImageToGallery(Texture2D texture2D, string title, string description)
{
using var mediaClass = new AndroidJavaClass(MediaStoreImagesMediaClass);
using var cr = Activity.Call<AndroidJavaObject>("getContentResolver");
var image = Texture2DToAndroidBitmap(texture2D);
var imageUrl = mediaClass.CallStatic<string>("insertImage", cr, image, title, description);
Debug.Log("imageUrl");
return imageUrl;
}
private static AndroidJavaObject Texture2DToAndroidBitmap(Texture2D texture2D)
{
var encoded = texture2D.EncodeToPNG();
using var bf = new AndroidJavaClass("android.graphics.BitmapFactory");
return bf.CallStatic<AndroidJavaObject>("decodeByteArray", encoded, 0, encoded.Length);
}
}