第一步,加载图片:
string url = "图片所在路径";
Texture2D texture = (Texture2D)Resources.Load(url);
第二步,写入手机相册:
byte[] bytes = texture.EncodeToPNG();
string path = Application.persistentDataPath;
#if UNITY_ANDROID
path = "/storage/emulated/0/DCIM/相册里面的新文件夹";
#endif
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
string savePath = string.Format("{0}/{1}.png", path, "图片名");
File.WriteAllBytes(savePath, bytes);
第三步,刷新手机相册:
unity端,调用这个方法,参数为上文的savePath:
public void savePng(string fileName)
{
#if UNITY_IOS
#elif UNITY_ANDROID
androidContext().Call("scanFile", fileName);
#endif
}
#if UNITY_ANDROID
public AndroidJavaObject androidContext()
{
return new AndroidJavaClass("com.unity3d.player.UnityPlayer").GetStatic<AndroidJavaObject>("currentActivity");
}
#endif
android端代码:
public void scanFile(String filePath) {
Log.i("Unity", "------------filePath"+filePath);
Intent scanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
scanIntent.setData(Uri.fromFile(new File(filePath)));
this.sendBroadcast(scanIntent);
}
完毕!
需要注意的有以下几点:
1.贴图文件Advanced下面的Non Power of 2 需要设置成None,Read/Write Enabled设置为true,不然会有各种异常。
2.存储路径最好直接设置到相册里面,如上文path那样,最初用的是Application.persistentDataPath,但是部分手机刷新不到相册,部分手机直接刷新到其他相册。
3.因为可能存储权限等等问题,会有异常发生,所以最好存储的时候捕获下异常,以免因为异常影响应用稳定性