C++ Fileoperations: read the file size and type of an image

The get_image_info() function takes a file path as input and opens the file in binary mode using the std::ios::binary flag. It then uses the tellg() method to get the file size and the seekg() method to set the read position to the beginning of the file. It then uses the cv::imread() method from the OpenCV library to read the image and get its type. If the image has 3 channels, it is assumed to be a JPEG file; otherwise, it is assumed to be a PNG file. The function then prints the file size and type. In the main() function, we call get_image_info() with the file path. Note that you need to have the OpenCV library installed to run this code.

#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <opencv2/opencv.hpp>

void get_image_info(std::string file_path) {
    std::ifstream file(file_path, std::ios::binary | std::ios::ate);
    std::streamsize size = file.tellg();
    file.seekg(0, std::ios::beg);
    std::string file_type = cv::imread(file_path, cv::IMREAD_UNCHANGED).type() == CV_8UC3 ? "JPEG" : "PNG";
    std::cout << "File size: " << size << " bytes" << std::endl;
    std::cout << "File type: " << file_type << std::endl;
}

int main() {
    get_image_info("image.jpg");
    return 0;
}