简体   繁体   中英

Bitmap.Save() method is not working in Unity source

I wanna implement 'Bitmap to Texture2D' function in Unity.

I learned to make Texture2D instance, use this syntax below.

// **LoadImage(byte[] arr)** can load byte array data and make Texture2D
var data = BitmapToByteMethod(bitmap);

var textureCanvas = new Texture2D(bitmap.Width, bitmap.Height, TextureFormat.ARGB32, false);
textureCanvas.LoadImage(data);
textureCanvas.Apply();

To make this function I did like this.

using (MemoryStream memoryStream = new MemoryStream())
{
    ImageCodecInfo jpgEncoder = GetEncoder(ImageFormat.Jpeg);

    System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality;
    EncoderParameters myEncoderParameters = new EncoderParameters(1);
    EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, 100L);
    myEncoderParameters.Param[0] = myEncoderParameter;

// this is the point error occurred.

    bitmap.Save(memoryStream, jpgEncoder, myEncoderParameters);
    //bitmap.Save(memoryStream, ImageFormat.Jpeg);
    return memoryStream.ToArray();
}

First, I have a bitmap image. Second, Convert Bitmap to byte array. (It works well in my c# sample project.) But when I try to run that function in Unity, Unity program shut down after do 'Bitmap.Save()' method.

I'm beginner of Unity so this is not easy to solve the problems.. below is the source sample code in my project.

System.Drawing is not supported by Unity3D. Probably because it's based on GDI+ and Unity is multiplatform, so it couldn't be used anywhere but on Windows (Mono has its own version of GDI+ for *nix systems, but it doesn't work with Unity either). The official reason seems to be "System.Drawing doesn't work with OpenGL/DirectX".

There seem to be some hacks you could use to make this work, but it only makes sense if you want to stick to Windows. If you want to go this way, there's an answer on the Unity3D forums that should help you - http://answers.unity3d.com/answers/253571/view.html

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