16

I just wondered if it would be possible to create a small, simple jpg, png, gif with a given Text in powershell:

e.g: a small square, 250px × 61px, yellow background and black text on it: "Test"

Can I do this with "System.Drawing.Image"?

Thanks

cherouvim
  • 31,725
  • 15
  • 104
  • 153
icnivad
  • 2,231
  • 8
  • 29
  • 35

1 Answers1

29

Sure, if you're on PowerShell 2.0 try this:

Add-Type -AssemblyName System.Drawing

$filename = "$home\foo.png" 
$bmp = new-object System.Drawing.Bitmap 250,61 
$font = new-object System.Drawing.Font Consolas,24 
$brushBg = [System.Drawing.Brushes]::Yellow 
$brushFg = [System.Drawing.Brushes]::Black 
$graphics = [System.Drawing.Graphics]::FromImage($bmp) 
$graphics.FillRectangle($brushBg,0,0,$bmp.Width,$bmp.Height) 
$graphics.DrawString('Hello World',$font,$brushFg,10,10) 
$graphics.Dispose() 
$bmp.Save($filename) 

Invoke-Item $filename  
Keith Hill
  • 194,368
  • 42
  • 353
  • 369
  • Add-Type isn't available in PS 1.0, instead you can use: [Reflection.Assembly]::LoadWithPartialName("System.Drawing") – Mark Foreman Sep 12 '12 at 03:57
  • NB: it seems that the file created is a PNG (i.e. there's no special logic in the `Save` function to convert to the format appropriate for the filename. Instead you can pass a second parameter to change the file format: `$bmp.Save($filename,[System.Drawing.Imaging.ImageFormat]::Jpeg)`. https://msdn.microsoft.com/en-us/library/system.drawing.image.save(v=vs.110).aspx – JohnLBevan Mar 08 '16 at 19:28