public class SaveImagesToPlartform : MonoBehaviour
{
/// <summary>
/// 保存图片
/// </summary>
/// <param name="texture"></param>
/// <returns></returns>
private void SaveImages()
{
string path = Application.streamingAssetsPath;
#if UNITY_ANDROID && !UNITY_EDITOR
path = "/sdcard/DCIM/Camera"; //设置图片保存到设备的目录.
#endif
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
string savePath = path + "/" + "test" + ".png";
try
{
Application.HasUserAuthorization(UserAuthorization.Microphone);
byte[] data = DeCompress(ScreenCapture.CaptureScreenshotAsTexture()).EncodeToPNG();
File.WriteAllBytes(savePath, data);
OnSaveImagesPlartform(savePath);
}
catch
{
}
}
/// <summary>
/// 刷新相册(不需要单独创建原生aar或jar)
/// </summary>
/// <param name="path"></param>
private void OnSaveImagesPlartform(string filePath)
{
#if UNITY_ANDROID && !UNITY_EDITOR
string[] paths = new string[1];
paths[0] = filePath;
using (AndroidJavaClass PlayerActivity = new AndroidJavaClass("com.unity3d.player.UnityPlayer"))
{
AndroidJavaObject playerActivity = PlayerActivity.GetStatic<AndroidJavaObject>("currentActivity");
using (AndroidJavaObject Conn = new AndroidJavaObject("android.media.MediaScannerConnection", playerActivity, null))
{
Conn.CallStatic("scanFile", playerActivity, paths, null, null);
}
}
#endif
}
/// <summary>
/// 压缩图片
/// </summary>
/// <param name="source"></param>
/// <returns></returns>
public Texture2D DeCompress(Texture2D source)
{
RenderTexture renderTex = RenderTexture.GetTemporary(
source.width,
source.height,
0,
RenderTextureFormat.Default,
RenderTextureReadWrite.Linear);
Graphics.Blit(source, renderTex);
RenderTexture previous = RenderTexture.active;
RenderTexture.active = renderTex;
Texture2D readableText = new Texture2D(source.width, source.height);
readableText.ReadPixels(new Rect(0, 0, renderTex.width, renderTex.height), 0, 0);
readableText.Apply();
RenderTexture.active = previous;
RenderTexture.ReleaseTemporary(renderTex);
return readableText;
}
}
unity2022截屏保存到安卓相册
最新推荐文章于 2025-06-28 22:32:12 发布