Image to colortext(html) converter

This is a C++ snippet, talking about magick++, image and text

Image to colortext(html) converter Add to Favorite

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <Magick++.h>

using namespace Magick;
using namespace std;

class TextBlock
{
  private:
    string content;
    int pos;
  
  public: 
    TextBlock(const char *filename)
    {
      ifstream ifs(filename);
      stringstream ss;
      ss << ifs.rdbuf() << endl;
      
      this->content = ss.str();
    }
    
    char next()
    {
      if (this->pos + 1 >= this->content.length())
        this->pos = 0;
      else
        this->pos++;
      
      if (this->content[pos] == '\n' || this->content[pos] == ' ')
        return this->next();
      else
        return this->content[pos];
    }
};

string RGBToHex(int rNum, int gNum, int bNum)
{
        string result;

        char r[255];    
        sprintf(r, "%.2X", rNum);
        result.append(r );

        char g[255];    
        sprintf(g, "%.2X", gNum);
        result.append(g );

        char b[255];    
        sprintf(b, "%.2X", bNum);
        result.append(b );
        
        return result;
}

string imageToHtml(TextBlock *chars, Image *image)
{
  const PixelPacket *pixels = image->getConstPixels(0, 0, 
          image->columns(),
          image->rows());
  stringstream output;
  
  output << "<html><head>";
  output << "<link href='style.css' type='text/css' rel='stylesheet' />";
  output << "</head><body>";
             
  for (int i = 0; i < image->rows(); i++)
  {
      for (int j = 0; j < image->columns(); j++)
      {
        output << "<font color='#" << RGBToHex(pixels->red,
                                                 pixels->green,
                                                 pixels->blue)
                                     << "'>" << chars->next() 
                                     << "</font>";
        *pixels++;
      }
      
      output << "<br />\n";
  }
  output << "</body>";
  output << "</html>";
  return output.str();
}

int main(int argc, char** argv)
{
  if (argc < 3)
  {
    cout << "Usage: textpic /path/to/text-file /path/to/image-file" << endl;
    return 1;
  }
  
  TextBlock *chars = new TextBlock(argv[1]);
  Image *image = new Image(argv[2]);
  ofstream output("out.html");
  output << imageToHtml(chars, image);
  output.close();
  return 0;
}

It converts any image to colored text (html). In order to compile textimg you will need to install magick++ dev libraries.

Created by ThePeppersStudio (144 days, 17.72 hours ago)

Do you want to leave a message? Please login first.