Locked pointer when locking a rectangle in a C# Bitmap - c#

This may be a repeat of the following unanswered question:
Help with bitmap lock - Format8bppIndexed
I'm locking an image in the following manner:
// PixelFormat is 8BppIndexed in my case.
Bitmap bmp = new Bitmap("mySampleImage.tif");
// ClipRectangle will be a Rectangle such as {x=128, y=290, width=250, height=200},
// selected by the user by seeing the image on screen. Thus, it's a valid region
BitmapData data = bmp.LockBits(rect, ImageLockMode.ReadOnly, bmp.PixelFormat);
unsafe
{
byte* origin = (byte*)data.Scan0.ToPointer();
// Processing...
}
In the processing section, I step through the pixels in the ClipRectangle in the Y direction. However, a pixel that should be valid returns with a memory access error, saying I cannot dereference the pointer.
For example, in a 704x600 image using:
ClipRectangle = {x=128, y=290, width=250, height=200}
The pixel (128x321) should be valid. By manually typing in the math to get that pixel in the intermediate window, I get the following:
origin + (321 * stride) + 128
0x053a80c0
*(origin + (321 * stride) + 128): Cannot dereference 'origin + (321 * stride) + 128'. The pointer is not valid.
Stride is 704, the logic in my software comes up with the exact pointer location as the intermediate window, so everything seems right. The Y pixels from 290-320 can be dereferenced just fine. If I instead lock the entire Bitmap, all my logic proceeds fine, but I have doubts about whether I'm getting the right pixels, or how the locking rectangle is used in LockBits.
Why can I not access the expected locked pixels in the BitmapData when I lock only the region I need?

When you lock bits using a rectangle with an offset, BitmapData.Scan0 doesn't return the bitmap origin, but rather the specified rectangle origin.
So, if you used:
Rectangle rect = new Rectangle(128, 290, 250, 200);
BitmapData data = bmp.LockBits(rect, ImageLockMode.ReadOnly, bmp.PixelFormat);
then the maximum offset from Scan0 is (250 * Stride) + 200.
In other words, the pixel at (128x321) would be at (Scan0 + (321 - 290) * Stride).

Related

Scale x and y coordinates to Form/pictureBox location. C#

