using System.IO;
using UnityEngine;
///
/// 将图片保存在本地
///
public class SaveImageLocalComputer:SingletonManager
{
///
/// 保存图片
///
/// 图片
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
{
}
}
///
/// 刷新相册(不需要单独创建原生aar或jar)
///
///
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("currentActivity");
using (AndroidJavaObject Conn = new AndroidJavaObject("android.media.MediaScannerConnection", playerActivity, null))
{
Conn.CallStatic("scanFile", playerActivity, paths, null, null);
}
}
#endif
}
///
/// 压缩图片
///
///
///
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;
}
}