/// <summary> /// 将一个纹理对象保存为文件。要求<see cref="Texture2D.isReadable"/>开启 /// </summary> /// <param name="texture"></param> /// <param name="path">路径名,不以斜杠结尾</param> /// <param name="fileName">文件名,不包含扩展名</param> /// <param name="format"></param> /// <param name="destroyAfterSave">是否保存后销毁原texture,调用<c>DestroyImmediate</c></param> /// <returns>生成文件的路径</returns> public static string SaveTexture2DtoFile(Texture2D texture, string path, string fileName, SavingTextureFormat format, bool destroyAfterSave) { if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } if (!Directory.Exists(path)) { EditorUtility.DisplayDialog("Error", "SaveTexture2DtoFile: Cannot create path " + path, "OK"); return(null); } byte[] bytes; string fName; switch (format) { case SavingTextureFormat.JPG: bytes = texture.EncodeToJPG(); fName = path + "/" + fileName + ".jpg"; break; case SavingTextureFormat.PNG: bytes = texture.EncodeToPNG(); fName = path + "/" + fileName + ".png"; break; case SavingTextureFormat.TGA: bytes = texture.EncodeToTGA(); fName = path + "/" + fileName + ".tga"; break; case SavingTextureFormat.EXR: bytes = texture.EncodeToEXR(); fName = path + "/" + fileName + ".exr"; break; default: throw new ArgumentOutOfRangeException(nameof(format), format, null); } FileStream file = File.Open(fName, FileMode.Create); BinaryWriter writer = new BinaryWriter(file); writer.Write(bytes); file.Close(); if (destroyAfterSave) { UnityEngine.Object.DestroyImmediate(texture); } return(fName); }
/// <summary> /// 将一个纹理对象保存为文件。要求<see cref="Texture2D.isReadable"/>开启 /// </summary> /// <param name="texture"></param> /// <param name="filePathWithoutExt">文件路径,不包含扩展名</param> /// <param name="format"></param> /// <param name="destroyAfterSave">是否保存后销毁原texture,调用<c>DestroyImmediate</c></param> /// <returns>生成文件的路径</returns> public static string SaveTexture2DtoFile(Texture2D texture, string filePathWithoutExt, SavingTextureFormat format, bool destroyAfterSave) { string path = Path.GetDirectoryName(filePathWithoutExt); string fn = Path.GetFileName(filePathWithoutExt); return(SaveTexture2DtoFile(texture, path, fn, format, destroyAfterSave)); }