How to find the resolution of an image in C++

We have a collection of images of different resolutions. So today we are going to find the resolution of a particular image using C++.

Resolution of an image in C++

Resolution is image quality produced by display or printer. It is also measured by pixels. Example is 1680X1050 resolution etc. Resolution is a deciding factor for image size. We can improve the image quality of an image by increasing it resolution. There are various processing of checking the resolution of an image. And by one of the methods using C++, we can find the resolution of an image by using our code.


#include <iostream>
#include <fstream>

using namespace std;

bool GetImageSize(const char *fn, int *x,int *y)
    FILE *f=fopen(fn,"rb");
    if (f==0) return false;
    long len=ftell(f);
    if (len<24) {
        return false;
    cout << fn << endl;

  unsigned char buf[24]; fread(buf,1,24,f);

  if (buf[0]==0xFF && buf[1]==0xD8 && buf[2]==0xFF && buf[3]==0xE0 && buf[6]=='J' && buf[7]=='F' && buf[8]=='I' && buf[9]=='F')
  { long pos=2;
    while (buf[2]==0xFF)
    { if (buf[3]==0xC0 || buf[3]==0xC1 || buf[3]==0xC2 || buf[3]==0xC3 || buf[3]==0xC9 || buf[3]==0xCA || buf[3]==0xCB) break;
      pos += 2+(buf[4]<<8)+buf[5];
      if (pos+12>len) break;
      fseek(f,pos,SEEK_SET); fread(buf+2,1,12,f);


  if (buf[0]==0xFF && buf[1]==0xD8 && buf[2]==0xFF)
  { *y = (buf[7]<<8) + buf[8];
    *x = (buf[9]<<8) + buf[10];
    return true;

  if (buf[0]=='G' && buf[1]=='I' && buf[2]=='F')
  { *x = buf[6] + (buf[7]<<8);
    *y = buf[8] + (buf[9]<<8);
    return true;

  if ( buf[0]==0x89 && buf[1]=='P'&&buf[2]=='N'&& buf[3]=='G'&&buf[4]==0x0D&&buf[5]==0x0A&&buf[6]==0x1A&&buf[7]==0x0A&&buf[12]=='I'&&buf[13]=='H'&&buf[14]=='D'&& buf[15]=='R')
  { *x = (buf[16]<<24) + (buf[17]<<16) + (buf[18]<<8) + (buf[19]<<0);
    *y = (buf[20]<<24) + (buf[21]<<16) + (buf[22]<<8) + (buf[23]<<0);
    return true;

  return false;

int main()

const char *theFile = "11.png";
int the_x =0;
int the_y =0;
bool didRun = false;

didRun = GetImageSize(theFile, &the_x, &the_y);

  cout << "resolution: " << the_x << " x " << the_y << endl;
    return 0;



resolution: 143 x 120

In this output first, we get the image i.e. 11.png. And then we are going to get the resolution of an image.

Also read: Generate RGBA Portable Graphic Image in C++

Leave a Reply

Your email address will not be published. Required fields are marked *