From 5c06eff4b50109012842ce408cf0ed846760ed88 Mon Sep 17 00:00:00 2001 From: mattmcw Date: Fri, 3 Feb 2023 23:10:50 -0500 Subject: [PATCH] Check image type using a C++ 11 compatible method --- example.cpp | 44 ++++++++++++++++++++++++++++++-------------- 1 file changed, 30 insertions(+), 14 deletions(-) diff --git a/example.cpp b/example.cpp index d5325f5..879f2bd 100644 --- a/example.cpp +++ b/example.cpp @@ -1,29 +1,38 @@ #include #include #include -#include // C++17 +#include +#include +#include namespace fs = std::filesystem; using namespace std; using namespace cv; -string supportedExt[10] = { - ".jpg", ".JPG", - ".jpeg", ".JPEG", - ".png", ".PNG", - ".tif", ".TIF", - ".tiff", ".tiff" +std::vector supportedExt = { + "jpg", "JPG", + "jpeg", "JPEG", + "png", "PNG", + "tif", "TIF", + "tiff", "tiff" }; -inline bool file_exists (const std::string& name) { - struct stat buffer; - return (stat (name.c_str(), &buffer) == 0); +inline bool in_array(const std::string &value, const std::vector &array) +{ + return std::find(array.begin(), array.end(), value) != array.end(); } -inline bool is_image (const std::string& name) { - fs::path filePath = name; - if (filePath.extension() == ".jpg") +inline bool file_exists (const std::string& name) +{ + struct stat buffer; + return (stat (name.c_str(), &buffer) == 0); +} + +inline bool is_image (const std::string& name) +{ + string ext = name.substr(name.find_last_of(".") + 1); + return in_array(ext, supportedExt); } int main(int argc, char** argv) @@ -40,11 +49,18 @@ int main(int argc, char** argv) return -2; } - if (!file_exists(input)) { + if (!file_exists(input)) + { cerr << "File " << input << " does not exist." << endl; return -3; } + if (!is_image(input)) + { + cerr << "File " << input << " is not a valid image." << endl; + return -4; + } + cout << "Using image " << input << "." << endl; return 0;