Converting to ARGB and writing to a bitmap

heathimself at gmail.com heathimself at gmail.com
Thu Mar 16 19:23:48 EST 2006


Hi,
I don't know what type of files they are, but the script allows me to
save to a bitmap just fine. But I do know they need to be in RGBA 4444
format, so I've followed what most of the tutorials for RGBA
conversions said to do...shifting the bytes.

The major problem is that everything is in green, it's shifted up by x
pixels, and it's..um..flipped from left to right. I've been working on
this for a few weeks now and any insight to the problem is greatly
appreciated.

http://www.geocities.com/fisherdude_99/TestImg.zip


import struct
import sys
import Image


if len(sys.argv) < 3:
   print "usage: tobmp.py <file> <width>"
   sys.exit(1)

width = int(sys.argv[2])

f1 = open(sys.argv[1], "rb")
f1.seek(0, 2)
size = f1.tell()
f1.seek(0)

### write BITMAPFILEHEADER ###
f2 = open(sys.argv[1] + ".bmp", "wb")
f2.write("BM")

bfSize = size+54
f2.write(struct.pack("L", bfSize))

# bfReserved1 and 2
f2.write("\x00\x00\x00\x00")

bfOffBits = 54
f2.write(struct.pack("L", bfOffBits))

### write BITMAPINFOHEADER ###
biSize = 40
f2.write(struct.pack("L", biSize))

biWidth = width
f2.write(struct.pack("L", biWidth))

biHeight = (size/ 2/ width)
f2.write(struct.pack("L", biHeight))

biPlanes = 1
f2.write(struct.pack("H", biPlanes))

biBitCount = 32
f2.write(struct.pack("H", biBitCount))

# biCompression
f2.write("\x00\x00\x00\x00")

# biSizeImage
f2.write("\x00\x00\x00\x00")

# biXPelsPerMeter
f2.write("\x00\x00\x00\x00")

# biYPelsPerMeter
f2.write("\x00\x00\x00\x00")

# biClrUsed
f2.write("\x00\x00\x00\x00")

# biClrImportant
f2.write("\x00\x00\x00\x00")

### write the bitmap data ###
print f2.tell() ##must be 54

# since bitmaps are upside down, gotta flip it over
data = f2.read()

i = size-21
while i >= 0:
    nm = 0x100

    f1.seek(i)
    temp1 = struct.unpack('B', f1.read(1))[0]

    peek = temp1

    a = nm*(peek >> 24) & 0xff
    r = nm*(peek >> 16) & 0xff
    g = nm*(peek >> 8 ) & 0xff
    b = nm*(peek & 0xff)

    sh = (a<<24)|(r<<16)|(g<<8)|b

    f2.write(struct.pack('H', sh))
    i -= 1

f1.close()
f2.close()


Usage: bmpcon.py testimg 100

Thanks a lot




More information about the Python-list mailing list