Transparent image and background color

Asked

Viewed 800 times

1

I have the following code:

FileStream fs = new FileStream(@"\path\imagem1.png", FileMode.Open, FileAccess.Read);
Image image = Image.FromStream(fs);
fs.Close();

Bitmap b = new Bitmap(image);
Graphics graphics = Graphics.FromImage(b);

graphics.DrawString("Meu texto", new Font("Arial", 50), Brushes.White, 0, 0);
b.Save(@"\path\resultado.png", image.RawFormat);

image.Dispose();
b.Dispose();

Image1: inserir a descrição da imagem aqui

Yeah, there’s a picture there! But it not only has no background color, it also has a great level of transparency.

The problem is that I would like to put a background to it, so the result would be:

inserir a descrição da imagem aqui

I tried to draw a red rectangle, but it superimposes the image.

1 answer

1


Well, the following code solved the problem:

FileStream fs = new FileStream(@"\path\imagem1.png", FileMode.Open, FileAccess.Read);
Image image = Image.FromStream(fs);
fs.Close();

var imageHeight = image.Height;
var imageWidth = image.Width;

Bitmap b = new Bitmap(image);
Graphics graphics = Graphics.FromImage(b);
graphics.Clear(Color.FromArgb(255, Color.Red));

graphics.DrawImage(image, 0, 0, imageWidth, imageHeight);

graphics.DrawString("Meu texto", new Font("Arial", 50), Brushes.White, 0, 0);
b.Save(@"\path\resultado.png", image.RawFormat);

image.Dispose();
b.Dispose();

Browser other questions tagged

You are not signed in. Login or sign up in order to post.