Skip to content

KaraniAbdellah/Image2ASCII

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

15 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Image to ASCII Converter Using stb_image Library

Images

tom

simpson

Introduction

This project uses the stb_image library to load and save images in C. The goal is to convert images into ASCII art.

Steps

1. Loading an Image

The goal is to load the image from disk into memory.

How to load an image:

unsigned char *stbi_load(char *img_path, int *width, int *height, int *channels, 0);
  • img_path: The path to the image file.
  • width, height: The dimensions of the image.
  • channels: The number of pixel values (RGB or RGBA).
  • 0: Load only RGB, ignoring the alpha channel.

2. Looping Through Image Data

The goal is to convert each pixel in the image to ASCII code.

Each pixel in the image contains three values (RGB).
The image pixels look like this: [R, G, B][R, G, B]...

Calculate pixel index:

index = (y * width + x) * channels;
  • y * width: The total number of pixels in all rows.
  • + x: The current pixel position in the row.
  • * channels: Find the exact byte position.

Get the channel values:

The channels read the red, green, and blue values of each pixel.


int red = img[index_pixel]; 
int green = img[index_pixel + 1]; 
int blue = img[index_pixel + 2];

Convert each pixel to ASCII code:

Each image has brightness, which indicates how light or dark it appears. We need to get the brightness for each pixel and determine which ASCII character we can choose for that pixel.

int brightness = (red + green + blue) / 3;
for (int k = 0; k < density_size; k++) {
    if (brightness < (256 * (k + 1) / density_size)) {
        char asciiChar = density[k];
        printf("%c", asciiChar); 
        usleep(1000);
        break;
    }
}
  • density: An array that contains ASCII characters.
  • It checks if the brightness is less than a calculated value based on the density size.
  • If the condition is true, it gets the corresponding ASCII character and prints it.
  • usleep(1000); pauses for 1 millisecond before the next character is printed.

3. Saving an Image

We can save the image after editing each pixel to see the image in ASCII code.

How to save an image:

stbi_write_png("path_to_save", width, height, channels, img, width * channels);
  • width: The total number of values in one row of the image.
  • channels: The number of values per pixel (3 for RGB, 4 for RGBA).
  • height: The number of rows in the image.

4. Summary

  • Load the image.
  • Loop through the image data.
  • Save the new version.

5. Compiling the Code

Use this command to compile:

gcc main.c -o main -lm && ./main

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors