I'm working in a Unity Project where the user choose image files (in .bmp
format) that is used to make a Texture2D
and pasted to a model, I create the next code, I work fine with .png
and .jpg
file, but when I try load .bmp
I got only a (I assume) default texture with a red "?" symbol, so I think is for the image format, how can I create a Texture using .bmp
files at run-time?
this is my code:
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;
}
The Texture2D.LoadImage
function is only used to load PNG/JPG image byte array into a Texture
. It doesn't support .bmp
so the red symbol which usually means corrupted or unknown image is expected.
To load .bmp
image format in Unity, you have to read and understand the .bmp
format specification then implement a method that converts its byte array into Unity's Texture. Luckily, this has already been done by another person. Grab the BMPLoader
plugin here.
To use it, include the using B83.Image.BMP
namespace:
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;
}
You can also skip the File.ReadAllBytes(filePath);
part and pass the .bmp
image path directly to the BMPLoader.LoadBMP
function:
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With