Hi I’m trying to convert c# code that works with System.Drawing.Bitmap into Unity. What I’m trying to do is swap out all references to Bitmap with Texture2D.
I have the following method:
/// <summary>
///
/// Produces a binary Matrix with Dimensions
/// For the threshold, we take the sum of weighted R,g,b value. The sum of weights must be 1.
/// The result fills the field bm;
/// </summary>
/// <param name="bitmap"> A Bitmap, which will be transformed to a binary Matrix</param>
/// <returns>Returns a binaray boolean Matrix </returns>
static Bitmap_p ConvertBitmap(Bitmap bitmap)
{
byte[] Result = new byte[bitmap.Width * bitmap.Height];
BitmapData SourceData = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
unsafe
{
byte* SourcePtr = (byte*)(void*)SourceData.Scan0;
int l = Result.Length;
Debug.Log(l);
for (int i = 0; i < l; i++)
{
// if ((0.2126 * (double)SourcePtr[4 * i + 2] + 0.7153 * (double)SourcePtr[4 * i + 1] + 0.0721 * (double)SourcePtr[4 * i]) < Treshold*255)
if (((double)SourcePtr[4 * i + 2] + (double)SourcePtr[4 * i + 1] + (double)SourcePtr[4 * i]) < Treshold * 255 * 3)
Result[i] = 1;
else
Result[i] = 0;
}
}
bitmap.UnlockBits(SourceData);
bm = new Bitmap_p(bitmap.Width, bitmap.Height);
bm.data = Result;
return bm;
}
}
I tried to do this:
static Bitmap_p ConvertBitmap(Texture2D texture)
{
byte[] original = texture.EncodeToPNG();
byte[] result = new byte[texture.width * texture.height];
for (int i = 0; i < original.Length; i++)
{
if (((double)original[4 * i + 2] + (double)original[4 * i + 1] + (double)original[4 * i]) < Treshold * 255 * 3)
result[i] = 1;
else
result[i] = 0;
}
bm = new Bitmap_p(texture.width, texture.height);
bm.data = result;
return bm;
}
but I’m getting array index out of bounds errors. I’m completely not used to working with pointers so I’m confused as heck. Also, perhaps PixelFormat.Format32bppArgb
is a different format than EncodeToPNG? Can anyone help me along?