简体   繁体   中英

Load Bitmap into memory in Unity using System.Drawing

Using 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. Please note that I am not interested in saving this bmp as an asset or anything like that. I am only looking to load it into RAM where I can do some calculations. 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
  • AssetDatabase.GetAssetPath(mainImg) resolves to 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 . 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?

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:

  1. Go to Edit -> Project Settings -> Player. Change the API Compatability Level from .NET 2.0 Subset to .NET 2.0.
  2. Add an mcs.rsp to my unity projects root Asset folder. Open in it in a text editor and on the first line, enter: -r:System.Drawing.dll . Save.
  3. Close and reopen Unity.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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