Reputation: 14800
How can I calculate in C# the exact resolution based on megapixels?
Let's say I have a 5000x4000 pixels image and I want to rescale to 0.6mpx, how can I get the exact horizontal and vertical resolution to get an image of 0.6mpx keeping the original aspect ratio?
I have this:
int nXPixels=5000; // original image Width
int nYPixels=4000; // original image Height
float fRatio=5000/4000; // original image aspect ratio
int nNewPixelResolution=600000; // 0.6mpx new resolution
int nNewXPixels=?
int nNewYPixels=?
Upvotes: 0
Views: 919
Reputation: 3523
int nXPixels=5000; // original image Width
int nYPixels=4000; // original image Height
//float fRatio=5000/4000; // original image aspect ratio
int nNewPixelResolution=600000; // 0.6mpx new resolution
int nOldPixelResolution=nXPixels*nYPixels;
double conv = Math.sqrt((double)nNewPixelResolution/(double)nOldPixelResolution);
int nNewXPixels= (int)Math.round(nXPixels*conv);
int nNewYPixels= (int)Math.round(nYPixels*conv);
Upvotes: 2
Reputation: 633
Amount of megapixels is equal to the product of the length and width of the resolution, divided by 1 million. So for your 5000x4000 pixels, you would have 20 Mpx. To rescale it to 0.6Mpx, but keeping the ratio, you would just need to rescale each dimension by the squareroot of 20Mpx/0.6Mpx, so that, when the newly computed dimensions will be multiplied, the result would be equal to 0.6Mpx
So your computation should be similar to :
ratio=sqrt(20/0.6)
newWidth=oldWidth/ratio
newHeight=oldHeight/ratio
If you then multiply newWidth
with newHeight
, the result should be aproximately 0.6Mpx, or 600000 px
Upvotes: 3