We have an application in Unity3d where we want to take in a byte array formatted in ARGB (0-255 format), convert it to a bitmap and then to a png byte array and display this as a texture2d.
All the separate parts of the system works fine, though when trying to save the bitmap to the MemoryStream in PNG imageFormat Unity Crashes and leaves us with the following error:
Unity Editor [version: Unity
4.2.1f4_4d30acc925c2]Unity.exe caused an Access Violation
(0xc0000005) in module Unity.exe at
0023:00000000.Error occurred at 2013-10-25_152302.
C:\Program Files
(x86)\Unity\Editor\Unity.exe, run by
Commander. 11% memory in use. 0 MB
physical memory [0 MB free]. 0 MB
paging file [0 MB free]. 0 MB user
address space [3511 MB free]. Read
from location 00000000 caused an
access violation.
We have added the dll System.Drawing.dll into the main Asset Folder.
The function which causes the crash (bmp2.Save) works just fine if we set it to save the file to disk instead of to stream.
The following is the main code which tries to save the bitmap to MemoryStream:
// Create bitmap from raw image data
Bitmap bmp = CreateBitmap(rawImageBuffer, header);
// encode byte array to png formated byte array
byte[] resultImageBuffer = null;
using (Bitmap bmp2 = new Bitmap(bmp))
{
using (System.IO.MemoryStream stream = new System.IO.MemoryStream())
{
// This is the line which causes the crash /////////////////////////
bmp2.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
Debug.Log("Saved to stream");
resultImageBuffer = stream.ToArray();
if (resultImageBuffer == null)
Debug.Log("resultImageBuffer is null");
else
Debug.Log("resultImageBuffer length: " + resultImageBuffer.Length);
}
}
Following is the code which converts the raw image data ARGB byte array into a bitmap.
/// <summary>
/// Creates a Bitmap image from raw image data
/// </summary>
/// <param name="rawImage">Raw image data, uncompressed</param>
/// <param name="header">Message header describing original image format</param>
/// <returns>A bitmap</returns>
private Bitmap CreateBitmap(byte[] rawImage, MessageHeader header)
{
// Create bitmap from raw image data
Bitmap bmp = new Bitmap(header.Width, header.Height, header.PixFormat);
BitmapData bmpData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.WriteOnly, bmp.PixelFormat);
Marshal.Copy(rawImage, 0, bmpData.Scan0, rawImage.Length);
bmp.UnlockBits(bmpData);
return bmp;
}
How can we solve the Access Violation so that it can save the bitmap successfully to the memorystream?
What is the Cause of the Access Violation Error?