Overlay two or more Bitmaps to show in Picturebox (C#) - c#

In my C# program I have a Picturebox in which i want to show a stream of video (consecutive frames). I receive raw data, that I then transform into Bitmap or Image. I can show one image at a time without a problem (to reproduce the video stream).
Now my issue is that I want to merge 2 or more bitmaps (like layers) with the same size and alpha values (ARGB) and show it on the picturebox.
I have read lots of websites and posts here on SO, but many use the Graphics class, and I just can't draw it on my application (very likely because i'm new to C#! and already have my program setup, so I didn't want to change the structure).
What i need (to know):
How to overlay two or more Bitmaps with alpha values;
NO pixel manipulation please, can't afford that cost in performance.
Thank you so much in advance!
NOTE: I think this question shouldn't be marked (or closed) as duplicate, because everything i found in SO is done either with pixel manipulation or through the Graphics class. (but I might be wrong!)
EDIT: Possible workaround (NOT the solution to the question)
In
A PictureBox Problem, the 4th answer (from user comecme) tells me to have 2 picturebox, one on top of the other. The only (extra) thing I had to do to make it work with this approach was:
private void Form1_Load(object sender, EventArgs e)
{
pictureBox2.Parent = pictureBox1;
}
Where pictureBox2 will be the one on top.
I won't consider this an answer to this problem, because I consider it a workaround (specially because having more than 10 pictureboxes doesn't seem ideal! lol). That's why I will leave this question opened waiting for a real answer to my question.
EDIT: Resolved! check my answer.

Here is the real answer to my problem.
1) Use a List<Bitmap> to store all the images you want to blend;
2) Create a new Bitmap to hold the final image;
3) Draw each image on top of the final image's graphics using the using statement.
The code:
List<Bitmap> images = new List<Bitmap>();
Bitmap finalImage = new Bitmap(640, 480);
...
//For each layer, I transform the data into a Bitmap (doesn't matter what kind of
//data, in this question) and add it to the images list
for (int i = 0; i < nLayers; ++i)
{
Bitmap bitmap = new Bitmap(layerBitmapData[i]));
images.Add(bitmap);
}
using (Graphics g = Graphics.FromImage(finalImage))
{
//set background color
g.Clear(Color.Black);
//go through each image and draw it on the final image (Notice the offset; since I want to overlay the images i won't have any offset between the images in the finalImage)
int offset = 0;
foreach (Bitmap image in images)
{
g.DrawImage(image, new Rectangle(offset, 0, image.Width, image.Height));
}
}
//Draw the final image in the pictureBox
this.layersBox.Image = finalImage;
//In my case I clear the List because i run this in a cycle and the number of layers is not fixed
images.Clear();
Credits go to Brandon Cannaday in this tech.pro webpage.

Related

Webcam image differ from printed image

I am busy with a C# winform software. I use webcam to take a picture which display in a pictureBox.
When I capture the image with the webcam, it captures a zoomed image, and when printing, it is a stretched image. I have tried a variety of SizeMode settings.All give the same result
Because I am not sure where the fault is, I will include as much detail as possible:
Using
using AForge.Video;
using AForge.Video.DirectShow;
Selecting Camera:
webcam = new FilterInfoCollection(FilterCategory.VideoInputDevice);
foreach (FilterInfo VideoCaptureDevice in webcam)
{
cmbVideoList.Items.Add(VideoCaptureDevice.Name);
}
Using camera (btn click):
cam = new VideoCaptureDevice(webcam[cmbVideoList.SelectedIndex].MonikerString);
cam.NewFrame += new NewFrameEventHandler(cam_NewFrame);
cam.Start();
if (cam.IsRunning)
{
btnStart.Hide();
}
btnStop.Show();
}
void cam_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
Bitmap bit = (Bitmap)eventArgs.Frame.Clone();
pboxPhoto.Image = bit;
}
PictureBox size:
Width: 226
Height: 328
Printing code:
PictureBox pict = (PictureBox)pboxPhoto;
pict.SizeMode = PictureBoxSizeMode.Zoom;
e.Graphics.DrawImage(pict.Image, 20, 416, 305, 328);
Here is a sample of the image on software:
enter image description here
Sample of printed image.
enter image description here
The simplest way is to tell the PictureBox to draw itself to a Bitmap.
This can be done with all Controls and the result will include not just the Image and maybe BackgroundImage but also anything drawn in the Paint event as well as any nested Controls.
Here is a simple example:
Size sz = pictureBox1.ClientSize;
using (Bitmap bmp = new Bitmap(sz.Width, sz.Height))
{
pictureBox1.DrawToBitmap(bmp, pictureBox1.ClientRectangle);
// save the image..
bmp.Save(yourfilepath, ImageFormat.Png);
// ..or print it!
}
A few notes:
Due to the using clause the Bitmap get disposed after the last curly, so you would either make use of it inside scope or change to a pattern that disposes of the Bitmap at a later point in time.
The nested Controls will be drawn a reverse order which will cause problem if they are overlapping!
Only nested, not overlayed Controls will be included. Since PictureBox is not a Container (as opposed to e.g. a Panel) it won't do to simply placea, say Label, over it; instead you need to nest it in code, i.e. make the PictureBox its Parent and also set a suitable relative Location..
By default the Bitmap will have the current machine's screen dpi resolution. You cold change it afterwards with bmp.SetResolution()..

