code_junkie

Can you make an alpha transparent PNG with C#?

Nov 13th, 2011
259
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.29 KB | None | 0 0
  1. Font f = GetSystemConfiguredFont();
  2. //this sets the text to be rotated 90deg clockwise (i.e. down)
  3. StringFormat stringFormat = new StringFormat { FormatFlags = StringFormatFlags.DirectionVertical };
  4.  
  5. SizeF size;
  6. // creates 1Kx1K image buffer and uses it to find out how bit the image needs to be to fit the text
  7. using ( Image imageg = (Image) new Bitmap( 1000, 1000 ) )
  8. size = Graphics.FromImage( imageg ).
  9. MeasureString( text, f, 25, stringFormat );
  10.  
  11. using ( Bitmap image = new Bitmap( (int) size.Width, (int) size.Height ) )
  12. {
  13. Graphics g = Graphics.FromImage( (Image) image );
  14. g.FillRectangle( Brushes.White, 0f, 0f, image.Width, image.Height );
  15. g.TranslateTransform( image.Width, image.Height );
  16. g.RotateTransform( 180.0F ); //note that we need the rotation as the default is down
  17.  
  18. // draw text
  19. g.DrawString( text, f, Brushes.Black, 0f, 0f, stringFormat );
  20.  
  21. //make be background transparent - this will be an index (rather than an alpha) transparency
  22. image.MakeTransparent( Color.White );
  23.  
  24. //note that this image has to be a PNG, as GDI+'s gif handling renders any transparency as black.
  25. context.Response.AddHeader( "ContentType", "image/png" );
  26. using ( MemoryStream memStream = new MemoryStream() )
  27. {
  28. image.Save( memStream, ImageFormat.Png );
  29. memStream.WriteTo( context.Response.OutputStream );
  30. }
  31. }
  32.  
  33. using ( Bitmap image = new Bitmap( (int) size.Width, (int) size.Height, PixelFormat.Format32bppArgb ) )
  34. {
  35. Graphics g = Graphics.FromImage( (Image) image );
  36. g.TranslateTransform( image.Width, image.Height );
  37. g.RotateTransform( 180.0F ); //note that we need the rotation as the default is down
  38.  
  39. // draw text
  40. g.DrawString( text, f, Brushes.Black, 0f, 0f, stringFormat );
  41.  
  42. //note that this image has to be a PNG, as GDI+'s gif handling renders any transparency as black.
  43. context.Response.AddHeader( "ContentType", "image/png" );
  44. using ( MemoryStream memStream = new MemoryStream() )
  45. {
  46. //note that context.Response.OutputStream doesn't support the Save, but does support WriteTo
  47. image.Save( memStream, ImageFormat.Png );
  48. memStream.WriteTo( context.Response.OutputStream );
  49. }
  50. }
  51.  
  52. g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;
  53.  
  54. Graphics g = Graphics.FromImage( (Image) image );
Add Comment
Please, Sign In to add comment