PSE Entertainment Corp
September 06, 2010, 06:51:38 PM *
Welcome, Guest. Please login or register.
Did you miss your activation email?

Login with username, password and session length
News: Enjoy PSE Tunes!  They're great!
 
   Home   Help Search Login Register  
Pages: [1] 2
 1 
 on: July 17, 2010, 09:00:02 AM 
Started by webmaster - Last post by webmaster
The following code will quickly fetch an image from BING maps.  Use your own BING API key.  The latitude and longitude below shows Red Rocks Amphitheatre near Denver, Colorado.

Code:

import urllib2

bingkey = "Get a Bing Maps API Key"
lat = 39.665401
lon = -105.205824
size_x = 300
size_y = 300
zoomLevel = 17

base_url = "http://dev.virtualearth.net/REST/v1/Imagery/Map/Aerial/%s,%s/%s?mapSize=%s,%s&key=%s" \
           % (lat,lon,zoomLevel,size_x,size_y,bingkey)

f = urllib2.urlopen(base_url)
image = open('bing_image.jpg',"wb")
image.write(f.read())
image.close()


 2 
 on: May 26, 2010, 09:51:04 PM 
Started by webmaster - Last post by blah
Indeed - spamming friendly forums is lame!

 3 
 on: May 26, 2010, 09:41:27 PM 
Started by webmaster - Last post by webmaster
Good catch, Etienne!

Indeed, Python 3.x uses "bytes" as new object type.  I wrote this script in Python v2.6 and didn't have that problem.

The original source code has been modified and "bytes" has been replace with "the_bytes" everywhere to make sure it works across python versions.

JDM2

 4 
 on: May 24, 2010, 04:19:11 PM 
Started by webmaster - Last post by riseofthedecays
Hi !

Thanks for this code, it will be very useful for me.
For some reasons, it did not work with my python v3.1.2 :
  • It did not like naming a variable 'bytes' (the IDLE editor detects it as a function name)
  • It didn't recognize '' as an empty bytes object but as an empty string. I replaced it by bytes() and it went fine
You'll find below the modified version of your code that runs ok on my computer.

Code:
#Some key imports.
#Struct is used to create the actual bytes.
#It is super handy for this type of thing.
import struct, random

#Function to write a bmp file.  It takes a dictionary (d) of
#header values and the pixel data (bytes) and writes them
#to a file.  This function is called at the bottom of the code.
def bmp_write(d,byte):
    mn1 = struct.pack('<B',d['mn1'])
    mn2 = struct.pack('<B',d['mn2'])
    filesize = struct.pack('<L',d['filesize'])
    undef1 = struct.pack('<H',d['undef1'])
    undef2 = struct.pack('<H',d['undef2'])
    offset = struct.pack('<L',d['offset'])
    headerlength = struct.pack('<L',d['headerlength'])
    width = struct.pack('<L',d['width'])
    height = struct.pack('<L',d['height'])
    colorplanes = struct.pack('<H',d['colorplanes'])
    colordepth = struct.pack('<H',d['colordepth'])
    compression = struct.pack('<L',d['compression'])
    imagesize = struct.pack('<L',d['imagesize'])
    res_hor = struct.pack('<L',d['res_hor'])
    res_vert = struct.pack('<L',d['res_vert'])
    palette = struct.pack('<L',d['palette'])
    importantcolors = struct.pack('<L',d['importantcolors'])
    #create the outfile
    outfile = open('bitmap_image.bmp','wb')
    #write the header + the bytes
    outfile.write(mn1+mn2+filesize+undef1+undef2+offset+headerlength+width+height+\
                  colorplanes+colordepth+compression+imagesize+res_hor+res_vert+\
                  palette+importantcolors+byte)
    outfile.close()

