2013
10.31

Couldn’t find any good examples of directly writing to the QImage bits without using numpy, so here’s a simple example 🙂 (PyQt)

This just accesses the image bits uchar* directly, and uses struct.pack to convert the qRgb values into bytes for the uchar * (via sip.voidptr)

</span>
<pre>import struct
from PyQt4 import QtGui

#initialize the QImage
img = QtGui.QImage(512, 512, QtGui.QImage.Format_RGB32)
#Build the color object up front, new QColor every pixel is SLOW!
color = QtGui.QColor()

#Initialize the sip uchar ptr
ucharptr = img.bits()
ucharptr.setsize(img.byteCount())

i = 0
w = float(img.width())
h = float(img.height())
halfw = w/2

for y in range(img.height()):
	for x in range(img.width()):
		hue = (y/h)*360
		if x<halfw:
			sat = (x/halfw)*255
			val = 255
		else:
			sat = 255
			val = 255 - (((x-halfw)/halfw)*255)

		#Set the color values as HSV, then convert to qRgb
		color.setHsv(hue, sat, val)

		#Pack the qRgb into bytes using struct
		#Each pixel is 4 bytes, write the slice
		ucharptr[i:i+4] = struct.pack('I', color.rgb())
		i+=4

img.save('c:/out.png')

Result should look like Maya’s spectrum color picker

(And yes, QImage.setPixel does work as an alternative, but speed is worse, and even the QImage documentation recommends avoiding it)

You must be logged in to post a comment.