This is my code
from PIL import Image
ASCII_CHARS = ["@", "#", "$", " ", " ", "-", "|", ":", ".", " ", " ", " " ]
def resize_image(image, new_width=50):
width, height = image.size
ratio = height/width
new_height = int(new_width * ratio)
resized_image = image.resize((new_width, new_height))
#resized_image.save('output.png')
return(resized_image)
def grayify(image):
grayscale_image = image.convert("L")
#grayscale_image.save('output.png')
return(grayscale_image)
# convert pixels to a string of ascii characters
def pixels_to_ascii(image):
pixels = image.getdata()
characters = ''.join([ASCII_CHARS[pixel//25] for pixel in pixels])
return(characters)
def main(new_width=50):
# attempt to open image from user-input
#path = input("Enter a valid pathname to an image:\n")
try:
image = Image.open("picachu.jpg")
except:
print(path, " is not a valid pathname to an image.")
return
# convert image to ascii
new_image_data = pixels_to_ascii(grayify(resize_image(image)))
# format
pixel_count = len(new_image_data)
ascii_image = '\n'.join([new_image_data[index:(index+new_width)] for index in range(0, pixel_count, new_width)])
with open("full_image.txt", "w") as f:
f.write(ascii_image)
fa = open("full_image.txt", "r")
fb = open("trimmed_image.txt", "w")
lines = fa.readlines()
fa.close()
lines = filter(lambda x: not x.isspace(), lines)
fb.write("".join(lines))
fb.close()
main()
and for picachu.jpg output is like this:
|-
$
|#$
##.
.: | #.
:## : ..:$.
|### .. ...|.
|## ..::. :...
:#$....:: :..:
. |.....:. :..:
:|::...:. ...:
:|::..::::.:::. ...:
.:|:..........:....::
::...........::.:.
:.............:.|
...:............::
.. -:...........:.
..$$ ............
.|.| |.......|:-..
- ......::... $.:
. :..:- -...-#-.:
: :... $ -......
. -....--- $-....:: ..::
|:....||||-:...| -:....:
......|||-:...: |.....:
:....|--|....| :....::
.::::::..||.....| |....:::::::...
:.......::.......:|....::..........::..
..........::.....::....:|:..............:.
:.........:|::........:|:.:...............
..........|:.........:| ..:::............
:::::::||:.........|| ..||||:.........
:|||||:..........:| ::|||||::.....:
:::.............| ::||::|||::..:
................: .::|. .:|::
:................ |::.:|
.................: :|:.|.
.................: :||:|
:..................: -
:.................- $-
...................: -
:....................
:....................
:..........::::::...:
.::::::::::||||||::..
||||||||||-||||||||.
:::|||. ..::|-|::|.
.-|:::. ...::-:
.. ..
So there is no problem with the code! But the thing is that i want to use Braille alphabet "⡿⡾⡹⡲⡱⠶⠷⠸" instead of "@#|- etc" and when i try :
ASCII_CHARS = ["\u280F", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " "]
it gives me this error UnicodeEncodeError: 'charmap' codec can't encode character '\u280f' in position 317: character maps to <undefined>
anyone have ideas how to solve this issue? you can find other Braille characters Unicode and Decimalcode here