Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import sys
- from PyQt4 import QtGui
- def main(*args, **kwargs):
- return readTga(*args, **kwargs)
- def readTga(file, asPixmap=True):
- 'Given the path to a TGA file, return either a QImage or QPixmap if asPixmap is True'
- with open(file, 'rb') as f:
- header = f.read(12)
- imageSpec = f.read(6)
- header = [ord(c) for c in header]
- imageSpec = [ord(c) for c in imageSpec]
- width = imageSpec[1]*256+imageSpec[0]
- height = imageSpec[3]*256+imageSpec[2]
- bitDepth = imageSpec[4]
- bytesPerPixel = bitDepth/8
- descriptor =imageSpec[5]
- bits = []
- for i in xrange(8):
- bits.append((descriptor >> i) & 1)
- bottomUp = bool(not bits[5])
- rightToLeft = bool(bits[4])
- #print 'Read tga - Image info:'
- #print '- (width, height, bitDepth, bytesPerPixel)', width, height, bitDepth, bytesPerPixel
- image = QtGui.QImage(width, height, QtGui.QImage.Format_ARGB32)
- if header[2] == 2:
- #print '- True color, uncompressed'
- for y in range(height):
- for x in range(width):
- color = getPixel(f, bytesPerPixel)
- pX = x
- pY = y
- if rightToLeft:
- pX = (width-1)-x
- if bottomUp:
- pY = (height-1)-y
- image.setPixel(pX, pY, color)
- if header[2] == 10:
- #print '- True color, rle compressed'
- y=0
- x=0
- while y<height:
- while x<width:
- #rle chunk
- pack = ord(f.read(1))
- #if pack is less than 127, indicates how many normal pixels until the next rle pack value
- #if pack is more than 127, the distance from 127 is how many times to repeat the same pixel
- if pack>127:
- length = pack-127
- color = getPixel(f, bytesPerPixel)
- else:
- length = pack + 1
- for i in range(length): #set the chunk pixels
- if pack<=127:
- color = getPixel(f, bytesPerPixel)
- pX = x
- pY = y
- if rightToLeft:
- pX = (width-1)-x
- if bottomUp:
- pY = (height-1)-y
- image.setPixel(pX, pY, color)
- x+=1
- x=0
- y+=1
- else:
- raise Exception, 'Header value %s is not supported by loadTga.'%header[2]
- if asPixmap:
- image = QtGui.QPixmap().fromImage(image)
- return image
- def getPixel(f, bytesPerPixel):
- 'Given the file object f, and number of bytes per pixel, read in the next pixel and return a qRgba uint'
- pixel = []
- for i in range(bytesPerPixel):
- pixel.append(ord(f.read(1)))
- if bytesPerPixel==4:
- pixel = [pixel[2], pixel[1], pixel[0], pixel[3]]
- color = QtGui.qRgba(*pixel)
- else:
- pixel = [pixel[2], pixel[1], pixel[0]]
- color = QtGui.qRgb(*pixel)
- return color
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement