Search code examples
c++cmakeimagemagick

How to add ImageMagick/Magick++ to my c++ project with CMake?


I am new to CMake. I was trying to use ImageMagick's c++ api Magick++ in my code.

This is my whole directory structure:

enter image description here

external/image_magick just contains the result of cloning the image magick library using: git submodule add https://github.com/ImageMagick/ImageMagick.git external/image_magick.

This is the top-level CMakeLists.txt ( the one in the pic above):

cmake_minimum_required (VERSION 3.22.1)
project(DEMO)
add_executable(${PROJECT_NAME} main.cpp)

This is main.cpp (it just crops the image magick image and saves it, just for the demo):

#include <iostream>

#include <Magick++.h>

using namespace std;

using namespace Magick;

int main()
{
    cout << "Hello World!" << endl;

    // Construct the image object. Seperating image construction from the
    // the read operation ensures that a failure to read the image file
    // doesn't render the image object useless.
    Image image;
    try
    {
        // Read a file into image object
        image.read("logo:");

        // Crop the image to specified size (width, height, xOffset, yOffset)
        image.crop(Geometry(100, 100, 100, 100));

        // Write the image to a file
        image.write("logo.png");
        printf("Image written to logo.png");
    }
    catch (Exception &error_)
    {
        cout << "Caught exception: " << error_.what() << endl;
        printf("Error: %s", error_.what());
        return 1;
    }

    return 0;
}

If I compile and run the app like this (as per image magick docs):

c++ main.cpp -o main.out `Magick++-config --cppflags --cxxflags --ldflags --libs`
./main.out

Then all is good and image is generated.

But I can't use the CMakeLists.txt to build and run like this:

cmake -S . -B out/build
cd out/build; make
cd out/build
./DEMO

Because the external/image_magick directory I cloned does not contain CMakeLists.txt. I tried searching inside that directory for the library file (something like libmagic++??) to use it like below in my top level CMakeLists.txt but I didn't know how to do it:

add_subdirectory(external/image_magick/Magick++)

target_include_directories(${PROJECT_NAME} 
    PUBLIC external/image_magick/
)
target_link_directories(${PROJECT_NAME} 
PRIVATE external/image_magick/Magick++
)
target_link_libraries(${PROJECT_NAME} 
    PUBLIC ${PROJECT_SOURCE_DIR}/Magick++
)
# DOES NOT WORK

So how to properly add this library to my app while keeping using CMAke?


Solution

  • According to this answer, the solution was to add the following to CMakeLists.txt:

    #ImageMagick
    add_definitions( -DMAGICKCORE_QUANTUM_DEPTH=16 )
    add_definitions( -DMAGICKCORE_HDRI_ENABLE=0 )
    find_package(ImageMagick COMPONENTS Magick++)
    include_directories(${ImageMagick_INCLUDE_DIRS})
    target_link_libraries(demo ${ImageMagick_LIBRARIES})