###################################   
def main():
    #Here is a minimal dictionary with header values.
    #Of importance is the offset, headerlength, width,
    #height and colordepth.
    #Edit the width and height to your liking.
    #These header values are described in the bmp format spec.
    #You can find it on the internet. This is for a Windows
    #Version 3 DIB header.
    d = {
        'mn1':66,
        'mn2':77,
        'filesize':0,
        'undef1':0,
        'undef2':0,
        'offset':54,
        'headerlength':40,
        'width':200,
        'height':200,
        'colorplanes':0,
        'colordepth':24,
        'compression':0,
        'imagesize':0,
        'res_hor':0,
        'res_vert':0,
        'palette':0,
        'importantcolors':0
        }

    #Function to generate a random number between 0 and 255
    def rand_color():
        x = random.randint(0,255)
        return x

    #Build the byte array.  This code takes the height
    #and width values from the dictionary above and
    #generates the pixels row by row.  The row_mod and padding
    #stuff is necessary to ensure that the byte count for each
    #row is divisible by 4.  This is part of the specification.
    byte = bytes()
    for row in range(d['height']-1,-1,-1):# (BMPs are L to R from the bottom L row)
        for column in range(d['width']):
            b = rand_color()
            g = rand_color()
            r = rand_color()
            pixel = struct.pack('<BBB',b,g,r)
            byte = byte + pixel
        row_mod = (d['width']*d['colordepth']/8) % 4
        if row_mod == 0:
            padding = 0
        else:
            padding = (4 - row_mod)
        padbytes = bytes()
        for i in range(padding):
            x = struct.pack('<B',0)
            padbytes = padbytes + x
        byte = byte + padbytes
       
    #call the bmp_write function with the
    #dictionary of header values and the
    #bytes created above.
    bmp_write(d,byte)

if __name__ == '__main__':
    main()

I must tell you how much I'm delighted to have solved this problem, especially because I have been learning python (which is my first language apart from R and a little Matlab at school) for only 2 weeks !!!
Thanks again
Etienne

 5 
 on: May 01, 2010, 12:50:41 PM 
Started by webmaster - Last post by webmaster
The following command line application will create a 128B barcode as an image file of your choice.  Some of this code was found on the internet and the rest was created by the Webmaster.  This application requires the Python Image Library.  I haven't gotten around to generating an output image the hard way so PIL is still required.  One trick to get around that is to use something like PY2EXE and create a stand alone executable.  PIL will be wrapped up inside of the binary.  Enjoy!

Code:
help_text = r"""
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
PY_BARCODE v1.0
Copyright 2010 - PSE Entertainment Corp

This small utility uses the Python Image Library (thanks Fredrick Lundh!)
to create a Code 128 Barcode using Character Set B.  This set includes
most of the normal characters on your keyboard.  The resulting barcode
image will be saved as a file of the following supported types:

jpg, jpeg, gif, png, tif, tiff, bmp

Usage:
py_barcode [string] [valid\path\to\output.png]

Examples:
py_barcode "Hello World" "c:\folder\barcode.png"

py_barcode "98503730-1" "outputbarcode.gif"

py_barcode "Punkin Ninni Rocks!" "c:\folder\subfolder\barcode.jpg"

NOTE:  this help_text displays with ANY error.  Check that the file path
really exists and that you're requesting one of the supported image types.
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
"""

# courbB08.pil PIL Font file uuencoded
courB08_pil ="""eJztl91rFkcUxp+Zt7vGFYzVtiJKICgYlLRWkaBBVGgDraFGCH5gsQp+QMBqabAVRYJYAlakCkoh
CpYgxaLkIu1NvLBeSAStglpqL6xQAsVe2AuL5u2buH3mzGaYPf9AKWTl8d3nl7MzZ2bnazvea9+9
7+PurFWut5e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E4zW9QxnHVYx+bo64mIskDWjZgCrq
eVQFrS7Sh/uFLftIidKWbgj6Oq652d4c3v88Dw2JDK7bSWX/ByuaLZI="""

def decodeFontFile(data, file):
   """ Decode font file embedded in this script and create file """
   from zlib import decompress
   from base64 import decodestring
   from os.path import exists
  
   # If the font file is missing
   if not exists(file):
      # Write font file
      open (file, "wb").write(decompress(decodestring(data)))

CharSetB = {
            ' ':0, '!':1, '"':2, '#':3, '$':4, '%':5, '&':6, "'":7,
            '(':8, ')':9, '*':10, '+':11, ',':12, '-':13, '.':14, '/':15,
            '0':16, '1':17, '2':18, '3':19, '4':20, '5':21, '6':22, '7':23,
            '8':24, '9':25, ':':26, ';':27, '<':28, '=':29, '>':30, '?':31,
            '@':32, 'A':33, 'B':34, 'C':35, 'D':36, 'E':37, 'F':38, 'G':39,
            'H':40, 'I':41, 'J':42, 'K':43, 'L':44, 'M':45, 'N':46, 'O':47,
            'P':48, 'Q':49, 'R':50, 'S':51, 'T':52, 'U':53, 'V':54, 'W':55,
            'X':56, 'Y':57, 'Z':58, '[':59, '\\':60, ']':61, '^':62, '_':63,
            '' :64, 'a':65, 'b':66, 'c':67, 'd':68, 'e':69, 'f':70, 'g':71,
            'h':72, 'i':73, 'j':74, 'k':75, 'l':76, 'm':77, 'n':78, 'o':79,
            'p':80, 'q':81, 'r':82, 's':83, 't':84, 'u':85, 'v':86, 'w':87,
            'x':88, 'y':89, 'z':90, '{':91, '|':92, '}':93, '~':94, '\x7F':95,
            'FNC3':96, 'FNC2':97, 'SHIFT':98, 'Code C':99, 'FNC4':100, 'Code A':101, 'FNC1':102, 'START A':103,
            'START B':104, 'START C':105, 'STOP':106}

ValueEncodings ={
    0:'11011001100',  1:'11001101100',  2:'11001100110',
    3:'10010011000',  4:'10010001100',  5:'10001001100',
    6:'10011001000',  7:'10011000100',  8:'10001100100',
    9:'11001001000', 10:'11001000100', 11:'11000100100',
    12:'10110011100', 13:'10011011100', 14:'10011001110',
    15:'10111001100', 16:'10011101100', 17:'10011100110',
    18:'11001110010', 19:'11001011100', 20:'11001001110',
    21:'11011100100', 22:'11001110100', 23:'11101101110',
    24:'11101001100', 25:'11100101100', 26:'11100100110',
    27:'11101100100', 28:'11100110100', 29:'11100110010',
    30:'11011011000', 31:'11011000110', 32:'11000110110',
    33:'10100011000', 34:'10001011000', 35:'10001000110',
    36:'10110001000', 37:'10001101000', 38:'10001100010',
    39:'11010001000', 40:'11000101000', 41:'11000100010',
    42:'10110111000', 43:'10110001110', 44:'10001101110',
    45:'10111011000', 46:'10111000110', 47:'10001110110',
    48:'11101110110', 49:'11010001110', 50:'11000101110',
    51:'11011101000', 52:'11011100010', 53:'11011101110',
    54:'11101011000', 55:'11101000110', 56:'11100010110',
    57:'11101101000', 58:'11101100010', 59:'11100011010',
    60:'11101111010', 61:'11001000010', 62:'11110001010',
    63:'10100110000', 64:'10100001100', 65:'10010110000',
    66:'10010000110', 67:'10000101100', 68:'10000100110',
    69:'10110010000', 70:'10110000100', 71:'10011010000',
    72:'10011000010', 73:'10000110100', 74:'10000110010',
    75:'11000010010', 76:'11001010000', 77:'11110111010',
    78:'11000010100', 79:'10001111010', 80:'10100111100',
    81:'10010111100', 82:'10010011110', 83:'10111100100',
    84:'10011110100', 85:'10011110010', 86:'11110100100',
    87:'11110010100', 88:'11110010010', 89:'11011011110',
    90:'11011110110', 91:'11110110110', 92:'10101111000',
    93:'10100011110', 94:'10001011110', 95:'10111101000',
    96:'10111100010', 97:'11110101000', 98:'11110100010',
    99:'10111011110',100:'10111101110',101:'11101011110',
    102:'11110101110',103:'11010000100',104:'11010010000',
    105:'11010011100',106:'1100011101011'}

def makeBits(input_string):
    #start code for charsetB
    startbits = ValueEncodings[104]

    #stop code for charsetB
    stopbits = ValueEncodings[106]

    bits = ''
    checksum = 104
    place = 1
    for c in input_string:
        #get character code
        code = CharSetB[c]
        char_bits = ValueEncodings[code]
        bits = bits + char_bits
        checksum = checksum + place*code
        place = place + 1
    #checksum calculation
    checksum = checksum % 103
    checksum_bits = ValueEncodings[checksum]
    #put it all together
    bits = startbits + bits + checksum_bits + stopbits
    return bits

def makeBar(value, ext, savepath, height = 40):
  import Image, ImageFont, ImageDraw
  
  # Create a missing font file
  decodeFontFile(courB08_pil ,"courB08.pil")
  decodeFontFile(courB08_pbm ,"courB08.pbm")
  
  # Get the bar code list
  bits = makeBits(value)
  
  # Create a new image
  whitespace = 10
  textpad = 10
  im = Image.new("1",(len(bits)+whitespace+whitespace,(height)+textpad))
  
  # Load font
  font = ImageFont.load("courB08.pil")
  
  # Create drawer
  draw = ImageDraw.Draw(im)
  
  # Erase image
  draw.rectangle(((0,0),(im.size[0],im.size[1])),fill=256)
  
  # Draw text
  draw.text(((im.size[0]-font.getsize(value)[0])/2, height-2), value, font=font, fill=0)
  
  # Draw the bar codes
  for bit in range(len(bits)):
     if bits[bit] == '1':
        draw.rectangle(((bit+whitespace,0),(bit+whitespace,height-2)),fill=0)
        
  # Save the result image
  im.save(savepath)

if __name__=="__main__":
    import sys, os

##    sys.argv.append("crapola")
##    sys.argv.append(r"crapola.png")

    #print the help_text if there are any errors    
    if len(sys.argv) <> 3:
       print help_text
       sys.exit()

    value = sys.argv[1]
    outfile = sys.argv[2]

    thepath = os.path.normpath(outfile)
    ext = os.path.splitext(outfile)[1]
    #set the extension appropriately per PIL
    if ext.lower() == "jpg": ext = "jpeg"
    if ext.lower() == "tif": ext = "tiff"
    ext = ext.upper()

    makeBar(value,ext,thepath)  

  
[/code]

 6 
 on: May 01, 2010, 10:21:59 AM 
Started by webmaster - Last post by webmaster
I'm pleased to announce that the above BMP writer has found it's way into the very cool GOLLY project.  One of the contributors, Tim Hutton, needed a quick and dirty way to output BMP images without requiring the user to install the Python Image Library (PIL).

