Farhood ET
Farhood ET

Reputation: 1541

How to create an image from a string?

I'm trying to create an image file from a string, but so far I have not had any luck. Using ImageDraw I can print a string on an image file, but this is not what I intend to do. I want to generate just a simple image file from a set of characters.

Edit: Imagine a hypothetical case of creating an ASCII art text of a pic, but instead of creating an output of a text file, generate an image file. My code consists of multiple loops and using Matplotlib will affect my code's performance.

Upvotes: 1

Views: 2405

Answers (2)

kalehmann
kalehmann

Reputation: 5011

You can use the PIL.Image.frombytes method

import PIL

my_string = b'\xf8\xff\xb0\xbc\xd8]\xba\xdf0\xbd\xdeE\xfb\xff\xd1\xf1\xff\xbf\xb4\xd9p\xad\xd9F\xae\xd7U\xf2\xff\xd6\xdf\xff\xdc\xde\xff\xd2m\xa8L\xe0\xff\xc5\xe0\xff\xe1F\x9a\\I\x9e]E\x9bTD\x9aSK\x9fa1\xadO,\xa7L3\xaeT/\xa9R.\xa8Q'
img = Image.frombytes("RGB", (5,5), my_string)
img.show()

Note, that the length of your string must equals the number of bytes used for a pixel multiplied by the width and height of the image.

In my case my_string holds an RGB image, that makes 3 bytes per pixel and the image is 5 pixels width and 5 pixel high.

Therefore my_string should have a length of 75 bytes (3 * 5 * 5)

Upvotes: 0

Magellan88
Magellan88

Reputation: 2573

you could try matplotlib:

import matplotlib.pyplot as plt
plt.text(0,0,mystring)
plt.savefig("mysentence.png", dpi=100)

Upvotes: 2

Related Questions