Purpose of ImageLockMode in Bitmap.LockBits - c#

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

Related

Number of channels in System.Drawing.Bitmap C#

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

Load a bitmap from file in RGB format (without alpha)

i simply want to load a .BMP file and get the Bitmap object in 24bit RGB format (or 32bit in RGB format).
All methods I tried return a Bitmap/Image object with PixelFormat = Format32bppArgb. Even if of course BMPs don't have alpha.
new Bitmap(System.Drawing.Image.FromFile(fileName, true));
new Bitmap(fileName);
I currently solve the problem by copying the first object to another in memory bitmap at 24bit RBG.
Is there a single method to do it?
Thanks
As far as I can tell it is not possible to specify the PixelFormat for loading bitmaps using the classes in System.Drawing. To convert the bitmap check this question: Converting Bitmap PixelFormats in C#
This is currently the top answer there:
Bitmap orig = new Bitmap(#"c:\temp\24bpp.bmp");
Bitmap clone = new Bitmap(orig.Width, orig.Height, System.Drawing.Imaging.PixelFormat.Format32bppPArgb);
using (Graphics gr = Graphics.FromImage(clone)) {
gr.DrawImage(orig, new Rectangle(0, 0, clone.Width, clone.Height));
}
// Dispose orig as necessary..
One option would be to put that in a function which takes a filename and PixelFormat. That hides the ugly code, which has its ups and downs since it also hides the fact it is probably not that efficient.
According to the linked SO question using the Clone method not always works.
You can clone it to a RGB format one:
var bitmapInRgbFormat = loadedBitmap.Clone(new Rectangle(0, 0, loadedBitmap.Width, loadedBitmap.Height), PixelFormat.Format32bppRgb)
Exactly what do you mean by copying the first object to another?
To achieve what you want to do, meaning loading an image and converting it to 24 bit, just get the graphics context of a second bitmap that matches the size and that is RGB, and paint the original bitmap onto this one.

How can I overwrite a System.Drawing.Bitmap onto an existing GDI bitmap?

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).

8bpp Bitmap format on the Compact Framework

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...

Bitmap editing in unsafe context - how to avoid instability?

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.

Categories