some thoughts on ofImage

A bunch of different things I thought I’d throw in one place.

* It’d be nice to have swapRgb() exposed. I have some images that are being loaded as BGR and displaying funny. Though maybe this is just a display issue, and could be optimally solved by making use of GL_BGR?

* Both operator=(const ofImage&) and ofImage(const ofImage& mom) have these two lines of code:


But clone(const ofImage &) itself finishes:


Which means that update() is unnecessarily being called multiple times.

* A get(x, y, w, h) or even ofImage(mom, x, y, w, h) would be nice. Like Processing’s PImage.get() On the other hand, if all that’s needed is drawing a subset of an ofImage, and not actually creating a new one (this is my situation), this could probably done well just using GL.

Here’s an implementation of the get() suggestion, with a reasonably optimized copy loop:

void get(const ofImage& mom, unsigned int x, unsigned int y, unsigned int w, unsigned int h);  

void ofImage::get(const ofImage& mom, unsigned int x, unsigned int y, unsigned int w, unsigned int h) {  
	myPixels.bAllocated = false;  
	if (!bFreeImageInited){  
		bFreeImageInited = true;  
	allocatePixels(myPixels, w, h, mom.bpp);  
	unsigned int bytesPerPixel, bytesPerRow;  
	bytesPerPixel = mom.myPixels.bytesPerPixel;  
	bytesPerRow = w * bytesPerPixel;  
	unsigned int fromStart, fromOffset, toStart, toOffset;  
	fromStart = (y * mom.width + x) * bytesPerPixel;  
	fromOffset = mom.width * bytesPerPixel;  
	toStart = 0;  
	toOffset = w * bytesPerPixel;  
	for(unsigned int i = 0; i < h; i++) {  
		memcpy(&myPixels.pixels[toStart], &mom.myPixels.pixels[fromStart], bytesPerRow);  
		fromStart += fromOffset;  
		toStart += toOffset;  
	bUseTexture = mom.bUseTexture;  
	if (bUseTexture)  
		tex.allocate(myPixels.width, myPixels.height, myPixels.glDataType);  

Regarding swapRgb again, there’s a note in ofImage:

// RGB or RGBA swap  
// this can be done with some ill pointer math.  
// anyone game?  

I have one optimization suggestion, which is to get rid of the multiplies by changing cnt++ to cnt += byteCount:

temp = pix.pixels[cnt];  
pix.pixels[cnt] = pix.pixels[cnt + 2];  
pix.pixels[cnt + 2] = temp;  
cnt += byteCount;  

Is there really anything faster than this…? Whoever wrote “ill pointer math” – what did you have in mind? Maybe maintaining two pointers, one offset, and incrementing both the same distance?

Just curious :slight_smile: