让我们来导出unity3d中的mainTexture贴图转换保存为png

来源:互联网 发布:联想y5070优化教程 编辑:程序博客网 时间:2024/05/18 14:46

有这么一个需求,我们知道unity3d的模型一般用fbx格式进行导入的。

但fbx里面所引用的贴图文件格式那就是很多,比如TGA,DDS,BMP,等等,各式各样。

我的想法很简单,就是把这些贴图导出成PNG就行了。

大家觉得会说,你用其它软件进行批量转换不就好了?这个可以有!推荐XnView给大家使用!

不过,这不是本篇文章的重点,我就是想用unity3d来实现转换。 


查了一下API,发现Texture2D有一个EncodeToPNG()功能,这就是我想要的!

步骤如下,先找到Material。Material上默认会有一个mainTexture,我们的主材质贴图。

接下来就是获取编码然后保存即可!确实很简单呀


其实写这篇文章前,也查阅了网上其它例子,都是实现全屏截图的功能。

本文虽略有不同,但思路都大同小异。给有需要的朋友们参考~


献上关键unity3d代码C#版本:

public static bool saveMainTextureToPng (string filePath, Material mt){Texture tex = mt.mainTexture;if (tex.GetType () != typeof(Texture2D)) {return false;}Texture2D savedTexture = (Texture2D)tex;try {Texture2D newTexture = new Texture2D (savedTexture.width, savedTexture.height, TextureFormat.RGBA32, false);newTexture.SetPixels (0, 0, savedTexture.width, savedTexture.height, savedTexture.GetPixels ());newTexture.Apply ();byte[] bytes = newTexture.EncodeToPNG ();if (bytes != null && bytes.Length > 0) {File.WriteAllBytes (filePath, bytes);Debug.Log ("转换PNG成功:" + AssetDatabase.GetAssetPath (mt.mainTexture) + "-->" + savedTexture.format.ToString ());}} catch (IOException ex) {Debug.Log ("转换PNG失败:" + AssetDatabase.GetAssetPath (mt.mainTexture));return false;}return true;}


原创粉丝点击