C# 如何在运行时使用.bmp文件并在Unity中创建纹理?

C# 如何在运行时使用.bmp文件并在Unity中创建纹理?,c#,unity3d,textures,bmp,texture2d,C#,Unity3d,Textures,Bmp,Texture2d,我在一个Unity项目中工作,用户选择用于制作纹理2D并粘贴到模型的图像文件(采用.bmp格式),我创建下一个代码,我可以使用.png和.jpg文件,但当我尝试加载.bmp时,我只得到一个(我假设)带有红色“”的默认纹理符号,所以我认为对于图像格式,如何在运行时使用.bmp文件创建纹理 这是我的代码: public static Texture2D LoadTexture(string filePath) { Texture2D tex = null; byte[] fileDa

我在一个Unity项目中工作,用户选择用于制作
纹理2D
并粘贴到模型的图像文件(采用
.bmp
格式),我创建下一个代码,我可以使用
.png
.jpg
文件,但当我尝试加载
.bmp
时,我只得到一个(我假设)带有红色“”的默认纹理符号,所以我认为对于图像格式,如何在运行时使用
.bmp
文件创建纹理

这是我的代码:

public static Texture2D LoadTexture(string filePath)
{
    Texture2D tex = null;
    byte[] fileData;

    if (File.Exists(filePath))
    {
        fileData = File.ReadAllBytes(filePath);
        tex = new Texture2D(2, 2);
        tex.LoadImage(fileData);
    }

    return tex;
}
该函数仅用于将PNG/JPG图像字节数组加载到
纹理中。它不支持
.bmp
,因此红色符号通常表示图像已损坏或未知

要在Unity中加载
.bmp
图像格式,您必须阅读并理解
.bmp
格式规范,然后实现将其字节数组转换为Unity纹理的方法。幸运的是,这已经由另一个人完成了。抓取
BMPLoader
插件

要使用它,请使用B83.Image.BMP包含
名称空间:

public static Texture2D LoadTexture(string filePath)
{
    Texture2D tex = null;
    byte[] fileData;

    if (File.Exists(filePath))
    {
        fileData = File.ReadAllBytes(filePath);

        BMPLoader bmpLoader = new BMPLoader();
        //bmpLoader.ForceAlphaReadWhenPossible = true; //Uncomment to read alpha too

        //Load the BMP data
        BMPImage bmpImg = bmpLoader.LoadBMP(fileData);

        //Convert the Color32 array into a Texture2D
        tex = bmpImg.ToTexture2D();
    }
    return tex;
}
您还可以跳过
文件.ReadAllBytes(文件路径)分割并将
.bmp
图像路径直接传递到
BMPLoader.LoadBMP
函数:

public static Texture2D LoadTexture(string filePath)
{
    Texture2D tex = null;

    if (File.Exists(filePath))
    {
        BMPLoader bmpLoader = new BMPLoader();
        //bmpLoader.ForceAlphaReadWhenPossible = true; //Uncomment to read alpha too

        //Load the BMP data
        BMPImage bmpImg = bmpLoader.LoadBMP(filePath);

        //Convert the Color32 array into a Texture2D
        tex = bmpImg.ToTexture2D();
    }
    return tex;
}

请注意,BMP加载程序不会检查镜像BMP。这将导致绘制错误。