{

What if you had a client who has a big product catalog you're integrating with the web.  You work out a convention for how data is displayed and want to generate some test images for yourself...

First, just some basics on generating a single image:

import clr
clr.AddReference("System.Drawing")
from System import *
from System.Drawing import *

def GenerateImage(text):
starter = Bitmap(1,1)
g = Graphics.FromImage(starter)
f = Font("Arial", 14)
theImage = Bitmap(starter, Size(200,200))
g = Graphics.FromImage(theImage)
g.Clear(Color.Orange)
g.DrawString(text, f, SolidBrush(Color.DarkBlue), 0, 0)
g.Flush()
theImage.Save("c:\\temp\\pyImage.gif")

if __name__ == "__main__":
GenerateImage("Holly was a hunter")



Here's some TSQL for the sample data I'll use:

create table testdata(
testid int identity(1,1),
testvalue varchar(50)
)

declare @i int
set @i = 0
while @i < 25 begin
insert into testdata(testvalue)
values('PRODUCT ' + convert(varchar(2), @i))
set @i = @i + 1
end



Now for a finalized version that hits the database and generates images:

import clr
clr.AddReference("System.Drawing")
clr.AddReference("System.Data")

from System import *
from System.Drawing import *
from System.Data import *
from System.Data.SqlClient import *

def GenerateImage(text, path):
starter = Bitmap(1,1)
g = Graphics.FromImage(starter)
f = Font("Arial", 14)
theImage = Bitmap(starter, Size(200,200))
g = Graphics.FromImage(theImage)
g.Clear(Color.Orange)
g.DrawString(text, f, SolidBrush(Color.DarkBlue), 0, 0)
g.Flush()
theImage.Save(path)

def GenerateImagesFromDatabase(connectString, query, sourceColumn, outPath):
cn = SqlConnection(connectString)
cn.Open()
cmd = SqlCommand(query, cn)
r = cmd.ExecuteReader(CommandBehavior.CloseConnection)
while r.Read():
baseText = r[sourceColumn].ToString()
GenerateImage(baseText, outPath + "\\" + baseText + ".gif")
r.Close()

if __name__ == "
__main__":
connect = "
Data Source=.\\sqlexpress;Initial Catalog=MVCBaby;Integrated Security=SSPI;"
sql = "
select * from testdata"
col = "
testvalue"
GenerateImagesFromDatabase(connect, sql, col, "
c:\\temp\\fobot")




 


Pretty cool stuff, I hope it's useful to more people than just myself.  Download the first script here, the second more elaborate one here.


}