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

4
我是一个Unity项目的辅助人员,在该项目中,用户选择图像文件(以.bmp格式)用于创建Texture2D并贴到模型上。我编写了下面的代码,对于.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;
}
1个回答

9
Texture2D.LoadImage函数仅用于将PNG/JPG图像字节数组加载到Texture中。它不支持.bmp格式,因此通常表示损坏或未知图像的红色符号是可以预期的。
要在Unity中加载.bmp图像格式,您必须阅读并理解.bmp格式规范,然后实现一种方法,将其字节数组转换为Unity的Texture。幸运的是,另一个人已经完成了这项工作。在这里获取BMPLoader插件。
使用它时,包括using 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;
}

您也可以跳过 File.ReadAllBytes(filePath); 的部分,而是直接将.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;
}

请注意,BMPLoader不会检查镜像图像bmp。这将导致它们被错误地绘制。 - Anthony Burg
@AnthonyBurg:最近我修复了一些加载器的问题,这是由于在 github 上提交的问题。我已经更新了两个版本。现在它可以在高度为负数时翻转纹理。虽然这是一个非常罕见的情况,几乎没有图像编辑器使用这种格式。我还没有足够的时间对加载器进行充分的测试。如果您发现任何奇怪的问题,请随时提交问题。 - Bunny83

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接