Hi we have problem with reading bitmap data using C# functions:
we have implemented textmanager and we want to create bitmap with Pixelformat
Format1bppIndexed
for text entered in my textbox.
We want to get bitmap data in byte array, for that purpose I am using Bitmap.LockBits methode. to copy Bitmapdata in to byte array I am creating byte array,Array size is calculated using "BitmapData.Stride" and "BitmapData.Width".
We have VC++ application there we have same functionality to read bitmap data in byte array and write to some hardware, we want to implment same in C#. I tried to port code in C# code is working fine but output is not as per expectations.
When I tried to get byte array in C# and VC++ for same text , byte array content are different. It should be same in VC++ and C# , Am I missing some steps?
I am not able to find out solution for same.
dose any body face same issue in development?
private void button2_Click(object sender, EventArgs e)
{
Bitmap bmp = new Bitmap(1, 1);
Graphics g = Graphics.FromImage(bmp);
int w = (int)g.MeasureString(textBox1.Text, fontDialog1.Font).Width;
int h = (int)g.MeasureString(textBox1.Text, fontDialog1.Font).Height;
Bitmap bmp2 = new Bitmap(w, h,PixelFormat.Format32bppArgb);
Graphics g2 = Graphics.FromImage(bmp2);
Brush brush = new SolidBrush(Color.White);
g2.FillRectangle(brush, 0, 0, bmp2.Width, bmp2.Height);
Brush brush2 = new SolidBrush(Color.Black);
g2.DrawString(textBox1.Text, fontDialog1.Font, brush2, 0, 0);
g2.Flush();
Bitmap bmp_return = Bitmap_Conversion.ConvertToBitonal(bmp2);
bmp2.Save(@"c:\temp\test.bmp", System.Drawing.Imaging.ImageFormat.Bmp);
bmp_return.Save(@"c:\temp\test1.bmp", System.Drawing.Imaging.ImageFormat.Bmp);
Rectangle rect = new Rectangle(0, 0, bmp_return.Width, bmp_return.Height);
System.Drawing.Imaging.BitmapData bmpData =
bmp_return.LockBits(rect, ImageLockMode.ReadWrite, bmp_return.PixelFormat);
IntPtr ptr = bmpData.Scan0;
int bytes = Math.Abs(bmpData.Stride) * bmp_return.Height;
byte[] rgbValues = new byte[bytes];
System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes);
StreamWriter fs = new StreamWriter(Environment.GetEnvironmentVariable("tmp") + @"\Hoge.txt");
fs.Close();
bmp2.Dispose();
bmp.Dispose();
g.Dispose();
}
public static Bitmap BitmapTo1Bpp(Bitmap img)
{
int w = img.Width;
int h = img.Height;
Bitmap bmp = new Bitmap(w, h, PixelFormat.Format1bppIndexed);
BitmapData data = bmp.LockBits(new Rectangle(0, 0, w, h), ImageLockMode.ReadWrite, PixelFormat.Format1bppIndexed);
for (int y = 0; y < h; y++)
{
byte[] scan = new byte[(w + 7) / 8];
for (int x = 0; x < w; x++)
{
Color c = img.GetPixel(x, y);
if (c.GetBrightness() >= 0.5) scan[x / 8] |= (byte)(0x80 >> (x % 8));
}
Marshal.Copy(scan, 0, (IntPtr)((int)data.Scan0 + data.Stride * y), scan.Length);
}
bmp.UnlockBits(data);
return bmp;
}