C#: Draw one Bitmap onto Another, with Transparency - c#

I have two Bitmaps, named largeBmp and smallBmp. I want to draw smallBmp onto largeBmp, then draw the result onto the screen. SmallBmp's white pixels should be transparent. Here is the code I'm using:
public Bitmap Superimpose(Bitmap largeBmp, Bitmap smallBmp) {
Graphics g = Graphics.FromImage(largeBmp);
g.CompositingMode = CompositingMode.SourceCopy;
smallBmp.MakeTransparent();
int margin = 5;
int x = largeBmp.Width - smallBmp.Width - margin;
int y = largeBmp.Height - smallBmp.Height - margin;
g.DrawImage(smallBmp, new Point(x, y));
return largeBmp;
}
The problem is that the result winds up transparent wherever smallBmp was transparent! I just want to see through to largeBmp, not to what's behind it.

CompositingMode.SourceCopy is the problem here. You want CompositingMode.SourceOver to get alpha blending.

Specify the transparency color of your small bitmap. e.g.
Bitmap largeImage = new Bitmap();
Bitmap smallImage = new Bitmap();
--> smallImage.MakeTransparent(Color.White);
Graphics g = Graphics.FromImage(largeImage);
g.DrawImage(smallImage, new Point(10,10);

Winform copy image on top of another
private void timerFFTp_Tick(object sender, EventArgs e)
{
if (drawBitmap)
{
Bitmap bitmap = new Bitmap(_fftControl.Width, _fftControl.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
_fftControl.DrawToBitmap(bitmap, new Rectangle(0, 0, _fftControl.Width, _fftControl.Height));
if (!fDraw)
{
bitmap.MakeTransparent();
Bitmap fftFormBitmap = new Bitmap(_fftForm.BackgroundImage);
Graphics g = Graphics.FromImage(fftFormBitmap);
g.DrawImage(bitmap, 0, 0);
_fftForm.BackgroundImage = fftFormBitmap;
}
else
{
fDraw = false;
_fftForm.Width = bitmap.Width + 16;
_fftForm.Height = bitmap.Height + 48;
_fftForm.BackgroundImage = bitmap;
}
}
}

Related

how to have my rectangle always on the middle of the image without knowing the size of the incomming image

Trying to add a watermark image to a png image, i´ve been able to do it, but i want to take out the hardCoded size regulation for the rectangle of the waterMark, and make it always stay in the center of the image. How can i achieve this.
public Form1()
{
InitializeComponent();
picBox.Parent = this;
picBox.Dock = DockStyle.Fill;
picBox.SizeMode = PictureBoxSizeMode.Zoom;
Bitmap Jpg = new Bitmap(#"C:\Users\tferreira\Desktop\213123.PNG");
using (Bitmap Bmp = new Bitmap(#"C:\Users\tferreira\Desktop\logo.png"))
{
using (Bitmap WatermarkBmp = new Bitmap(Bmp, Bmp.Width / 1, Bmp.Height / 1))
{
picBox.Image = WatermarkImage(Jpg, WatermarkBmp, new Point(400, 100), 0.40F);
}
}
}
public Bitmap WatermarkImage(Bitmap ImageToWatermark, Bitmap Watermark, Point WatermarkPosition, float Opacity)
{
using (Graphics G = Graphics.FromImage(ImageToWatermark))
{
using (ImageAttributes IA = new ImageAttributes())
{
ColorMatrix CM = new ColorMatrix();
CM.Matrix33 = Opacity;
IA.SetColorMatrix(CM);
G.DrawImage(Watermark, new Rectangle(WatermarkPosition, Watermark.Size), 0, 0, Watermark.Width, Watermark.Height, GraphicsUnit.Pixel, IA);
}
}
return ImageToWatermark;
}
Right now the images are hardCoded but that will be taken out. If anyone can help me make this watermark allways stay centered i thank you.
I fixed this problem with this nice peace of code.
System.Drawing.Image img = System.Drawing.Image.FromFile(JpgFilePath);
Bitmap jpg = new Bitmap(img);
filePath = JpgFilePath;
int Width = jpg.Width;
int Height = jpg.Height;
jpg.SetResolution(300, 300);
WaterMarked = WatermarkImage(jpg, WaterMarkBit, new Point((Width - WaterMarkBit.Width) / 2, (Height - WaterMarkBit.Height) / 2), 0.4F);
WaterMarked.Save(filePath.Replace(".jpg", "") + ".tif", ImageFormat.Tiff);
filesJpgForTif.Add(JpgFilePath.Replace("jpg", "tif"));
Using the the sizes of the image and sizes of the watermark and divide it by 2 it makes the image always stay centered.

Get pixel perfect zooming [duplicate]

I am developing an application for image processing. To zoom the image, I enlarge PictureBox. But after enlarging I get below image as result.
But I want result like below image
Here is my Code :
picturebox1.Size = new Size((int)(height * zoomfactor), (int)
(width* zoomfactor));
this.picturebox1.Refresh();
The PictureBox by itself will always create a nice and smooth version.
To create the effect you want you need to draw zoomed versions yourself. In doing this you need to set the
Graphics.InterpolationMode = InterpolationMode.NearestNeighbor;
Then no blurring will happen..
Example:
private void trackBar1_Scroll(object sender, EventArgs e)
{
Bitmap bmp = (Bitmap)pictureBox1.Image;
Size sz = bmp.Size;
Bitmap zoomed = (Bitmap)pictureBox2.Image;
if (zoomed != null) zoomed.Dispose();
float zoom = (float)(trackBar1.Value / 4f + 1);
zoomed = new Bitmap((int)(sz.Width * zoom), (int)(sz.Height * zoom));
using (Graphics g = Graphics.FromImage(zoomed))
{
if (cbx_interpol.Checked) g.InterpolationMode = InterpolationMode.NearestNeighbor;
g.PixelOffsetMode = PixelOffsetMode.Half;
g.DrawImage(bmp, new Rectangle( Point.Empty, zoomed.Size) );
}
pictureBox2.Image = zoomed;
}
Of course you need to avoid setting the PBox to Sizemode Zoom or Stretch!

Watermark not drawing in image

I had an error come up:
A Graphics Object cannot be Created from an Image that has an Indexed Pixel Format
So I implemented this code into my method: Solution for "A Graphics Object cannot be Created from an Image that has an Indexed Pixel Format"
But now my watermark doesnt want to draw on my image.
Please can anyone assist.
Code:
private Image AddWaterMark(Image original)
{
Image waterMark = Image.FromFile(ConfigurationManager.AppSettings["GalleryFolder"] + #"\watermark.png");
Bitmap bm = (Bitmap)original;
Size waterMarkResize = ResizeFit(new Size(original.Width, original.Height));
using (Image watermarkImage = new Bitmap(waterMark, waterMarkResize))
using (Graphics imageGraphics = Graphics.FromImage(new Bitmap(bm.Width, bm.Height)))
{
imageGraphics.DrawImage(bm, new Rectangle(0, 0, bm.Width, bm.Height), 0, 0, bm.Width, bm.Height, GraphicsUnit.Pixel);
using (TextureBrush watermarkBrush = new TextureBrush(watermarkImage))
{
int x = (original.Width / 2 - watermarkImage.Width / 2);
int y = (original.Height / 2 - watermarkImage.Height / 2);
watermarkBrush.TranslateTransform(x, y);
imageGraphics.FillRectangle(watermarkBrush, new Rectangle(new Point(x, y), new Size(watermarkImage.Width + 1, watermarkImage.Height)));
}
}
return bm;
}
You're creating a new Bitmap to pass to Graphics.FromImage then returning the uneditted original Bitmap. Create the new Bitmap independently, pass it to FromImage then return the new Bitmap.
var edit = new Bitmap(bm.Width, bm.Height);
// ...
using (Graphics imagesGraphics = Graphics.FromImage(edit))
{
// draw original
// draw watermark
}
return edit;

How to overlay two picturebox c# but the picturebox in the background can be seen

Good day
i don't know if my title is correct. sorry for my bad english
How to overlay two picturebox using c# inoder to achieve the image below, and change the opacity of upper picture box on runtime.
what i need to achieve is something like this. i have two images and i need to overlay them
first image:
enter image description here
and i have second image with a text of: Another Text on image.
and the location of the text is lower than the text location of the first image
(i can't upload more than two image because i don't have 10 reputation yet.)
i need to do like on the image below, but using two picturebox and can change the opacity in order for the second picturebox below the first one to be seen
and the output of the two image:
enter image description here
i created the output image using java. i know that i can run the jar file using c#. but the user required to changed the opacity on run time. so how can i do this?
this is the java code i used
BufferedImage biInner = ImageIO.read(inner);
BufferedImage biOutter = ImageIO.read(outter);
System.out.println(biInner);
System.out.println(biOutter);
Graphics2D g = biOutter.createGraphics();
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f));
int x = (biOutter.getWidth() - biInner.getWidth()) / 2;
int y = (biOutter.getHeight() - biInner.getHeight()) / 2;
System.out.println(x + "x" + y);
g.drawImage(biInner, x, y, null);
g.dispose();
ImageIO.write(biOutter, "PNG", new File(output));
i hope my question is understandable. thank you
Here you go, just a sample, but blueBox is transparent (0.5):
public sealed partial class Form1 : Form
{
private readonly Bitmap m_BlueBox;
private readonly Bitmap m_YellowBox;
public Form1()
{
InitializeComponent();
DoubleBuffered = true;
m_YellowBox = CreateBox(Color.Yellow);
m_BlueBox = CreateBox(Color.Blue);
m_BlueBox = ChangeOpacity(m_BlueBox, 0.5f);
}
public static Bitmap ChangeOpacity(Image img, float opacityvalue)
{
var bmp = new Bitmap(img.Width, img.Height);
using (var graphics = Graphics.FromImage(bmp))
{
var colormatrix = new ColorMatrix();
colormatrix.Matrix33 = opacityvalue;
var imgAttribute = new ImageAttributes();
imgAttribute.SetColorMatrix(colormatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
graphics.DrawImage(img, new Rectangle(0, 0, bmp.Width, bmp.Height), 0, 0, img.Width, img.Height,
GraphicsUnit.Pixel, imgAttribute);
}
return bmp;
}
private static Bitmap CreateBox(Color color)
{
var bmp = new Bitmap(200, 200);
for (var x = 0; x < bmp.Width; x++)
{
for (var y = 0; y < bmp.Height; y++)
{
bmp.SetPixel(x, y, color);
}
}
return bmp;
}
private void Form1_Paint(object sender, PaintEventArgs e)
{
e.Graphics.DrawImage(m_YellowBox, new Point(10, 10));
e.Graphics.DrawImage(m_BlueBox, new Point(70, 70));
}
}

Can't resize the changed image? C# WinForms

If i change the colour of the image and then try to resize, it only resizes the original image. Why is this happening and how do i fix it?
Here is my code:
private PrintDocument printDoc = new PrintDocument();
private PageSettings pgSettings = new PageSettings();
private PrinterSettings prtSettings = new PrinterSettings();
Bitmap myBitmapImage; // image (bitmap) for some background mountains
Boolean isInvert = false;
Boolean isLOaded = false;
Boolean isGrayscale = false;
Boolean isThreshold = false;
Boolean isResize = false;
OpenFileDialog ofd;
Bitmap bmBack;
public EditImage()
{
printDoc.PrintPage += new PrintPageEventHandler(printDoc_PrintPage);
InitializeComponent();
this.SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | ControlStyles.DoubleBuffer, true);
}
private void EditImage_Load(object sender, EventArgs e)
{
}
private void EditImage_Paint(object sender, PaintEventArgs e)
{
if (isLOaded == true)
{
Graphics gWindow; // reference to the graphic surface of this window
Graphics gBack; // reference to in-memory surface
bmBack = new Bitmap(Width, Height); // bitmap for window surface copy
gWindow = e.Graphics; // get our current window's surface
gBack = Graphics.FromImage(bmBack); // create surfaces from the bitmaps
gBack.DrawImage(myBitmapImage, 0, 0, Width, Height);
if (isInvert == true)
{
InvertBitmap(bmBack);
}
else if (isGrayscale == true)
{
GrayscaleBitmap(bmBack);
}
else if (isThreshold == true)
{
ThresholdBitmap(bmBack);
}
else if (isResize == true)
{
bmBack = resizeImage(bmBack, 10, 100);
}
gWindow.DrawImage(bmBack, 0, 0);
}
}
private void toolStripMenuItemLoadImage_Click(object sender, EventArgs e)
{
using (ofd = new OpenFileDialog())
{
ofd.Title = "Load Image";
if (ofd.ShowDialog() == DialogResult.OK)
{
myBitmapImage = new Bitmap(ofd.FileName);
this.Invalidate();
}
}
isLOaded = true;
}
private void GrayscaleBitmap(Bitmap bmp)
{
Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
System.Drawing.Imaging.BitmapData bmpData = bmp.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite,
System.Drawing.Imaging.PixelFormat.Format32bppRgb);
IntPtr ptr = bmpData.Scan0;
int numPixels = bmpData.Width * bmp.Height;
int numBytes = numPixels * 4;
byte[] rgbValues = new byte[numBytes];
System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, numBytes);
for (int i = 0; i < rgbValues.Length; i += 4)
{
byte gray = (byte)(.3 * rgbValues[i + 0]); //blue
gray += (byte)(.59 * rgbValues[i + 1]); //green
gray += (byte)(.11 * rgbValues[i + 2]); //red
rgbValues[i + 0] = gray; //blue
rgbValues[i + 1] = gray; //green
rgbValues[i + 2] = gray; //red
}
System.Runtime.InteropServices.Marshal.Copy(rgbValues, 0, ptr, numBytes);
bmp.UnlockBits(bmpData);
}
private Bitmap resizeImage(Bitmap sourceBMP, int width, int height)
{
Bitmap result = new Bitmap(width, height);
using(Graphics g = Graphics.FromImage(result))
g.DrawImage(sourceBMP, 0, 0, width, height);
return result;
}
i also have methods which deal with when the user clicks on a button and sets the bools to appropriate values so that it calls the correct method. The images DO change colour - as intended.. but when i click on resize, i want it to resize the version of the image that has changed colour - not the original image...
There are lots of things wrong here:
resizeImage()
You should dispose of the Graphics object that you create here (wrap it in a using() statement)
Don't call invalidate from here, this function just resizes your image, you invalidate after you've changed your image and your Paint method paints the image which has now changed.
You should also think about disposing of the sourceBMP right before you return the function if you no longer have any use for it.
GrayscaleBitmap()
This looks right, but again there's no reason to invalidate here. You should invalidate after you call this method in the calling function. It makes more sense.
EditImage_Paint
You should not be calling these functions from within your Paint event. And you should not be creating a new Bitmap and a new Graphics class on each Paint. This is way more work than necessary. These functions should only execute when the data needs to be changed based on user input (user clicks a button to apply a grayscale effect).
For what you want to do, you should only need 2 bitmap variables at most. One to store the original unmodified bitmap in case you want to let the user "Reset" it or to undo any effects (most effects cause permanent data loss, you can't make a grayscale image color again). And the other to store the bitmap that gets painted. Each time the user applies an effect, it modifies the 2nd bitmap, and then calls invalidate.
All your Paint function should do is paint the 2nd bitmap:
Bitmap originalBitmap; // load from file, do not modify
Bitmap currentBitmap; // when user clicks an effect, modify this bitmap and then Invalidate afterward
private void EditImage_Paint(object sender, PaintEventArgs e)
{
e.Graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
// Draw the currentBitmap centered on the window
SizeF clientSize = this.ClientSize;
double zoomRatio = Math.Min(
clientSize.Width / currentBitmap.Width,
clientSize.Height / currentBitmap.Height
);
SizeF zoomedSize = new SizeF(
(float)(currentBitmap.Width * zoomRatio),
(float)(currentBitmap.Height * zoomRatio)
);
PointF imageOffset = new PointF(
(clientSize.Width - zoomedSize.Width) / 2,
(clientSize.Height - zoomedSize.Height) / 2
);
e.Graphics.Clear(Color.White);
e.Graphics.DrawImage(currentBitmap, imageOffset.X, imageOffset.Y, zoomedSize.Width, zoomedSize.Height);
}
This emulates a simple zoom effect that centers the image on the control and draws it to fit the window.

Categories

Resources