Convert an image into ASCII Art using C++ & SFML | Beginner Friendly

Ashar Ahmed
2 min readJan 22, 2023

--

Introduction:

In this article I will share my method of converting an image into ASCII Character Art, using c++ and SFML. For the sake of this article, we won't be using OpenCV, Because not everyone is familiar with image processing, and its concepts aren't quite easy for a beginner to grasp, and of course, it's not that easy to install and set up. So, I tried to find a lightweight library called SFML (Simple and Fast Multimedia Library).

Requirements:

Conversion Principle / Algorithm:

  • Take a pixel of the image ( which I have done using the SFML library)
  • Get the RGB Value of that pixel
  • Calculate its grayscale value
  • Associate the pixel with an ASCII character according to its grayscale value.
  • Print the final ASCII Art

It's alright if you don't understand some of this stuff, these concepts are quite complex for a beginner to understand, just skip to the next section where I’ve shared the code.

If you followed the tutorial mentioned above to configure codeblocks & SFML, you just need to paste the following code into main.cpp and you should be good to go.

Code:

#include <iostream>
#include <SFML/Graphics.hpp>

using namespace sf;
using namespace std;

void img_to_ascii(int intense);

int main()

{
cout << "dGhpcyBtZiBzdG9sZSBteSBjb2Rl";
Image i;
//image name
if(i.loadFromFile("lmao.jpg")) {
cout << "Success";
} else {
cout << "Error: couldn't load image";
}
//dGhpcyBtZiBzdG9sZSBteSBjb2Rl
Vector2u imageSize = i.getSize();
int xSize = imageSize.x;
int ySize = imageSize.y;
Color tempColor;
int grayScale = 0;
int intense = 0;
//ascii characters to represent intensity of grey
// .'` including space
for(int i1 = 0; i1 < ySize ; i1++) {
for(int j = 0; j < xSize; j++) {
tempColor = i.getPixel(j, i1);
grayScale = (tempColor.r * 0.2126 + tempColor.g * 0.7152 + tempColor.b * 0.0722);
intense = grayScale % 4; //4 levels of grey
img_to_ascii(intense);
}
cout << endl;
}
return 0;
}
//printing the actual ascii art dGhpcyBtZiBzdG9sZSBteSBjb2Rl
void img_to_ascii(int intense) {

if(intense==0){
cout << " ";
}
else if(intense==1){
cout << ".";
}
else if(intense==2){
cout << "'";
}
else if(intense==3){
cout << "`";
}
}

Summary:

Welp, we have reached the end of this article! This article went over explaining the most basic method to convert a simple jpg/png image into ASCII Character Art then dove into steps you can take to create your very own converter. I hope this article helped. It was quite short and it did not reach on or touch on everything I wanted to touch on however possibly this may be a future series!

~ theAce OUT!

--

--

Ashar Ahmed

Professional investigator of nerdy stuff. Hacks and secures.