Asem Khen
Asem Khen

Reputation: 361

How to add a colored background to PNG or add a Color overlay to an Image?

What is the proper wax to give a PNG image a colored background. as shown in the example below:
A PNG Image with different levels of opacity and transparent background: A PNG Image with different levels of opacity and transparent background

A PNG image with a background color applied: A PNG image with a background color applied

The question is to reproduce a new Image from the old one with a specified color.

The second part is how to add a color overlay to a PNG Image. perhaps replace the white with the new color.

This is the example PNG I have: This is the example PNG I have

And this is the example PNG I want to get: And this is the example PNG I want to get

Upvotes: 0

Views: 662

Answers (1)

Asem Khen
Asem Khen

Reputation: 361

Correct me if I am wrong .. but this might be a possibility to use a grayscale image instead of a PNG with an alpha channel

Bitmap colorBitmap(Color forGroundColor, Color backGroundColor, Bitmap bmpGrayScale)
{
  Size size = bmpGrayScale.Size;
  Bitmap applyForgroundColor= new Bitmap(size.Width, size.Height);
  Rectangle rect1 = new Rectangle(Point.Empty, bmpGrayScale.Size);
  using (Graphics G1 = Graphics.FromImage(applyForgroundColor) )
  {
    G1.Clear(forGroundColor);
    G1.DrawImageUnscaledAndClipped(applyForgroundColor, rect1);
  }
  for (int y = 0; y < size.Height; y++)
    for (int x = 0; x < size.Width; x++)
    {
      Color c1 = applyForgroundColor.GetPixel(x, y);
      Color c2 = bmpGrayScale.GetPixel(x, y);
      applyForgroundColor.SetPixel(x, y, Color.FromArgb((int)(255 * c2.GetBrightness()), c1 ) );
    }

  Bitmap applyBackgroundColor= new Bitmap(size.Width, size.Height);
  Rectangle rect2 = new Rectangle(Point.Empty, bmpGrayScale.Size);
  using (Graphics G2 = Graphics.FromImage(applyBackgroundColor) )
  {
    G2.Clear(backGroundColor);
    G2.DrawImageUnscaledAndClipped(applyForgroundColor, rect2);
  }
  return applyBackgroundColor;
}

Upvotes: 1

Related Questions