From the GOLLY WEB SITE:  (http://golly.sourceforge.net)

"Golly is an open source, cross-platform application for exploring Conway's Game of Life and other cellular automata. The primary authors are Andrew Trevorrow and Tomas Rokicki, with code contributions by Tim Hutton, Dave Greene and Jason Summers."

Right on!

 7 
 on: May 01, 2010, 10:11:57 AM 
Started by webmaster - Last post by webmaster
The following code snippet can be used to calculate the distance between two points.  It's a fairly decent algorithm using the Haversine Formula.  Enjoy!

>>>>>>>>>>>>>>>>>>>>>>>
from math import *

#Insert some coordinates here
lat1 = 39.00
lon1 = -105.00
lat2 = 40.00
lon2 = -104.00
r = 3959.00 #mean radius of earth in miles

#This is the Haversine formula.  It is widely used for this purpose.
#In reality the earth is NOT a sphere so this formula can be off
#by a bit - usually less than .3% - not bad!

lat1_r,lon1_r,lat2_r,lon2_r = map(radians,(lat1,lon1,lat2,lon2))

dlon = lon2_r - lon1_r
dlat = lat2_r - lat1_r

a = sin(dlat/2)**2 + cos(lat1_r) * cos(lat2_r) * sin(dlon/2)**2
c = 2*atan2(sqrt(a),sqrt(1-a))
d = r*c

print """
Lat1: %f   Lon2: %f
Lon1: %f   Lat2: %f
Distance: %.2f miles
""" % (lat1,lat2,lon1,lon2,d)

 8 
 on: February 15, 2010, 10:59:18 PM 
Started by webmaster - Last post by webmaster
As an exercise, I decided to see if I could create an bmp file using pure python.  I know how to write raw bytes to the disk using the very handy struct module so I figured it was just a matter of getting the image specification down.  Turns out I was right.  The BMP format (like most image formats) contains some header bytes followed by data bytes.  A decent explanation of the format can be found on the Wikipedia (check it out!).

This code generates a 200 x 200 bmp file with a random color for each pixel.  It uses a very minimal header.  The output will look something like this:


Enjoy!

Code:
#Some key imports.
#Struct is used to create the actual bytes.
#It is super handy for this type of thing.
import struct, random

#Function to write a bmp file.  It takes a dictionary (d) of
#header values and the pixel data (bytes) and writes them
#to a file.  This function is called at the bottom of the code.
def bmp_write(d,the_bytes):
    mn1 = struct.pack('<B',d['mn1'])
    mn2 = struct.pack('<B',d['mn2'])
    filesize = struct.pack('<L',d['filesize'])
    undef1 = struct.pack('<H',d['undef1'])
    undef2 = struct.pack('<H',d['undef2'])
    offset = struct.pack('<L',d['offset'])
    headerlength = struct.pack('<L',d['headerlength'])
    width = struct.pack('<L',d['width'])
    height = struct.pack('<L',d['height'])
    colorplanes = struct.pack('<H',d['colorplanes'])
    colordepth = struct.pack('<H',d['colordepth'])
    compression = struct.pack('<L',d['compression'])
    imagesize = struct.pack('<L',d['imagesize'])
    res_hor = struct.pack('<L',d['res_hor'])
    res_vert = struct.pack('<L',d['res_vert'])
    palette = struct.pack('<L',d['palette'])
    importantcolors = struct.pack('<L',d['importantcolors'])
    #create the outfile
    outfile = open('bitmap_image.bmp','wb')
    #write the header + the_bytes
    outfile.write(mn1+mn2+filesize+undef1+undef2+offset+headerlength+width+height+\
                  colorplanes+colordepth+compression+imagesize+res_hor+res_vert+\
                  palette+importantcolors+the_bytes)
    outfile.close()

###################################    
def main():
    #Here is a minimal dictionary with header values.
    #Of importance is the offset, headerlength, width,
    #height and colordepth.
    #Edit the width and height to your liking.
    #These header values are described in the bmp format spec.
    #You can find it on the internet. This is for a Windows
    #Version 3 DIB header.
    d = {
        'mn1':66,
        'mn2':77,
        'filesize':0,
        'undef1':0,
        'undef2':0,
        'offset':54,
        'headerlength':40,
        'width':200,
        'height':200,
        'colorplanes':0,
        'colordepth':24,
        'compression':0,
        'imagesize':0,
        'res_hor':0,
        'res_vert':0,
        'palette':0,
        'importantcolors':0
        }

    #Function to generate a random number between 0 and 255
    def rand_color():
        x = random.randint(0,255)
        return x

    #Build the byte array.  This code takes the height
    #and width values from the dictionary above and
    #generates the pixels row by row.  The row_mod and padding
    #stuff is necessary to ensure that the byte count for each
    #row is divisible by 4.  This is part of the specification.
    the_bytes = ''
    for row in range(d['height']-1,-1,-1):# (BMPs are L to R from the bottom L row)
        for column in range(d['width']):
            b = rand_color()
            g = rand_color()
            r = rand_color()
            pixel = struct.pack('<BBB',b,g,r)
            the_bytes = the_bytes + pixel
        row_mod = (d['width']*d['colordepth']/8) % 4
        if row_mod == 0:
            padding = 0
        else:
            padding = (4 - row_mod)
        padbytes = ''
        for i in range(padding):
            x = struct.pack('<B',0)
            padbytes = padbytes + x
        the_bytes = the_bytes + padbytes
        
    #call the bmp_write function with the
    #dictionary of header values and the
    #bytes created above.
    bmp_write(d,the_bytes)

if __name__ == '__main__':
    main()





 9 
 on: February 15, 2010, 08:12:05 PM 
Started by webmaster - Last post by webmaster
What's the point?  The webmaster will just prune those posts a short time later.  It's not like Google is going to crawl this site and see that "cheap canadian pharmaceuticals" is for sale, then up your page rank.  That's just stupid.  Give it a rest, please...

 10 
 on: February 15, 2010, 08:05:05 PM 
Started by webmaster - Last post by webmaster
Rockin', absolutely rockin!

Pages: [1] 2
Powered by MySQL Powered by PHP Powered by SMF 1.1.11 | SMF © 2006-2008, Simple Machines LLC Valid XHTML 1.0! Valid CSS!