Is there a way to overlay or merge a Drawing.Bitmap and a DrawingImage
In a windows forms application, 开发者_StackOverflow社区I have as input a Drawing.Bitmap and a DrawingImage. I need to overlay them and put there output in a Controls.Image. How can I do this?
It doesn't matter if you use Image
object or Bitmap
object, The Drawing.Image
is abstract class and Drawing.Bitmap
inherited from it. to
draw image over image, get the graphics object from the base image and then use Graphics.DrawImage which accept parameter of type Image
.
So you have two images here, one should be printed "overlay" over the other image:
System.Drawing.Image primaryImage = Image.FromFile(@"Your file path");//or resource..
using (Graphics graphics = Graphics.FromImage(primaryImage))//get the underlying graphics object from the image.
{
using (Bitmap overlayImage = new Bitmap(primaryImage.Width, primaryImage.Hieght,
System.Drawing.Imaging.PixelFormat.Format32bppArgb)//or your overlay image from file or resource...
{
graphics.DrawImage(overlayImage, new Point(0, 0));//this will draw the overlay image over the base image at (0, 0) coordination.
}
}
Control.Image = primaryImage;
Not that if the overlay image doesn't have some transparent, and its size is equals or larger than the base image, it will overlap the other image completely, so you the overlay image must have some opacity.
I realize it has been awhile, but the answers here weren't quite working for me. A little tweaking, though made them work fine. For what it is worth, here is my final version.
SCENARIO:
- background image is RGB 24
- overlay image is ARGB 32 with alpha channel already set properly.
- images created from a memory stream
PROBLEM:
- Creating the overlay image from the memory stream assumed I meant:
Format32bppRgb
- But what is needed is
Format32bppArgb
since the transparency is already in place..
SOLUTION:
pictureBox1.Image = MergeImages( backgroundImage, overlayImage);
using System.Drawing; using System.Drawing.Imaging; // ... private Image MergeImages(Image backgroundImage, Image overlayImage) { Image theResult = backgroundImage; if (null != overlayImage) { Image theOverlay = overlayImage; if (PixelFormat.Format32bppArgb != overlayImage.PixelFormat) { theOverlay = new Bitmap(overlayImage.Width, overlayImage.Height, PixelFormat.Format32bppArgb); using (Graphics graphics = Graphics.FromImage(theOverlay)) { graphics.DrawImage(overlayImage, new Rectangle(0, 0, theOverlay.Width, theOverlay.Height), new Rectangle(0, 0, overlayImage.Width, overlayImage.Height), GraphicsUnit.Pixel); } ((Bitmap)theOverlay).MakeTransparent(); } using (Graphics graphics = Graphics.FromImage(theResult)) { graphics.DrawImage(theOverlay, new Rectangle(0, 0, theResult.Width, theResult.Height), new Rectangle(0, 0, theOverlay.Width, theOverlay.Height), GraphicsUnit.Pixel); } } return theResult; }
精彩评论