这里主要记录一下在Unity中加载本地图片的方法
1、通过unity再带的texture.LoadImage来加载一些jpg、png等(无法加载bmp)
public static Texture2D LoadTextureFromLoadImage(string loadPath)
{
var imageData = File.ReadAllBytes(loadPath);
var texture = new Texture2D(8, 8);
var rect = new Rect(0, 0, texture.width, texture.height);
texture.LoadImage(imageData);
return texture;
}
2、通过System.Drawing.Bitmap去加载(加载bmp)
public static Texture2D LoadTextureFromBitMap(string loadPath)
{
Texture2D texture = null;
Bitmap bmpImage = new Bitmap(loadPath);
texture = new Texture2D(bmpImage.Width, bmpImage.Height);
for (int y = 0; y < bmpImage.Height; y++)
{
for (int x = 0; x < bmpImage.Width; x++)
{
System.Drawing.Color color = bmpImage.GetPixel(x, y);
texture.SetPixel(x, bmpImage.Height - y - 1, new Color32(color.R, color.G, color.B, color.A));
}
}
texture.Apply();
bmpImage.Dispose();
return texture;
}
这个就是通过插件System.Drawing插件里的方法去加载,这种方式只需要将对应插件导入到Unity中,就引用命名空间就可以使用了,需要注意的是 .NET Standard 2.1并不支持他,所以对于使用(.NET Standard 2.1)的已有项目中加载bmp通过这种方式就不合适,Api Compatibility Level这个选项对于已有项目是