Unity中如何从jpg或png文件创建Texture2D
2012-07-28 11:43
190 查看
使用Texture2D的LoadImage方法即可实现从jpg或png文件创建Texture2D。经验证,当发布的目标平台为iOS时,此方法也是有效的。
function LoadImage (data : byte[]) : boolean
Description
Loads an image from a byte array.This function loads a JPG or PNG image from raw byte[] array.
C#
using UnityEngine; using System.Collections; public class example : MonoBehaviour { public TextAsset imageTextAsset; void Start() { Texture2D tex = new Texture2D(4, 4); tex.LoadImage(imageTextAsset.bytes); renderer.material.mainTexture = tex; } }
This function replaces texture contents with new image data. After LoadImage, texture size and format might change. JPG files are loaded into RGB24 format,
PNG files are loaded into ARGB32 format. If
texture format before calling LoadImage is DXT1 or DXT5,
then the loaded image will be DXT-compressed (into DXT1 for JPG images and DXT5 for PNG images).
例子:
//imagePath是jpg或png图片的路径
FileStream fs = new System.IO.FileStream(imagePath, System.IO.FileMode.Open, System.IO.FileAccess.Read);
byte[] thebytes =
new byte[fs.Length];
fs.Read(thebytes,
0, (int)fs.Length);
//实例化一个Texture2D,宽和高设置可以是任意的,因为当使用LoadImage方法会对Texture2D的宽和高会做相应的调整
Texture2D texture =
new Texture2D(1,1);
texture.LoadImage(thebytes);
material.mainTexture = texture;
material.mainTextureScale =
new Vector2(1,
1);
material.mainTextureOffset =
new Vector2(0,
0);
相关文章推荐
- [Q]如何将图纸转换为PDF、JPG、PNG、plt、DWF、DWFx、XPS等格式文件
- 如何用正则匹配后缀名不为.jpg, .css, .js, .html, .htm, .png的文件
- 如何优化PNG,JPG图片减小图片文件大小
- PDF文件转化成word,ppt,excel,图片(png,jpg...),tiff,rtf,txt,html,PDF组合,PDF编辑,PDF创建
- Java如何在不存在文件夹的目录下创建文件
- java web 如何创建一个可供访问的文件(通过url访问)
- 如何创建.gitignore文件,忽略不必要提交的文件
- ORACLE ASM环境中如何删除和创建表空间(数据文件)
- 如何为php cli模式独立创建配置文件
- 一种强行指定dll assembly读取其相应*.dll.config配置文件的方法(又名:如何创建.net 的DCOM)
- 如何在Android Studio中创建一个selector.xml文件
- 如何创建并发布Google Earth KML 地标文件?
- 如何使用PHP DOM创建动态的XML文件
- ios创建的sqlite数据库文件如何从ios模拟器中导出
- 如何创建自定义的文件类型关联
- 如何获得创建控制文件的脚本并重建控制文件
- UnityProject面板中右键创建新的Lua脚本以及修改文件默认打开方式的编辑器
- 如何允许 WinXP 和 Win7 自动创建 dump 文件
- 如何创建自定义的文件类型关联
- iOS Xcode 6以后如何创建预编译文件(pch)