using System.Drawing;
using System.Drawing.Drawing2D;
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))
using (Font f = new Font("Univers", 14f, FontStyle.Regular, GraphicsUnit.Pixel))
{
//set up bitmap
g.Clear(Color.Transparent);
g.SmoothingMode = SmoothingMode.AntiAlias;
g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
//draw text
Brush b = Brushes.Black;
Rectangle textrect = new Rectangle(5, 5, 90, 90);
//using the rectangle instead of a point is a quick way to do word wrapping on the graphic
g.DrawString("This is a bunch of text, for testing.", f, b, textrect);
//save from the bitmap
g.Flush(FlushIntention.Flush); //this seems to be wise, but unnecessary.
bmp.Save("bmpsave.png", ImageFormat.Png);
//save from the image - loses transparency
//Image image = Image.FromHbitmap(bmp.GetHbitmap());
//image.Save("image.png");
}
}
}
}
Note that the last 2 lines:
Image image = Image.FromHbitmap(bmp.GetHbitmap());Are the wrong way. This is the way you'll find if you Google for "How do I save a Graphic object to a file or stream". Somehow, the GetHbitmap function manages to mangle the formatting out of the image.
image.Save("image.png");
Here are the resulting images from this code.
Bitmap.Save() |
Image Save() |
No comments:
Post a Comment