Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create bitmap via Powershell

I'd like to learn to create/edit images with Powershell. Help me, please, to create bitmap image, fill it with some color, set color of some pixel to some other color and save image to file.

EDIT: I tried following code, but got a black bitmap

[System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
$bmp = New-Object System.Drawing.Bitmap(320, 240)

for ($i = 0; $i -lt 100; $i++)
{
   for ($j = 0; $j -lt 100; $j++)
   {
     $bmp.SetPixel($i, $j, 1000)
   }
}

$bmp.Save("f:\Temp\bmp.bmp")
ii f:\Temp\bmp.bmp
like image 210
Loom Avatar asked Sep 18 '12 20:09

Loom


1 Answers

SetPixel takes a final argument of type System.Drawing.Color. Powershell is converting the integer 1000 into a Color object, and this ends up with basically a "black" color:

PS > [system.drawing.color] 1000

R             : 0
G             : 3
B             : 232
A             : 0       # A is "Alpha", aka opacity. A = 0 -> full transparent
IsKnownColor  : False
IsEmpty       : False
IsNamedColor  : False
IsSystemColor : False
Name          : 3e8

You can either pass a string corresponding to a known named color (e.g. 'Red'), or create a custom RGB color from either [System.Drawing.Color]::FromArgb($r, $g, $b) or [System.Drawing.Color]::FromArgb($a, $r, $g, $b), where all arguments can be from 0 to 255 inclusive. See the docs here and here.

for ($i = 0; $i -lt 100; $i++)
{
   for ($j = 0; $j -lt 100; $j += 2)
   {
     $bmp.SetPixel($i, $j, 'Red')
     $bmp.SetPixel($i, $j + 1, [System.Drawing.Color]::FromArgb(0, 100, 200))
   }
}
like image 151
latkin Avatar answered Sep 22 '22 00:09

latkin