Skip to content

Instantly share code, notes, and snippets.

@mshafae
Last active December 13, 2023 23:18
Show Gist options
  • Save mshafae/c60dcd64a98e664c6d75115e7f57fe41 to your computer and use it in GitHub Desktop.
Save mshafae/c60dcd64a98e664c6d75115e7f57fe41 to your computer and use it in GitHub Desktop.
CPSC 120 Example of creating an image using GraphicsMagick and rasterizing some text into the image. Uses X11 color names instead of RGB color values.
// Gist https://gist.github.com/mshafae/c60dcd64a98e664c6d75115e7f57fe41
// Filename cpsc120_image_with_text.cc
// CompileCommand clang++ -std=c++17 -I /usr/include/GraphicsMagick -lGraphicsMagick++ cpsc120_image_with_text
// Create a simple, small image from a given
// filename. GraphicsMagick will figure out how to output to the given file
// format.
// Supported formats: http://www.graphicsmagick.org/formats.html
// Example:
// clang++ -std=c++17 -I /usr/include/GraphicsMagick -lGraphicsMagick++ cpsc120_image_with_text
// ./a.out my_image.jpg
// ./a.out my_image.png
#include <Magick++.h>
#include <cmath>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
int main(int argc, char* argv[]) {
// Set these to whatever dimensions you want the output image to be.
// Warning: don't make this too big or your program will take a long time
// to execute.
const int kImageWidth{1024};
const int kImageHeight{512};
// This initializes the image library we are using.
Magick::InitializeMagick(*argv);
std::vector<std::string> args{argv, argv + argc};
if (args.size() < 2) {
std::cout << "Please provide a path to a file.\n";
std::cout << "For example: " << args.at(0) << " my_image.jpg\n";
return 1;
}
std::string output_file_name;
output_file_name = args.at(1);
// Let's specify a color by using the X11 color name
// See https://en.wikipedia.org/wiki/X11_color_names
Magick::Color orange = Magick::Color("orange");
Magick::Image image(Magick::Geometry(kImageWidth, kImageHeight), orange);
// Let's use the font Helvetica
image.font("Helvetica");
// Let's set it's size to 1/3 the number of rows the image has
image.fontPointsize(image.rows() / 3.0);
// Let's specify a color by using the X11 color name
// See https://en.wikipedia.org/wiki/X11_color_names
image.fillColor(Magick::Color("navy"));
// A message to write in the image.
std::string message{"Go Titans!"};
// Center the text and draw it.
image.annotate(message, Magick::CenterGravity);
// Write out the image to the computer user specified file name.
image.write(output_file_name);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment