B
Bryan Valencia
Guest
Here is a minimal console app that makes a supposedly transparent PNG. There is *something* missing, as it has two problems.
If you are going to try this code youll need to add a reference to System.Drawing.
using System.Drawing;
using System.Drawing.Imaging;
namespace TransparentPNGTests
{
class Program
{
static void Main(string[] args)
{
using (var bmp = new System.Drawing.Bitmap(100, 100, PixelFormat.Format32bppArgb))
using (Graphics g = Graphics.FromImage(bmp))
{
//set up bitmap
g.Clear(Color.White);
//draw text
Font f= new Font("Univers", 14f, FontStyle.Bold, GraphicsUnit.Pixel);
Brush b = Brushes.Green;
Rectangle textrect = new Rectangle(5, 5, 90, 90);
g.DrawString("This is a bunch of text, for texting.", f, b, textrect);
//save
Image image = Image.FromHbitmap(bmp.GetHbitmap());
image.Save("image.png");
}
}
}
}
The image produced by this is here.
if I change the g.clear line to g.Clear(Color.Transparent);, I get this.
Note that the background is NOT transparent, and the text is messed up.
PLEASE someone tell me what I am missing.
Ultimately this code is meant to generate a PNG for a web site, so it will be streamed, not saved.
Id rather live with false hope than with false despair.
Continue reading...
- It cannot make transparency
- it messes up the fonts.
If you are going to try this code youll need to add a reference to System.Drawing.
using System.Drawing;
using System.Drawing.Imaging;
namespace TransparentPNGTests
{
class Program
{
static void Main(string[] args)
{
using (var bmp = new System.Drawing.Bitmap(100, 100, PixelFormat.Format32bppArgb))
using (Graphics g = Graphics.FromImage(bmp))
{
//set up bitmap
g.Clear(Color.White);
//draw text
Font f= new Font("Univers", 14f, FontStyle.Bold, GraphicsUnit.Pixel);
Brush b = Brushes.Green;
Rectangle textrect = new Rectangle(5, 5, 90, 90);
g.DrawString("This is a bunch of text, for texting.", f, b, textrect);
//save
Image image = Image.FromHbitmap(bmp.GetHbitmap());
image.Save("image.png");
}
}
}
}
The image produced by this is here.
if I change the g.clear line to g.Clear(Color.Transparent);, I get this.
Note that the background is NOT transparent, and the text is messed up.
PLEASE someone tell me what I am missing.
Ultimately this code is meant to generate a PNG for a web site, so it will be streamed, not saved.
Id rather live with false hope than with false despair.
Continue reading...