c# - X Bitmap processor not working
I have been working on an image 开发者_Go百科processor recently and decided to look at the old XBitmap file format (XBM). I'm working in c# to copy the pixel data from these files to a bitmap. I have managed to set up and algorithm that seems to work in theory, but doesn't display correctly. For anyone who doesn't know, an XBM is an ACSII C file that contains and array of bytes and displays monochrome data. Below is my algorithm, so if anyone can point me in the right direction, I'd be really happy.
Sorry, It's a bit verbatim, but it's the whole decoder:
string input = File.ReadAllText(fname);
using (StreamReader r = new StreamReader(fname))
{
int i = input.IndexOf('{');
string bytes = input.Substring(i+1);
int j = bytes.IndexOf('}');
bytes = bytes.Remove(j-1);
string[] StringArray = bytes.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
byte[] pixels = new byte[StringArray.Length];
for (int k = 0; k < StringArray.Length; k++)
{
byte result;
StringArray[k] = StringArray[k].Replace("0x", "");
StringArray[k] = StringArray[k].Replace("\r", "");
StringArray[k] = StringArray[k].Replace("\n", "");
StringArray[k] = StringArray[k].Trim();
bool result1 = byte.TryParse(StringArray[k], NumberStyles.HexNumber, CultureInfo.CurrentCulture, out result);
if (result1)
pixels[k] = result;
else
throw new Exception();
}
xBits = System.Runtime.InteropServices.Marshal.AllocHGlobal(pixels.Length);
System.Runtime.InteropServices.Marshal.Copy(pixels, 0, xBits, pixels.Length);
}
return xBits;
I didn't try your code but here's a working sample that I kicked out. It doesn't parse a file but instead takes a byte array (from Wikipedia). It also creates a bitmap using normal GDI+ calls.
//Sample data from http://en.wikipedia.org/wiki/X_BitMap
int Width = 16;
int Height = 7;
byte[] test_bits = { 0x13, 0x0, 0x15, 0x0, 0x93, 0xcd, 0x55, 0xa5, 0x93, 0xc5, 0x0, 0x80, 0x0, 0x60 };
//Create our bitmap
using (Bitmap B = new Bitmap(Width, Height))
{
//Will hold our byte as a string of bits
string Bits = null;
//Current X,Y of the painting process
int X = 0;
int Y = 0;
//Loop through all of the bits
for (int i = 0; i < test_bits.Length; i++)
{
//Convert the current byte to a string of bits and pad with extra 0's if needed
Bits = Convert.ToString(test_bits[i], 2).PadLeft(8, '0');
//Bits are stored with the first pixel in the least signigicant bit so we need to work the string from right to left
for (int j = 7; j >=0; j--)
{
//Set the pixel's color based on whether the current bit is a 0 or 1
B.SetPixel(X, Y, Bits[j] == '0' ? Color.White : Color.Black);
//Incremement our X position
X += 1;
}
//If we're passed the right boundry, reset the X and move the Y to the next line
if (X >= Width)
{
X = 0;
Y += 1;
}
}
//Output the bitmap to the desktop
B.Save(System.IO.Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Desktop), "Output.bmp"), System.Drawing.Imaging.ImageFormat.Bmp);
}
精彩评论