Code:
#include <SFML\Graphics.hpp>
#include <iostream>
#include <fstream>
class Converter
{
public:
Converter(int width, bool reverse) :width(width), reverse(reverse)
{
}
char valueToChar(float value)
{
if (value == 1.0)
return ' ';
else if (value > 0.9)
return '.';
else if (value > 0.8)
return ',';
else if (value > 0.7)
return 'x';
else if (value > 0.6)
return '+';
else if (value > 0.5)
return 'o';
else if (value > 0.4)
return 'O';
else if (value > 0.3)
return '0';
else if (value > 0.2)
return '9';
else if (value > 0.1)
return '8';
return 'X';
}
bool isValid(sf::Vector2u size, sf::Vector2u pos)
{
if (pos.x < size.x && pos.y < size.y && pos.x >= 0 && pos.y >= 0)
return true;
else
return false;
}
float lookUpPixel(const sf::Uint8*pixels, sf::Vector2u size,sf::Vector2u pos)
{
const sf::Uint8*pixel = pixels + ((size.x*int(pos.y) + int(pos.x)))*4;
float value = pixel[0] + pixel[1] + pixel[2];
return value / (255.0f*3.0f);
}
std::string convert(std::string filename)
{
sf::Image image;
image.loadFromFile(filename);
const sf::Uint8*pixels = image.getPixelsPtr();
std::string result;
int height = width*(float(image.getSize().y)/image.getSize().x)*0.5f;
float modx = float(image.getSize().x)/ width;
float mody = float(image.getSize().y)/ height;
for (unsigned int y = 0; y < height; y ++)
{
for (unsigned int x = 0; x < width; x++)
{
sf::Vector2u pos;
pos.x = unsigned int(x*modx);
pos.y = unsigned int(y*mody);
if (isValid(image.getSize(), pos))
{
float value = lookUpPixel(pixels, image.getSize(), pos);
if (reverse)
value = 1.0f - value;
result += valueToChar(value);
}
}
result += "\n";
}
result += "END";
return result;
}
private:
int width;
bool reverse;
};
void saveToFile(std::string data)
{
std::fstream file;
file.open("result.txt", std::ios::out|std::ios::trunc);
file << data;
file.close();
}
int main()
{
std::cout << "Width: ";
int size;
std::cin >> size;
std::cout << std::endl;
Converter converter(size, false);
std::cout << "File name: ";
std::string name;
std::cin >> name;
std::cout << std::endl;
saveToFile(converter.convert(name));
std::cout << "DONE" << std::endl;
}