79 lines
2.7 KiB
C#
79 lines
2.7 KiB
C#
using System.IO;
|
||
using UnityEngine;
|
||
|
||
/// <summary>
|
||
/// 将图片保存在本地
|
||
/// </summary>
|
||
public class SaveImageLocalComputer:SingletonManager<SaveImageLocalComputer>
|
||
{
|
||
/// <summary>
|
||
/// 保存图片
|
||
/// </summary>
|
||
/// <param name="sprite">图片</param>
|
||
public void SaveImages(Sprite sprite)
|
||
{
|
||
Texture2D tex = sprite.texture;
|
||
string path = Application.streamingAssetsPath;
|
||
#if UNITY_ANDROID && !UNITY_EDITOR
|
||
path = "/sdcard/DCIM/Camera"; //设置图片保存到设备的目录.
|
||
#endif
|
||
if (!Directory.Exists(path))
|
||
Directory.CreateDirectory(path);
|
||
string savePath = path + "/" + tex.name + ".png";
|
||
try
|
||
{
|
||
Application.HasUserAuthorization(UserAuthorization.Microphone);
|
||
byte[] data = DeCompress(tex).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>
|
||
private Texture2D DeCompress(Texture2D source)
|
||
{
|
||
RenderTexture renderTex = RenderTexture.GetTemporary(
|
||
source.width,
|
||
source.height,
|
||
0,
|
||
RenderTextureFormat.Default,
|
||
RenderTextureReadWrite.sRGB);
|
||
|
||
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;
|
||
}
|
||
}
|