从unity保存图片到相册,游戏中需要一些保存图片到相册的操作,在这里分享一些自己在网上查的资料。话不多说直接上代码。
//传的参数是自己获取的图片
public IEnumerator getTexture2d(Texture2D t)
{//截图操作
yield return new WaitForEndOfFrame();
//截图保存的图片
//Texture2D t = new Texture2D(Screen.width, Screen.height, TextureFormat.RGB24, false);//t.ReadPixels(new Rect(0, 0,Screen.width, Screen.height), 0, 0, true);//设置屏幕的大小
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);
//发送给ios 发送路径
iOSSaveQR(Path_save);
}
}
如果有不懂的或者更好的方法欢迎在下方留言。