简体   繁体   English

使用 System.Drawing 在 Unity 中将 Bitmap 加载到 memory 中

[英]Load Bitmap into memory in Unity using System.Drawing

Using Unity 2017.4.33f1-Personal.使用 Unity 2017.4.33f1-Personal。

I'm trying to use the Image.FromFile method in the System.Drawing namespace to load a Bitmap in a GameObject's logic.我正在尝试使用 System.Drawing 命名空间中的Image.FromFile方法在 GameObject 的逻辑中加载 Bitmap。 Please note that I am not interested in saving this bmp as an asset or anything like that.请注意,我对将此 bmp 保存为资产或类似的东西不感兴趣。 I am only looking to load it into RAM where I can do some calculations.我只是想把它加载到我可以做一些计算的 RAM 中。 I have tried the following:我尝试了以下方法:

var result = Image.FromFile(
    AssetDatabase.GetAssetPath(mainImg)
) as Bitmap;

But I get the following error:但我收到以下错误:

InvalidProgramException: Invalid IL code in System.Drawing.Image:FromFile (string): IL_0000: ret    

FYI,供参考,

  • mainImg is a reference to a Texture2D resource mainImg是对Texture2D资源的引用
  • AssetDatabase.GetAssetPath(mainImg) resolves to Assets/CustomPackages/SeededConstruction/PuzzleBuilder/Input/main.bmp AssetDatabase.GetAssetPath(mainImg)解析为Assets/CustomPackages/SeededConstruction/PuzzleBuilder/Input/main.bmp

I've also tried a bunch of other goofy things, including getting the absolute path and replacing forward slashes with backslashes like this:我还尝试了许多其他愚蠢的事情,包括获取绝对路径和用反斜杠替换正斜杠,如下所示:

var result = Image.FromFile(    
    Directory.GetCurrentDirectory() 
    + "\\" 
    + AssetDatabase.GetAssetPath(mainTileset)
    .Replace('/', '\\')
) as Bitmap;

In this case, the path resolves to D:\_Projects\2dGenerator\PlatformGeneration\Assets\CustomPackages\SeededConstruction\PuzzleBuilder\Input\main.bmp .在这种情况下,路径解析为D:\_Projects\2dGenerator\PlatformGeneration\Assets\CustomPackages\SeededConstruction\PuzzleBuilder\Input\main.bmp However, this returns the same error as above.但是,这会返回与上述相同的错误。

What am I doing wrong here?我在这里做错了什么? It seems like this methodology works fine in normal.Net applications, why not in Unity?看起来这种方法在 normal.Net 应用程序中运行良好,为什么在 Unity 中不行呢?

It turns out it was not any kind of filepath issue.事实证明这不是任何类型的文件路径问题。 In order to properly reference System.Drawing in Unity 2017.4.33f1-Personal, I took the following steps:为了在 Unity 2017.4.33f1-Personal 中正确引用 System.Drawing,我采取了以下步骤:

  1. Go to Edit -> Project Settings -> Player. Go 编辑 -> 项目设置 -> 播放器。 Change the API Compatability Level from .NET 2.0 Subset to .NET 2.0.将 API 兼容性级别从 .NET 2.0 子集更改为 .NET 2.0。
  2. Add an mcs.rsp to my unity projects root Asset folder.mcs.rsp添加到我的统一项目根资产文件夹中。 Open in it in a text editor and on the first line, enter: -r:System.Drawing.dll .在文本编辑器中打开它,在第一行输入: -r:System.Drawing.dll Save.节省。
  3. Close and reopen Unity.关闭并重新打开 Unity。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM