Hi Greg, Nice puzzle. I don't know whether this solution is 'efficient' by your definition, but it uses standard libraries. I understand that you just want to swap B and R in an array of bytes formatted like 'RGBARGBA'. For illustration purposes, I'll use this exact string as input data.
I have three options. I haven't checked to see which is faster, but the first two options are memory efficient as they use iterators/generators instead of lists: data='RGBARGBA' from itertools import izip, chain pixels=izip(*[iter(data)]*4) # cluster into pixels per docs of zip() new_subpixels = (subpixel for p in pixels for subpixel in (p[2],p[1],p[0],p[3])) new_data = ''.join(new_subpixels) Section option: data='RGBARGBA' from itertools import izip, chain, imap pixels=izip(*[iter(data)]*4) # cluster into pixels per docs of zip() new_pixels = imap(lambda p: (p[2],p[1],p[0],p[3]), pixels) data = ''.join(chain(*new_pixels)) Third option is a slight variation involving zipping and unzipping. It takes more memory because it has to use zip instead of izip, but for all I know it may be faster: data='RGBARGBA' from itertools import izip, chain pixels=zip(*[iter(data)]*4) # cluster into pixels per docs of zip() R,G,B,A = izip(*pixels) # unzip new_pixels = zip(B,G,R,A) # re-zip in different order data = ''.join(chain(*new_pixels)) The last step is flattening the list. Looking up 'flatten' on google will reveal any number of ways to flatten lists and some may be more efficient than this, I don't know. The commented unzip/re-zip steps may be quicker to do with map() and a lambda function, and you may also find that they are a lot. Cheers, Berwyn -- Check out our *winning design* in this Bronchoscope Simulator<http://www.orsim.co.nz/>for AirwaySkills ( TVNZ coverage<http://tvnz.co.nz/business-news/health-sector-gets-help-cracking-us-market-3286407>or radio<http://podcast.radionz.co.nz/sno/sno-20110118-1020-Inventor_-_Dr_Paul_Baker-048.mp3>). Berwyn Hoyt, *Electronic Solutions & Business* -- Brush Technology *Ph:* +64 3 741 1204 *Mobile:* +64 21 045 7830 *Web:* brush.co.nz ------------------------ Greg wrote: Can anyone think of an efficient way to convert a string full of RGBA image data to BGRA, using only what's available in the standard library? I'm trying to add a function to PyGUI for creating an Image object from arbitrary data. The problem I'm having is that GDI+ on Windows expects BGRA, whereas most other platforms deal with RGBA. I don't want to require the user to supply the data in different formats on different platforms, so PyGUI needs to be able to convert where necessary. I know the conversion can be done easily using something like PIL or numpy, but I'm after a solution that doesn't depend on any third-party libraries.
_______________________________________________ Pygui mailing list [email protected] http://mail.python.org/mailman/listinfo/pygui
