I'm trying to use a bitmap in an unsafe context, and am seeing instability in that, e.g., the program runs the first time round but fails the second. Here is the code:
private static void RenderBitmap(Graphics g)
{
const int width = 150, height = 150;
using (Bitmap bmp = new Bitmap(width, height,
System.Drawing.Imaging.PixelFormat.Format24bppRgb))
{
Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
System.Drawing.Imaging.BitmapData bmpData =
bmp.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite,
bmp.PixelFormat);
NativeMethods.RenderText(Graphics.FromImage(bmp).GetHdc(), bmpData.Scan0,
"This works only first time round", "Segoe", 10,
new RGBA(255, 0, 0, 255), width, height);
bmp.UnlockBits(bmpData);
g.DrawImage(bmp, new Rectangle(width, height, width, -height));
}
}
Seeing how this isn't working, I have a few questions. Is what I'm doing safe and correct, provided the native RenderText method manipulates the bitmap memory directly? Is my way of getting HDC from the bitmap correct, or should I use the parameter g that was passed from a drawing method?
The error I'm getting is this:
System.AccessViolationException was
unhandled Message="Attempted to read
or write protected memory. This is
often an indication that other memory
is corrupt."
The NativeMethods.RenderRext method can't safely work with the bitmap data, as it doesn't know how wide the scan lines of the bitmap is, and if it is stored upside down in memory or not. The symptoms suggests that the method is writing to memory outside the bitmap, overwriting something else that you need in your application.
The BitmapData.Stride property has the information that the method needs to work with the data. It contains the scan line width in bytes, and if it's negative it means that the bitmap is stored upside down in memory. Simply Scan0 is the address of the first scan line, and Scan0 + Stride is the address of the second scan line.
Maybe this is a silly question, but why don't you use the TextRenderer class that comes with .NET instead of using p/invoke?
TextRenderer::DrawText Method (IDeviceContext, String, Font, Point, Color)
http://msdn.microsoft.com/en-us/library/4ftkekek.aspx
-Oisin
Well, after much pain and suffering, I found a solution: instead of passing in a memory buffer to be filled in, I passed a device context (HDC) to be rendered into. Seems to be working so far!
Thanks to all who answered.
Related
I'm coding in C#, and loading images this way :
// loading image
string imageFileName = "myImage.jpg";
Bitmap bmp = new Bitmap(imageFileName, false);
// trying to display color so that I know how many channels I have
// except it always displays 4 values, whether I have 1, 3 or 4 channels
Color color = bmp.GetPixel(0, 0);
Console.WriteLine(color.ToString());
// locking the bitmap's bits
System.Drawing.Imaging.BitmapData bmpData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, bmp.PixelFormat);
// doing stuff that requires me to know the number of channels of the image, amongst other things
// unlocking the bitmap's bits
bmp.UnlockBits(bmpData);
I need to know the number of channels in my image (usually they are grayscale (1), RGB (3) or RGBA (4)), and I don't know how is that information storred.
EDIT :
I'm not looking to force a pixel format. I'm trying to load an image, and figure out procedurally what is the number of channel in the image I loaded.
There is a PixelFormat property, you can read about in on MSDN.
You can combine with: GetPixelFormatSize it to get the bytes per pixel if you want.
Creation:
You need to use an overload of the Bitmap contructor that takes a PixelFormat parameter.
Usage:
The the bitmap.PixelFormat property will tell you what you have.
Here is more info about the PixelFormats
I'm working in C# and I've got a question about the Bitmap.LockBits method.
Let's say that I have a Bitmap called myBitmap and use LockBits on this bitmap:
BitmapData bmpData = myBitmap.LockBits(new Rectangle(0, 0, myBitmap.Width, myBitmap.Height), ImageLockMode.ReadOnly, PixelFormat.Format8bppIndexed);
In my limited understanding bmpData.Scan0 is a pointer to the image data, but is this the "actual image data" or some sort of copy (using just the data in the specified rectangle)? The reason I'm asking is that I can't figure out the purpose of the ImageLockMode enumeration. It seems to me that if I have the Scan0 pointer I can fiddle around and do all sorts of reads/writes to the image data (using for example Marshal.Copy) regardless of the choosen ImageLockMode.
Thank you for your time!
Kind regards / Henrik
I'm trying to convert a Drawing.Bitmap to an Imaging.Metafile for the purposes of inserting the metafile into a Forms.RichTextBox. (For reference, embedding a bitmap in a metafile is the recommended practice for putting a bitmap into richtext (see Rich Text Format (RTF) Specification Version 1.9.1, p. 149.) Unfortunately it also appears to be the only way to embed an image into a Forms.RichTextBox, as I can't get any device-dependent or device-independent methods of inserting an bitmap into a RichTextBox to work.)
Later, I must retrieve the pixel-data from the metafile. I require that the pixels of the metafile exactly match those of the bitmap. When I perform the conversion, however, the pixels are slightly altered. (Perhaps due to GDI Image Color Management (ICM)?)
Here is my technique:
public static Imaging.Metafile BitmapToMetafileViaGraphicsDrawImage(Forms.RichTextBox rtfBox, Drawing.Bitmap bitmap)
{
Imaging.Metafile metafile;
using (IO.MemoryStream stream = new IO.MemoryStream())
using (Drawing.Graphics rtfBoxGraphics = rtfBox.CreateGraphics())
{
IntPtr pDeviceContext = rtfBoxGraphics.GetHdc();
metafile = new Imaging.Metafile(stream, pDeviceContext);
using (Drawing.Graphics imageGraphics = Drawing.Graphics.FromImage(metafile))
{
//imageGraphics.DrawImage(bitmap, new Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height));
imageGraphics.DrawImageUnscaled(bitmap, new Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height));
}
rtfBoxGraphics.ReleaseHdc(pDeviceContext);
}
return metafile;
}
In this case I access the pixels of the metafile in this way:
metafile.Save(stream, Imaging.ImageFormat.Png);
Bitmap bitmap = new Bitmap(stream, false);
bitmap.GetPixel(x, y);
I have also tried to use a BitBlt technique with no success.
BitBlt technique:
[System.Runtime.InteropServices.DllImportAttribute("gdi32.dll")]
static extern int BitBlt(
IntPtr hdcDest, // handle to destination DC (device context)
int nXDest, // x-coord of destination upper-left corner
int nYDest, // y-coord of destination upper-left corner
int nWidth, // width of destination rectangle
int nHeight, // height of destination rectangle
IntPtr hdcSrc, // handle to source DC
int nXSrc, // x-coordinate of source upper-left corner
int nYSrc, // y-coordinate of source upper-left corner
System.Int32 dwRop // raster operation code
);
public static Imaging.Metafile BitmapToMetafileViaBitBlt(Forms.RichTextBox rtfBox, Drawing.Bitmap bitmap)
{
const int SrcCopy = 0xcc0020;
Graphics bitmapGraphics = Graphics.FromImage(bitmap);
IntPtr pBitmapDeviceContext = bitmapGraphics.GetHdc();
RectangleF rect = new RectangleF(new PointF(0, 0), new SizeF(bitmap.Width, bitmap.Height));
Imaging.Metafile metafile = new Imaging.Metafile(pBitmapDeviceContext, rect);
Graphics metafileGraphics = Graphics.FromImage(metafile);
IntPtr metafileDeviceContext = metafileGraphics.GetHdc();
BitBlt(pBitmapDeviceContext, 0, 0, bitmap.Width, bitmap.Height,
metafileDeviceContext, 0, 0, SrcCopy);
return metafile;
}
I'm not even sure this technique is correctly copying the pixel-data. This technique fails when I try to access the data in the metafile later:
IntPtr h = metafile.GetHenhmetafile(); // ArgumentException "Parameter is not valid."
byte[] data;
uint size = GetEnhMetaFileBits(h, 0, out data);
data = new byte[size];
GetEnhMetaFileBits(h, size, out data);
stream = new IO.MemoryStream(data);
How do I convert a bitmap into a metafile without altering the pixels, and then retrieve the pixel-data again later? Thank you!
Setting Bitmap Resolution
This is how I try to set the bitmap resolution so that the metafile's resolution matches:
Drawing.Bitmap bitmap = new Drawing.Bitmap(width, height,
Imaging.PixelFormat.Format32bppArgb); // Use 32-bit pixels so that each component (ARGB) matches up with a byte
// Try setting the resolution to see if that helps with conversion to/from metafiles
Drawing.Graphics rtfGraphics = rtfBox.CreateGraphics();
bitmap.SetResolution(rtfGraphics.DpiX, rtfGraphics.DpiY);
// Set the pixel data
...
// Return the bitmap
return bitmap;
The rtfBox is the same one sent to BitmapToMetafileViaGraphicsDrawImage.
You can create and process the metafile manually (e.g. enumerate its records), in which case you can actually insert a bitmap with its exact data into the metafile stream. However, this is not as simple as it may sound.
When playing a GDI metafile, all operations are internally converted into GDI+, which is actually a completely different API and which handles a lot of things differently. Unfortunately, the built-in way to do it as soon as the metafile has some complexity or the output needs to be transformed is to let GDI render the metafile on a low-res bitmap and then draw this, which never gives you the results you're looking for.
For a project (closed-source - so don't bother asking for the source ;) ) I had to implement a complete GDI-to-GDI+ playback engine similar to the functionality of EMFExplorer, but using managed code only and with single character re-aligning for exact textual output. That is only to say that it can be done, if you're willing to invest some time dealing with all the metafile records you need youself (which should be a small subset only, but still).
Edit to address the questions asked in the comments:
The metafile is nothing but a series of drawing instructions, basically a recording of GDI(+) operations performed. So you should be able to construct a metafile as binary data consisting basically only of the header and the bitmap, and in that case (since you don't pass through drwing operations but always handle the bitmap at a binary level) you will be able to retrieve the exact same data from the metafile you wrote into it.
Fortunately, since a few years Microsoft has been documenting and making their file formats and protocols available to the public, so that a precise documentation of the WMF/EMF file format is available. The metafile format is explained by MS here:
http://msdn.microsoft.com/en-us/library/cc230514(PROT.10).aspx
It structure is outlined here:
http://msdn.microsoft.com/en-us/library/cc230516(v=PROT.10).aspx
The bitmap records are described here:
http://msdn.microsoft.com/en-us/library/cc231160(v=PROT.10).aspx
Using this information, you should be able to put together binary data (maybe using a BinaryWriter) and then also load/enumerate the file to get the data back (e.g. finding the bitmap again in the metafile and extract the required data from it).
There are a number of possible answers here, the two most likely culprits being aliasing and resolution. My guess is resolution because when you save a Bitmap without specifying a resolution, I believe it is set to 120 DPI automatically, which could affect aliasing.
Before someone remarks that resolution doesn't matter and that DPI is only used for printing and blah blah, please resist the urge to make that comment. I'm happy to have that debate with you on your own question.
Set the resolution of the bitmap you're converting back to with your metafile's resolution.
This is just a shot in the dark, but have a look at some of the ImageFlags flag values and see if they can be incorporated into the generation or rendering of the metafile.
it's a funny way to solve it, but if all you need is to put it inside RichTextBox - you can use the Clipboard:
private void button1_Click(object sender, EventArgs e)
{
System.Drawing.Bitmap bmp = new Bitmap("g.bmp");
Clipboard.SetData(DataFormats.Bitmap, bmp);
richTextBox1.Paste();
}
but I'm not sure about the opposite way (reading the bitmap from RTF text)
If I have a .Net Bitmap, I can create from it a GDI bitmap by calling the Bitmap's GetHbitmap() method.
Bitmap bmp = new Bitmap(100, 100);
IntPtr gdiBmp = bmp.GetHbitmap();
This works fine, but every time you call GetHbitmap, Windows has to allocate the new memory that the returned IntPtr references.
What I'd like to do - if possible - is write a function (I know PInvoke will be necessary here) that also generates a GDI bitmap copy of a Bitmap, but that overwrites an existing chunk of memory already referenced by an IntPtr returned from GetHbitmap instead of allocating new memory. So it would look something like this (if it were an extension method of Bitmap):
// desired method signature:
void OverwriteHbitmap(IntPtr gdi)
{
}
// ex:
Bitmap bmp1 = new Bitmap(100, 100);
IntPtr gdi1 = bmp1.GetHbitmap();
Bitmap bmp2 = new Bitmap(100, 100);
bmp2.OverwriteHbitmap(gdi1); // gdi1 is still pointing to the same block
// of memory, which now contains the pixel data from bmp2
How can I do this? I assume I'll need to know the structure of a GDI bitmap, and probably I can use LockBits and BitmapData for this, but I'm not sure exactly how.
Clues for the bounty hunters:
Bitmap has a method LockBits which locks the bitmap in memory and returns a BitmapData object. The BitmapData object has a Scan0 property which is an IntPtr pointing to the start of the locked bitmap's pixel data (i.e it doesn't point to the bitmap's header a.k.a. the start of the bitmap itself).
I'm pretty sure the solution looks something like this:
Bitmap bmp1 = new Bitmap(100, 100);
IntPtr gdi1 = bmp1.GetHbitmap(); // now we have a pointer to a
// 100x100 GDI bitmap
Bitmap bmp2 = new Bitmap(100, 100);
BitmapData data = bmp2.LockBits();
IntPtr gdi1Data = gdi1 + 68; // magic number = whatever the size
// of a GDI bitmap header is
CopyMemory(data.Scan0, gdi1Data, 40000);
The solution does not have to be generic - it only needs to work for bitmaps with pixel format Format32bppArgb (the default GDI+ format).
I think you answered your own question: use LockBits.
See
How to: Use LockBits
and
Bob Powell - Locking Bits.
I used this method to rapidly draw fractals in a .NET (1.1!) program that I was writing for fun. Of all the methods that I experimented with, this was by far the fastest.
Create a Graphics from the IntPtr with Graphics.FromHdc and use Graphics.DrawImage to paste the Bitmap into it.
You should not assume that a HANDLE or HBITMAP is a pointer to anything. It can be implemented as an index into a handle table, key of a hash table, etc.
However, if you call the GDI GetObject function, the resultant BITMAP structure contains a pointer to the real bits.
Not sure if it would be as fast (I think in the case of the same pixel format for source and destination it will), but SetDIBits should do exactly what you want (replace the data in an existing HBITMAP).
I am messing around with Conway's Game of Life - http://en.wikipedia.org/wiki/Conway's_Game_of_Life
I started out coding algorithmns for winforms and now want to port my work onto windows mobile 6.1 (compact framework). I came across an article by Jon Skeet where he compared several different algorithmns for calculating next generations in the game. He used an array of bytes to store a cells state (alive or dead) and then he would copy this array to an 8bpp bitmap. For each new generation, he works out the state of each byte, then copies the array to a bitmap, then draws that bitmap to a picturebox.
void CreateInitialImage()
{
bitmap = new Bitmap(Width, Height, PixelFormat.Format8bppIndexed);
ColorPalette palette = bitmap.Palette;
palette.Entries[0] = Color.Black;
palette.Entries[1] = Color.White;
bitmap.Palette = palette;
}
public Image Render()
{
Rectangle rect = new Rectangle(0, 0, Width, Height);
BitmapData bmpData = bitmap.LockBits(rect, ImageLockMode.ReadWrite, bitmap.PixelFormat);
Marshal.Copy(Data, 0, bmpData.Scan0, Data.Length);
bitmap.UnlockBits(bmpData);
return bitmap;
}
His code above is beautifully simple and very fast to render. Jon is using Windows Forms but now I want to port my own version of this onto Windows Mobile 6.1 (Compact Framework) but . . . .there is no way to format a bitmap to 8bpp in the cf.
Can anyone suggest a way of rendering an array of bytes to a drawable image in the CF. This array is created in code on the fly (it is NOT loaded from an image file on disk). I basically need to store an array of cells represented by bytes, they are either alive or dead and I then need to draw that array as an image. The game is particularly slow on the CF so I need to implement clever optimised algoritmns but also need to render as fast as possible and the above solution would be pretty dam perfect if only it was available on the compact framework.
Many thanks for any help
Any suggestions?
You could have a look at GDI+ for CF. It's basically a wrapper for most of the GDI implemented in WinCE. Here's a link to the source code and a writeup: http://community.opennetcf.com/articles/cf/archive/2007/10/31/using-gdi-on-windows-mobile.aspx
I think ImagingFactoryClass.CreateBitmapFromBuffer() looks like a good place to start.
Ok, how about this:
use the Bitmap.Save() method to save to a MemoryStream instead of a file;
when you save to the MemoryStream, you get to name the ImageFormat as "GIF" (this is equivalent to 8bpp in .Net, according to this: http://support.microsoft.com/kb/318343)
use MemoryStream.Write() to change whatever data you want in the image, or copy the data using MemoryStream.ToArray() if that jives better.
After you change the MemoryStream, you'll probably have to copy it back into the Bitmap, or make a new Bitmap. If you do make a new Bitmap, be sure to Dispose() the old one, to avoid memory leaks.
Hi Rocjoe and thanks again for the help, I have tried the following
Image bmp = new Bitmap(10, 10);
byte[] array = ImageToByteArray(bmp);
public byte[] ImageToByteArray(Image img)
{
MemoryStream ms = new MemoryStream();
img.Save(ms, System.Drawing.Imaging.ImageFormat.Gif );
return ms.ToArray();
}
The array coming back has over 870 bytes in it, It seems to hold all sorts of header info, padding and what have you. so again it does not work...