Convert PictureBox image to bitmap

I am working with a fingerprint module and am able to capture and display the output in a picture box (C#). Now picture.Image is null even though picturebox displays an image. So I am trying to save the picturebox image as bmp and then assign that bmp to the same picturebox so that Picturebox.image is not null.
Here is the code :
Bitmap bmp = new Bitmap(picFP.width, picFP.height);
picFP.DrawToBitmap(bmp, picFP.ClientRectangle);
bmp.Save("path", Imageformat.bmp);
picFP.image = bmp;
Here bitmap image saved is blank. What can be the problem?
A PictureBox has three layers it can display and PictureBox.DrawToBitmap will put all three things into the Bitmap:
The BackgroundImage
The Image
Any graphics created in or from the Paint event
If your bitmap comes out black then you have none of the three, or the last you have is all black.
From your description it seems as if you can display the image in the PictureBox.
So I assume that you don't display it in the right way, probably you do it like this:
using (Graphics G = picFP.CreateGraphics())
G.DrawImage(yourCapturedImage, ..)
This will not work as it only creates non-persistent graphics. These go away with e.g. each minimize-restore cycle and are not called from the DrawToBitmap call
If you really want to draw it onto the PB's surface use the Paint event! But the more natural choice would be to set the PB's Image directly:
picFP.Image = yourCapturedImage;
Update 1 As you now reveal that you don't display it yourself but simply give the control handle to the external code objNitgen=picFP.Handle; the same applies: It is that Nitgen draws only onto the surface and the result is non-persistent.
In this case the remedy is either
Taking a screenshot of the result and then work from that. Here is a post that shows you how to capture a control via screenshot..
Or you may want to check if Nitgen will draw into a bitmap directly..
For this you should be to pass it not a handle to the PictureBox but to a Bitmap instead:
private void button_Click(object sender, EventArgs e)
{
Bitmap bmp = new Bitmap(picFP.ClientSize.Width, picFP.ClientSize.Height);
Graphics G = Graphics.FromImage(bmp);
IntPtr dc= G.GetHdc();
objNitgen = dc;
objNitgen.capture();
G.ReleaseHdc(dc);
pictureBox1.Image = bmp; // now display..
bmp.Save(yourfilename); // .. and/or save
}
Update 2
You noted in a comment that doing a manual screenshot also does not capture the image; so it seems the control handle is only used to overlay it with the image much like video overlays do; if this is the case I doubt you can get at the image without using other, more fitting Nitgen SDK methods.

Paste the contents of a Bitmap into a PictureBox

I'm currently writing a little paint application where the user is able to draw on a Panel. I am working on the select tool and want to be able to select a certain area of the Panel, and then paste this selected area directly into a PictureBox that I have just to the right of the Panel.
My problem is that my code at the moment is not working correctly, when I try to paste the Bitmap that I am creating from the panel I am getting a big red X in the PictureBox instead of the actual image. I know that the image is copying to the Bitmap correctly because I tried putting some code around it to save it to disk as a jpeg and then look at the image, and it is all displaying fine.
Here is my code:
private void tbCopy_Click(object sender, EventArgs e)
{
int width = selectList[0].getEnd().X - selectList[0].getInitial().X;
int height = selectList[0].getEnd().Y - selectList[0].getInitial().Y;
using (Bitmap bmp = new Bitmap(width, height))
{
pnlDraw.DrawToBitmap(bmp, new System.Drawing.Rectangle(
selectList[0].getInitial().X,
selectList[0].getInitial().Y,
width, height));
pbPasteBox.Image = bmp;
}
}
the width and height are just the dimensions of the area that I want to copy, and selectList is a List that contains one object which contains the coordinates of the area I want to copy.
Any help would be greatly appreciated.
Your problem is the using(){} when the code inside the using braces has completed the object inside the () is disposed of as it is deemed no longer needed.
Simply removing the brace to just have Bitmap bmp = new Bitmap(width, height) should solve your problem

Make overlapping picturebox transparent in C#.net

I have two overlapping pictureboxes.The images of both picture boxes have some transparent pixels.I want to see the bottom picture box through the transparent pixels of the overlapping picture box.
I tried setting the background color of both picture boxes as transparent.But it just sets the back color of the picture box to the background color of the form.
Clearly you are using Winforms. Yes, transparency is simulated by drawing the pixels of the Parent. Which is the form, you only see the form pixels, stacking effects don't work. There's a KB article that shows a workaround for this. It is painful. Another approach is to not use PictureBox controls but just draw the images in the form's Paint event.
Consider WPF, it has a very different rendering model that easily supports transparency.
Solutions to that problem might be various, and it mainly depends on your skills and amount of work will depend on kind of images you're dealing with. For example if images are always same resolution, size and overlapping image supports transparency you could try to do manipulation of two Image objects and draw one over another, then display it in PictureBox. Or if you will need to do it multiple times in various places of your app you could even consider creating your own UserContriol.
Code in answer of this question, method ResizeImagein particular, show how to create resized, good quality image, all you need it is to change it a little. Make it to get two Images as input parameters, and change it to draw one image over another.
Changes might look like this
public static Bitmap CombineAndResizeTwoImages(Image image1, Image image2, int width, int height)
{
//a holder for the result
Bitmap result = new Bitmap(width, height);
//use a graphics object to draw the resized image into the bitmap
using (Graphics graphics = Graphics.FromImage(result))
{
//set the resize quality modes to high quality
graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
//draw the images into the target bitmap
graphics.DrawImage(image1, 0, 0, result.Width, result.Height);
graphics.DrawImage(image2, 0, 0, result.Width, result.Height);
}
//return the resulting bitmap
return result;
}
And use it, for example, like this:
pictureBox1.Image = CombineAndResizeTwoImages(Image.FromFile("c:\\a.png"), Image.FromFile("c:\\b.png"), 100,100);
But that its only example, and you must tune it up to your needs.
Good luck.
If it's one PictureBox inside another, you can use:
innerPictureBox.SendToBack();
innerPictureBox.Parent = outerPictureBox;

How do I convert a Graphics object to a Bitmap object, inside PrintPage event?

This is the high level problem I'm trying to solve...
I have a 3rd party plotting/graphing (IoComp Plot), and I want to embed a high quality (at least 600 dpi) bitmap of the Plot control in reports created by another 3rd party report package (Combit List & Label).
This is the approach that seems most promising so far...
---Edit---:
After trying many other approachs, the only one that I think I can make work is to create a hidden instance of the Plot control, with everything scaled up to printer size (approx 5 times screen size). That includes width and height, font sizes, line widths - every visible component of the control. Yuck!
------
I can get a Graphics object of the proper resolution from the plot control's PrintPage event, but converting it to a Bitmap so the report package will be happy is proving to be the major stumbling block. Several hours of searching has led to other people who asked the same question, but no viable answers.
The only promising lead I've found suggested using one of the Bitmap constructors, which takes a Graphics instance as a parameter.
However, it's not working for me. It creates Bitmap, but with no content from the Plot control - it is a pure black image.
Here's my code (edited to show drawing of red line to Graphics object):
void PrintDocument_PrintPage(object sender, PrintPageEventArgs e)
{
// Draw a red line on the Graphics object. When printed, this
// line is shown as part of the normal Plot graphics.
Pen myPen;
myPen = new Pen(Color.Red);
e.Graphics.DrawLine(myPen, 0, 0, 200, 200);
myPen.Dispose();
// Create a bitmap from the Graphics object
Bitmap bm = new Bitmap(1000, 1000, e.Graphics);
// Save to disk
// DOES NOT WORK - CREATES FILE THAT IS PURE BLACK (VIEWED
// WITH "PAINT" PROGRAM)
bm.Save(#"C:\Bicw_Dev\Bic.Net\FrontEnd\GraphicsToBmp.bmp", ImageFormat.Bmp);
bm.Dispose();
}
Can anyone suggest why this doesn't work? Is this even a valid approach?
Also, please note:
As far as I can determine (and I've spent quite a bit of time looking) there is no way to get a high resolution, print quality Bitmap from the Plot control directly!
I stress this because several others who asked the question got code samples in response that solved the opposite problem - converting a Bitmap to a Graphics.
I need to convert a Graphics object to a Bitmap object.
And if anyone can suggest an alternate approach that allows me to get a print quality image of my plots into my reports, please feel free. (For example, I can get a low quality (72 bpi) Bitmap from the Plot control, and have considered trying to stretch it - but I've never seen that approach work well in other applications).
Thanks,
-Tom Bushell
Edit in response to comment:
As an experiment, I added the following:
Pen myPen;
myPen = new Pen(Color.Red);
e.Graphics.DrawLine(myPen, 0, 0, 200, 200);
myPen.Dispose();
This caused a red line to be drawn over the plot graphics when I printed my plot. But it had no effect on the Bitmap - it's still pure black.
However, it's not working for me. It
creates Bitmap, but with no content
from the Plot control - it is a pure
black image.
Well you never do paint to the graphics, what do you expect?
You are suppose to do the actual drawing for the output in that event.
The constructor you're using does not copy any graphics, only sets the resolution equal to the graphics resolution. See msdn. As Leppie points out, you have to actually draw something to the bitmap. I suggest getting another graphics object for the item you just created.
Graphics g = Graphics.FromImage(bmp);
//Make the background white
g.FillRectangle(Brushes.White, 0, 0, 1000, 1000);
It is not easy to control the DPI in the Print(Preview) system.
But maybe you are going about it the wrong way. What you want is to create a (large) bitmap and then 'trick' the control in to using that bitmap as if it was the screen. See this list of links.
No need for PrintDocument.

Categories