code nudge with cropping an ofImage

Hi, I’ve been wrestling with 'of a bit- it’s fun (and stresses my limited knowledge of C++…). I’ve build a few simple things. I got stuck today on something really basic: I want to display a section of another image.

I based my code (below) off the ‘image processing’ example in the wiki (along with trying out some other example code I found on this forum + the web). I’m screwing up the byte order or something since the resulting image is distorted. After poking the code a while I figured I would just ask for a nudge.

Image is scaled down. I was trying to copy a rect(0,0, 300, 200) from the image on the left into the image on the right.

tx!

  
  
void testApp::cropper(ofImage* im){  
   
	int bytes_per_pixel = im->bpp / 8;  
	if (im->type != OF_IMAGE_COLOR || bytes_per_pixel != 3)  
		return;  
   
	int w = 300;  
	int h = 200;  
	  
 	cropped.allocate(w, h, OF_IMAGE_COLOR);  
	  
	unsigned char * im_pixels = im->getPixels();  
 	unsigned char * pixels = new unsigned char[w*h*bytes_per_pixel];  
	  
	for (int i = 0; i < w*h; i++) {  
		int base = i * bytes_per_pixel;  
   
		pixels[base + 0] = im_pixels[base + 0];  
		pixels[base + 1] = im_pixels[base + 1];  
		pixels[base + 2] = im_pixels[base + 2];  
	}  
	  
	cropped.setFromPixels(pixels, w, h,  OF_IMAGE_COLOR);  
	delete [] pixels;   
}  

Sorted it out after looking through some forum code… My faulty understanding of the array offset part when referencing different size images.

This returns an ofImage based on a selection from a larger image.

  
  
ofImage testApp::crop(ofImage* sImg, int x, int y, int w, int h){  
  
	int sW = sImg->getWidth();  
	int sH = sImg->getHeight();  
  
	ofImage tmpImg;  
 	tmpImg.allocate(w, h, OF_IMAGE_COLOR);  
	   
	unsigned char subRegion[ w * h * 3  ];   
	unsigned char * srcPixels = sImg->getPixels();  
		  
	for (int i = 0; i < w; i++){  
		for (int j = 0; j < h; j++){  
			int mainPixelPos = ((j + y) * sW + (i + x)) * 3;  
			int subPixlPos = (j * w + i) * 3;  
			  
			subRegion[subPixlPos] = srcPixels[mainPixelPos];   // R  
			subRegion[subPixlPos + 1] = srcPixels[mainPixelPos + 1];  // G  
			subRegion[subPixlPos + 2] = srcPixels[mainPixelPos + 2];  // B  
		}  
	}  
	  
	tmpImg.setFromPixels(subRegion, w, h,  OF_IMAGE_COLOR);  
	return tmpImg;  
}