My Form2 is in layman terms an external 'mini-map' off the actual 'mini-map' in-game.
As you can see on my Form2, my drawn red dot does not have the same location for my player when compared to the 'mini-map' in-game which is the yellow dot.
In the DebugView, you can see my characters X and Y location (charX & charY).
The coordinates are passed as int x & int y in a function to my Form2 class file.
The image in my pictureBox1 (which is the image in the current example picture above) is pulled from my server (url= "http://randomspam.co/MAP/103000000.img/miniMap.canvas.png").
Here is the following code with comments to my progress as of now.
Please take note that the pictureBox1 location is set to 0,0.
The errors are as follows;
1) The red dot location on my external mini-map != the location of my character in the mini-map in-game.
2) The red dot consistently flickers (appears & disappears)
3) The tooltip when shown on the pictureBox is really lagging in revealing and dis-revealing itself.
If anyone knows how to help out my current situation (as I am lost), please, anything is appreciated.
Thanks.
Ok, lets split this in topics:
1) Red Dot Location:
Here you have to match red dot position to the new size, this was answered several times before, see this -> How can I transform XY coordinates and height/width on a scaled image to an original sized image?
2) Double Buffer to stop Flickering:
public void DrawWhatever(Graphics graphics, int cx, int cy)
{
Graphics g;
Bitmap buffer = null;
buffer = new Bitmap([image width], [image height], graphics);
g = Graphics.FromImage(buffer);
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
// Draw a circle.
Pen p = new Pen(Color.Red,1)
g.DrawEllipse(p,cx,cy,30,30); //example values
graphics.DrawImage(buffer, 0, 0);
g.Dispose();
}
3) Tooltip:
Check double buffer algorithm and let me know
Have a copy from the mini map:
Bitmap bmp = new Bitmap(pictureBox1.Width, pictureBox1.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
Bitmap bmpClone = new Bitmap(pictureBox1.Width, pictureBox1.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
Graphics objGraphics = Graphics.FromImage(bmpClone);
objGraphics.DrawImage(pictureBox1.Image, 0, 0);
objGraphics.Dispose();
bmp = (Bitmap)bmpClone.Clone();
pictureBox1.Image = bmp;
Now before any invalidation do:
Graphics objGraphics = Graphics.FromImage(bmp);
objGraphics.SmoothingMode = SmoothingMode.HighQuality;
objGraphics.DrawImage(bmpClone, 0, 0);
objGraphics.FillEllipse(Brushes.Red, cx, cy, 5, 5)
objGraphics.Dispose();
pictureBox1.Invalidate();
You dont need anything inside pictureBox1_Paint
valter

WPF Image Shows only 1/3 at the top

I'm trying to take a writeablebitmap that constantly updates and render it into an Image however only the top of the image displays and the middle and bottom 2/3's are black. I think it might have something to do with PixelFormat as the writeablebitmap is bgr24 and the image is rgb24. This is what I'm currently doing.
int bufferSize = videoRenderer.VideoWidth * videoRenderer.VideoHeight;
byte[] frameBuffer = new byte[bufferSize];
Marshal.Copy(videoRenderer.Bitmap.BackBuffer, frameBuffer, 0, bufferSize);
using (Bitmap frame = new Bitmap(videoRenderer.VideoWidth, videoRenderer.VideoHeight, System.Drawing.Imaging.PixelFormat.Format24bppRgb))
{
System.Drawing.Rectangle rect = new System.Drawing.Rectangle(0, 0, videoRenderer.VideoWidth, videoRenderer.VideoHeight);
BitmapData bmpData = frame.LockBits(rect, ImageLockMode.ReadWrite, frame.PixelFormat);
Marshal.Copy(frameBuffer, 0, bmpData.Scan0, bufferSize);
frame.UnlockBits(bmpData);
IntPtr hBitmap = frame.GetHbitmap();
source = Imaging.CreateBitmapSourceFromHBitmap(hBitmap, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
DeleteObject(hBitmap);
}
Does something look horribly wrong, or is it most likely the pixelformat. And if the pixelformat, how would one go through each pixel in c# to swap the blue's and red's?
It can't be just the pixel format in this case (it wouldn't cause 1/3 of the image to be rendered and the rest to be black). The difference between BGR24 and RGB24 is just a color swap.
In your case it's probably has to do with a difference in stride between the bitmap and the video source.
And as far as converting from BGR24 to RGB24 you could do it manually by locking the writable bitmap and looping over each pixel and swapping the components but that is not going to have good performance.
A much better approach would be to use the FormatConvertedBitmap class.

Converting 24bpp to 8bpp - How can I fix this method so it returns a Bitmap with positive stride

I'm looking for a fast way to convert a Bitmap from 24bpp to 8bpp.
I found a solution at this site Programmer » 1bpp in C#. It works, but the resulting Bitmap stride is negative!
How can I fix the stride of the image?
I've already tried this:
Bitmap.Clone: stride still negative
new Bitmap(b0): Creates a 32bpp image... ¬¬
EDIT:
Save to a file, read it back and make a deep copy (Marshal.Copy or memcopy) of pixel data to detach the Bitmap from the file works.. But is "kind of" ugly...
The code is below:
/// <summary>
/// Copy a bitmap into a 1bpp/8bpp bitmap of the same dimensions, fast
/// </summary>
/// <param name="source">original bitmap</param>
/// <param name="bpp">1 or 8, target bpp</param>
/// <returns>a 1bpp copy of the bitmap</returns>
/// <url>http://www.wischik.com/lu/programmer/1bpp.html</url>
private static Bitmap ConvertTo1or8bppNegativeStride(Bitmap source, int bpp = 8)
{
if (bpp != 1 && bpp != 8) throw new System.ArgumentException("1 or 8", "bpp");
// Plan: built into Windows GDI is the ability to convert
// bitmaps from one format to another. Most of the time, this
// job is actually done by the graphics hardware accelerator card
// and so is extremely fast. The rest of the time, the job is done by
// very fast native code.
// We will call into this GDI functionality from C#. Our plan:
// (1) Convert our Bitmap into a GDI hbitmap (ie. copy unmanaged->managed)
// (2) Create a GDI monochrome hbitmap
// (3) Use GDI "BitBlt" function to copy from hbitmap into monochrome (as above)
// (4) Convert the monochrone hbitmap into a Bitmap (ie. copy unmanaged->managed)
int w = source.Width, h = source.Height;
IntPtr hbm = source.GetHbitmap(); // this is step (1)
//
// Step (2): create the monochrome bitmap.
// "BITMAPINFO" is an interop-struct which we define below.
// In GDI terms, it's a BITMAPHEADERINFO followed by an array of two RGBQUADs
BITMAPINFO bmi = new BITMAPINFO();
bmi.biSize = 40; // the size of the BITMAPHEADERINFO struct
bmi.biWidth = w;
bmi.biHeight = h;
bmi.biPlanes = 1; // "planes" are confusing. We always use just 1. Read MSDN for more info.
bmi.biBitCount = (short)bpp; // ie. 1bpp or 8bpp
bmi.biCompression = BI_RGB; // ie. the pixels in our RGBQUAD table are stored as RGBs, not palette indexes
bmi.biSizeImage = (uint)(((w + 7) & 0xFFFFFFF8) * h / 8);
bmi.biXPelsPerMeter = 1000000; // not really important
bmi.biYPelsPerMeter = 1000000; // not really important
// Now for the colour table.
uint ncols = (uint)1 << bpp; // 2 colours for 1bpp; 256 colours for 8bpp
bmi.biClrUsed = ncols;
bmi.biClrImportant = ncols;
bmi.cols = new uint[256]; // The structure always has fixed size 256, even if we end up using fewer colours
if (bpp == 1)
{
bmi.cols[0] = MAKERGB(0, 0, 0);
bmi.cols[1] = MAKERGB(255, 255, 255);
}
else
{
for (int i = 0; i < ncols; i++)
bmi.cols[i] = MAKERGB(i, i, i);
}
// For 8bpp we've created an palette with just greyscale colours.
// You can set up any palette you want here. Here are some possibilities:
// greyscale: for (int i=0; i<256; i++) bmi.cols[i]=MAKERGB(i,i,i);
// rainbow: bmi.biClrUsed=216; bmi.biClrImportant=216; int[] colv=new int[6]{0,51,102,153,204,255};
// for (int i=0; i<216; i++) bmi.cols[i]=MAKERGB(colv[i/36],colv[(i/6)%6],colv[i%6]);
// optimal: a difficult topic: http://en.wikipedia.org/wiki/Color_quantization
//
// Now create the indexed bitmap "hbm0"
IntPtr bits0; // not used for our purposes. It returns a pointer to the raw bits that make up the bitmap.
IntPtr hbm0 = CreateDIBSection(IntPtr.Zero, ref bmi, DIB_RGB_COLORS, out bits0, IntPtr.Zero, 0);
//
// Step (3): use GDI's BitBlt function to copy from original hbitmap into monocrhome bitmap
// GDI programming is kind of confusing... nb. The GDI equivalent of "Graphics" is called a "DC".
IntPtr sdc = GetDC(IntPtr.Zero); // First we obtain the DC for the screen
// Next, create a DC for the original hbitmap
IntPtr hdc = CreateCompatibleDC(sdc); SelectObject(hdc, hbm);
// and create a DC for the monochrome hbitmap
IntPtr hdc0 = CreateCompatibleDC(sdc); SelectObject(hdc0, hbm0);
// Now we can do the BitBlt:
BitBlt(hdc0, 0, 0, w, h, hdc, 0, 0, SRCCOPY);
// Step (4): convert this monochrome hbitmap back into a Bitmap:
Bitmap b0 = Bitmap.FromHbitmap(hbm0);
//
// Finally some cleanup.
DeleteDC(hdc);
DeleteDC(hdc0);
ReleaseDC(IntPtr.Zero, sdc);
DeleteObject(hbm);
DeleteObject(hbm0);
//It have negative stride...
return b0;
}
According to documentation for the BITMAPINFOHEADER structure:
biHeight
Specifies the height of the bitmap, in pixels.
If biHeight is positive, the bitmap is a bottom-up DIB and its origin
is the lower left corner.
If biHeight is negative, the bitmap is a top-down DIB and its origin
is the upper left corner.
If biHeight is negative, indicating a top-down DIB, biCompression must
be either BI_RGB or BI_BITFIELDS. Top-down DIBs cannot be compressed.
So if you change the line in the code you posted to:
bmi.biHeight = -h;
Then it'll create a top-down bitmap with a positive stride.
--
There are other possibilities.
var newBmp = srcBmp.Clone(new Rectangle(0, 0, srcBmp.Width, srcBmp.Height), PixelFormat.Format8bppIndexed);
For me, that creates a bitmap that has a positive stride. But then, the original bitmap has positive stride. I don't know what it'll do if I call it on a bitmap with negative stride.
All that said, I'm wondering what problem you're really trying to solve. Why does it matter if the bitmap is bottom up or top down?

Create Bitmap from a byte array of pixel data

This question is about how to read/write, allocate and manage the pixel data of a Bitmap.
Here is an example of how to allocate a byte array (managed memory) for pixel data and creating a Bitmap using it:
Size size = new Size(800, 600);
PixelFormat pxFormat = PixelFormat.Format8bppIndexed;
//Get the stride, in this case it will have the same length of the width.
//Because the image Pixel format is 1 Byte/pixel.
//Usually stride = "ByterPerPixel"*Width
//But it is not always true. More info at bobpowell.
int stride = GetStride(size.Width, pxFormat);
byte[] data = new byte[stride * size.Height];
GCHandle handle = GCHandle.Alloc(data, GCHandleType.Pinned);
Bitmap bmp = new Bitmap(size.Width, size.Height, stride,
pxFormat, handle.AddrOfPinnedObject());
//After doing your stuff, free the Bitmap and unpin the array.
bmp.Dispose();
handle.Free();
public static int GetStride(int width, PixelFormat pxFormat)
{
//float bitsPerPixel = System.Drawing.Image.GetPixelFormatSize(format);
int bitsPerPixel = ((int)pxFormat >> 8) & 0xFF;
//Number of bits used to store the image data per line (only the valid data)
int validBitsPerLine = width * bitsPerPixel;
//4 bytes for every int32 (32 bits)
int stride = ((validBitsPerLine + 31) / 32) * 4;
return stride;
}
I thought that the Bitmap would make a copy of the array data, but it actually points to the same data. Was you can see:
Color c;
c = bmp.GetPixel(0, 0);
Console.WriteLine("Color before: " + c.ToString());
//Prints: Color before: Color [A=255, R=0, G=0, B=0]
data[0] = 255;
c = bmp.GetPixel(0, 0);
Console.WriteLine("Color after: " + c.ToString());
//Prints: Color after: Color [A=255, R=255, G=255, B=255]
Questions:
Is it safe to do create a bitmap from a byte[] array (managed memory) and free() the GCHandle? If it is not safe, Ill need to keep a pinned array, how bad is that to GC/Performance?
Is it safe to change the data (ex: data[0] = 255;)?
The address of a Scan0 can be changed by the GC? I mean, I get the Scan0 from a locked bitmap, then unlock it and after some time lock it again, the Scan0 can be different?
What is the purpose of ImageLockMode.UserInputBuffer in the LockBits method? It is very hard to find info about that! MSDN do not explain it clearly!
EDIT 1: Some followup
You need to keep it pinned. Will it slow down the GC? I've asked it here. It depends on the number of images and its sizes. Nobody have gave me a quantitative answer. It seams that it is hard to determine.
You can also alloc the memory using Marshal or use the unmanaged memory allocated by the Bitmap.
I've done a lot of test using two threads. As long as the Bitmap is locked it is ok. If the Bitmap is unlock, than it is not safe! My related post about read/write directly to Scan0. Boing's answer "I already explained above why you are lucky to be able to use scan0 outside the lock. Because you use the original bmp PixelFormat and that GDI is optimized in that case to give you the pointer and not a copy. This pointer is valid until the OS will decide to free it. The only time there is a guarantee is between LockBits and UnLockBits. Period."
Yeah, it can happen, but large memory regions are treated different by the GC, it moves/frees this large object less frequently. So it can take a while to GC move this array. From MSDN: "Any allocation greater than or equal to 85,000 bytes goes on the large object heap (LOH)" ... "LOH is only collected during a generation 2 collection". .NET 4.5 have Improvements in LOH.
This question have been answered by #Boing. But I'm going to admit. I did not fully understand it. So if Boing or someone else could please clarify it, I would be glad. By the way, Why I can't just directly read/write to Sca0 without locking? => You should not write directly to Scan0 because Scan0 points to a copy of the Bitmap data made by the unmanaged memory (inside GDI). After unlock, this memory can be reallocate to other stuff, its not certain anymore that Scan0 will point to the actual Bitmap data. This can be reproduced getting the Scan0 in a lock, unlock, and do some rotate-flit in the unlocked bitmap. After some time, Scan0 will point to an invalid region and you will get an exception when trying to read/write to its memory location.
Its safe if you marshal.copy data rather than setting scan0 (directly or via that overload of BitMap()). You don't want to keep managed objects pinned, this will constrain the garbage collector.
If you copy, perfectly safe.
The input array is managed and can be moved by the GC, scan0 is an unmanaged pointer that would get out of date if the array moved. The Bitmap object itself is managed but sets the scan0 pointer in Windows via a handle.
ImageLockMode.UserInputBuffer is? Apparently it can be passed to LockBits, maybe it tells Bitmap() to copy the input array data.
Example code to create a greyscale bitmap from array:
var b = new Bitmap(Width, Height, PixelFormat.Format8bppIndexed);
ColorPalette ncp = b.Palette;
for (int i = 0; i < 256; i++)
ncp.Entries[i] = Color.FromArgb(255, i, i, i);
b.Palette = ncp;
var BoundsRect = new Rectangle(0, 0, Width, Height);
BitmapData bmpData = b.LockBits(BoundsRect,
ImageLockMode.WriteOnly,
b.PixelFormat);
IntPtr ptr = bmpData.Scan0;
int bytes = bmpData.Stride*b.Height;
var rgbValues = new byte[bytes];
// fill in rgbValues, e.g. with a for loop over an input array
Marshal.Copy(rgbValues, 0, ptr, bytes);
b.UnlockBits(bmpData);
return b;
Concerning your question 4: The ImageLockMode.UserInputBuffer can give you the control of the allocating process of those huge amount of memory that could be referenced into a BitmapData object.
If you choose to create yourself the BitmapData object you can avoid a Marshall.Copy. You will then have to use this flag in combinaison with another ImageLockMode.
Beware that it is a complicated business, specially concerning Stride
and PixelFormat.
Here is an example that would get in one shot the content of 24bbp buffer onto a BitMap and then in one another shot read it back into another buffer into 48bbp.
Size size = Image.Size;
Bitmap bitmap = Image;
// myPrewrittenBuff is allocated just like myReadingBuffer below (skipped for space sake)
// But with two differences: the buff would be byte [] (not ushort[]) and the Stride == 3 * size.Width (not 6 * ...) because we build a 24bpp not 48bpp
BitmapData writerBuff= bm.LockBits(new Rectangle(0, 0, size.Width, size.Height), ImageLockMode.UserInputBuffer | ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb, myPrewrittenBuff);
// note here writerBuff and myPrewrittenBuff are the same reference
bitmap.UnlockBits(writerBuff);
// done. bitmap updated , no marshal needed to copy myPrewrittenBuff
// Now lets read back the bitmap into another format...
BitmapData myReadingBuffer = new BitmapData();
ushort[] buff = new ushort[(3 * size.Width) * size.Height]; // ;Marshal.AllocHGlobal() if you want
GCHandle handle= GCHandle.Alloc(buff, GCHandleType.Pinned);
myReadingBuffer.Scan0 = Marshal.UnsafeAddrOfPinnedArrayElement(buff, 0);
myReadingBuffer.Height = size.Height;
myReadingBuffer.Width = size.Width;
myReadingBuffer.PixelFormat = PixelFormat.Format48bppRgb;
myReadingBuffer.Stride = 6 * size.Width;
// now read into that buff
BitmapData result = bitmap.LockBits(new Rectangle(0, 0, size.Width, size.Height), ImageLockMode.UserInputBuffer | ImageLockMode.ReadOnly, PixelFormat.Format48bppRgb, myReadingBuffer);
if (object.ReferenceEquals(result, myReadingBuffer)) {
// Note: we pass here
// and buff is filled
}
bitmap.UnlockBits(result);
handle.Free();
// use buff at will...
If you use ILSpy you'll see that this method link to GDI+ and those methods helps are more complete.
You may increase performance by using your own memory scheme, but
beware that Stride may need to have some alignment to get the best
performance.
You then will be able to go wild for example allocating huge virtual memory mapped scan0 and blit them quite efficiently.
Note that pinning huge array (and especially a few) won't be a burden to the GC and will allow you to manipulate the byte/short in a totally safe way (or unsafe if you seek speed)
I'm not sure if there is a reason you're doing it the way you are. Maybe there is. It seems like you're off the beaten path enough so that you might be trying to do something more advanced than what the title of your question implies...
However, the traditional way of creating a Bitmap from a Byte array is:
using (MemoryStream stream = new MemoryStream(byteArray))
{
Bitmap bmp = new Bitmap(stream);
// use bmp here....
}
Here is a sample code i wrote to convert byte array of pixels to an 8 bits grey scale image(bmp)
this method accepts the pixel array, image width, and height as arguments
//
public Bitmap Convert2Bitmap(byte[] DATA, int width, int height)
{
Bitmap Bm = new Bitmap(width,height,PixelFormat.Format24bppRgb);
var b = new Bitmap(width, height, PixelFormat.Format8bppIndexed);
ColorPalette ncp = b.Palette;
for (int i = 0; i < 256; i++)
ncp.Entries[i] = Color.FromArgb(255, i, i, i);
b.Palette = ncp;
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
int Value = DATA[x + (y * width)];
Color C = ncp.Entries[Value];
Bm.SetPixel(x,y,C);
}
}
return Bm;
}

Copying from BitmapSource to WritableBitmap

I am trying to copy a part of a BitmapSource to a WritableBitmap.
This is my code so far:
var bmp = image.Source as BitmapSource;
var row = new WriteableBitmap(bmp.PixelWidth, bottom - top, bmp.DpiX, bmp.DpiY, bmp.Format, bmp.Palette);
row.Lock();
bmp.CopyPixels(new Int32Rect(top, 0, bmp.PixelWidth, bottom - top), row.BackBuffer, row.PixelHeight * row.BackBufferStride, row.BackBufferStride);
row.AddDirtyRect(new Int32Rect(0, 0, row.PixelWidth, row.PixelHeight));
row.Unlock();
I get "ArgumentException: Value does not fall within the expected range." in the line of CopyPixels.
I tried swapping row.PixelHeight * row.BackBufferStride with row.PixelHeight * row.PixelWidth, but then I get an error saying the value is too low.
I couldn't find a single code example using this overload of CopyPixels, so I'm asking for help.
Thanks!
What part of the image are trying to copy? change the width and height in the target ctor, and the width and height in Int32Rect as well as the first two params (0,0) which are x & y offsets into the image. Or just leave if you want to copy the whole thing.
BitmapSource source = sourceImage.Source as BitmapSource;
// Calculate stride of source
int stride = source.PixelWidth * (source.Format.BitsPerPixel + 7) / 8;
// Create data array to hold source pixel data
byte[] data = new byte[stride * source.PixelHeight];
// Copy source image pixels to the data array
source.CopyPixels(data, stride, 0);
// Create WriteableBitmap to copy the pixel data to.
WriteableBitmap target = new WriteableBitmap(
source.PixelWidth,
source.PixelHeight,
source.DpiX, source.DpiY,
source.Format, null);
// Write the pixel data to the WriteableBitmap.
target.WritePixels(
new Int32Rect(0, 0, source.PixelWidth, source.PixelHeight),
data, stride, 0);
// Set the WriteableBitmap as the source for the <Image> element
// in XAML so you can see the result of the copy
targetImage.Source = target;

Categories

Resources