Ok, i am making an image resize algorithm. The function works perfectly so long as the desired width is divisible by 4 (so newWidth%4 == 0), but the desired height can be any number. I cant for the life of me figure out why the function would work if the number is divisible by four but not any other number. I would like the formula to work for any width.
void Image::Resize(int newWidth, int newHeight) {
// ImageData - An unsigned char* pointer to the image data
// BytesPerPixel - An unsigned char, the bytes per pixel 3, or 4
// Width - An int, the original width of the image
// Height - An int, the original height of the image
try { // Try to load the image
if(!ImageData) throw("No Image has been loaded");
unsignedchar* newData = newunsignedchar[newWidth*newHeight*BytesPerPixel];
double scaleWidth = (double)newWidth/(double)Width;
double scaleHeight = (double)newHeight/(double)Height;
int pixel = 0;
for(int cy = 0; cy < newHeight; cy++) {
for(int cx = 0; cx < newWidth; cx++) {
int nearestMatch = ((int)(cy/scaleHeight)*(Width*BytesPerPixel))
+((int)(cx/scaleWidth)*BytesPerPixel);
newData[pixel] = ImageData[nearestMatch];
newData[pixel+1] = ImageData[nearestMatch+1];
newData[pixel+2] = ImageData[nearestMatch+2];
if(BytesPerPixel == 4) newData[pixel+3] = ImageData[nearestMatch+3];
pixel += BytesPerPixel;
}
}
delete ImageData;
ImageData = newData;
Width = newWidth;
Height = newHeight;
} catch(constchar* Error) { // If we encountered an error
MessageBox(NULL,Error,"Error", // Send a popup box with the error
MB_OK|MB_ICONEXCLAMATION);
return; // The image was not loaded
}
}
The link below shows the same image resized, the first image (321x240) does not have a width divisible by 4, so it screws up, but the second (324x240) does, so it works. http://nanobytes.comli.com/HTML/image-resize.html
Could one of you guys help me fix this so it will work with all dimensions