从unity保存图片到相册,游戏中需要一些保存图片到相册的操作,在这里分享一些自己在网上查的资料。话不多说直接上代码。
public IEnumerator getTexture2d(Texture2D t)
{
yield return new WaitForEndOfFrame();
byte[] bytes = t.EncodeToPNG();
t.Compress(true);
t.Apply();
System.DateTime now = new System.DateTime();
now = System.DateTime.Now;
string filename = string.Format("image{0}{1}{2}{3}.png", now.Day, now.Hour, now.Minute, now.Second);
StreamWriter sw;
FileInfo ft = new FileInfo(filepath);
if (!ft.Exists)
{
sw = ft.CreateText();
}
else
{
sw = ft.AppendText();
}
sw.WriteLine(filename);
sw.Close();
sw.Dispose();
if (Application.platform == RuntimePlatform.Android)
{
string origin = Path_save;
destination = "/mnt/sdcard/DCIM/abuddz";
if (!Directory.Exists(destination))
{
Directory.CreateDirectory(destination);
}
destination = destination + "/" + filename;
Path_save = destination;
Debug.Log("路径:" + Path_save);
File.WriteAllBytes(Path_save, bytes);
AndroidJavaClass obj = new AndroidJavaClass("com.ryanwebb.androidscreenshot.MainActivity");
obj.CallStatic<bool>("scanMedia", Path_save);
}
else if (Application.platform == RuntimePlatform.IPhonePlayer)
{
string origin = Path_save;
destination = Application.persistentDataPath;
if (!Directory.Exists(destination))
{
Directory.CreateDirectory(destination);
}
destination = destination + "/" + filename;
Path_save = destination;
Debug.Log("路径:" + Path_save);
File.WriteAllBytes(Path_save, bytes);
iOSSaveQR(Path_save);
}
}
|