在开发中,经常需要对图片和byte字节流进行互转,但是有时候会出现Texture2D转byte的时候byte字节数组会比原始byte数组大的情况。关键问题就是使用EncodeToPNG等Texture2D自带的方法。如果图片格式是jpg的时候,用EncodeToPNG转byte数组的时候就大10多倍。
所以,在转byte数组前,要清楚的知道图片格式,然后根据格式使用不同的方法。尤其是图片为png格式的时候,因为png格式在转换的时候会带有透明通道信息,也就是本来jpg等格式没有透明也会带有透明通道。这也是byte数组会大10多倍的原因。文章源自大腿Plus-https://www.zhaoshijun.com/archives/2043
下面是根据不同格式,使用不同方法转byte数组的代码。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
using System; using System.IO; using UnityEngine; public enum PictureType { Jpg, Png, Exr, Tga, } public static class PictureTools { public static byte[] CreateByte(Texture2D texture, PictureType type = PictureType.Jpg) { //根据不同图片格式转换成bytes,如果不根据格式转,jpg转png时会出现byte比原始数据大的情况。 byte[] textureByte = null; switch (type) { case PictureType.Jpg: textureByte = texture.EncodeToJPG(); break; case PictureType.Png: textureByte = texture.EncodeToPNG(); break; case PictureType.Exr: textureByte = texture.EncodeToEXR(); break; case PictureType.Tga: textureByte = texture.EncodeToTGA(); break; } return textureByte; } } |
如果不知道具体格式,并且图片没有透明通道的话,尽量用EncodeToJPG进行转换。文章源自大腿Plus-https://www.zhaoshijun.com/archives/2043 文章源自大腿Plus-https://www.zhaoshijun.com/archives/2043
我的微信
微信扫一扫

shijun_z
我的QQ
QQ扫一扫

846207670
评论