How to convert a string to an image?

2024/11/19 3:21:56

I started to learn python a week ago and want to write a small program that converts a email to a image (.png) so that it can be shared on forums without risking to get lots of spam mails.

It seems like the python standard library doesn't contain a module that can do that but I've found out that there's a PIL module for it (PIL.ImageDraw).

My problem is that I can't seem to get it working.

So basically my questions are:

  1. How to draw a text onto a image.
  2. How to create a blank (white) image
  3. Is there a way to do this without actually creating a file so that I can show it in a GUI before saving it?

Current Code:

import Image
import ImageDraw
import ImageFontdef getSize(txt, font):testImg = Image.new('RGB', (1, 1))testDraw = ImageDraw.Draw(testImg)return testDraw.textsize(txt, font)if __name__ == '__main__':fontname = "Arial.ttf"fontsize = 11   text = "[email protected]"colorText = "black"colorOutline = "red"colorBackground = "white"font = ImageFont.truetype(fontname, fontsize)width, height = getSize(text, font)img = Image.new('RGB', (width+4, height+4), colorBackground)d = ImageDraw.Draw(img)d.text((2, height/2), text, fill=colorText, font=font)d.rectangle((0, 0, width+3, height+3), outline=colorOutline)img.save("D:/image.png")
Answer
  1. use ImageDraw.text - but it doesn't do any formating, it just prints string at the given location

    img = Image.new('RGB', (200, 100))
    d = ImageDraw.Draw(img)
    d.text((20, 20), 'Hello', fill=(255, 0, 0))
    

    to find out the text size:

    text_width, text_height = d.textsize('Hello')
    
  2. When creating image, add an aditional argument with the required color (white):

    img = Image.new('RGB', (200, 100), (255, 255, 255))
    
  3. until you save the image with Image.save method, there would be no file. Then it's only a matter of a proper transformation to put it into your GUI's format for display. This can be done by encoding the image into an in-memory image file:

    import cStringIO
    s = cStringIO.StringIO()
    img.save(s, 'png')
    in_memory_file = s.getvalue()
    

    or if you use python3:

    import io
    s = io.BytesIO()
    img.save(s, 'png')
    in_memory_file = s.getvalue()
    

    this can be then send to GUI. Or you can send direct raw bitmap data:

    raw_img_data = img.tostring()
    
https://en.xdnf.cn/q/26482.html

Related Q&A

Numpy list of 1D Arrays to 2D Array

I have a large list files that contain 2D numpy arrays pickled through numpy.save. I am trying to read the first column of each file and create a new 2D array.I currently read each column using numpy.…

What is metrics in Keras?

It is not yet clear for me what metrics are (as given in the code below). What exactly are they evaluating? Why do we need to define them in the model? Why we can have multiple metrics in one model?…

ObjectNotExecutableError when executing any SQL query using AsyncEngine

Im using async_engine. When I try to execute anything: async with self.async_engine.connect() as con:query = "SELECT id, name FROM item LIMIT 50;"result = await con.execute(f"{query}&quo…

Store the cache to a file functools.lru_cache in Python = 3.2

Im using @functools.lru_cache in Python 3.3. I would like to save the cache to a file, in order to restore it when the program will be restarted. How could I do?Edit 1 Possible solution: We need to pi…

Moon / Lunar Phase Algorithm

Does anyone know an algorithm to either calculate the moon phase or age on a given date or find the dates for new/full moons in a given year?Googling tells me the answer is in some Astronomy book, but…

Flask-RESTful API: multiple and complex endpoints

In my Flask-RESTful API, imagine I have two objects, users and cities. It is a 1-to-many relationship. Now when I create my API and add resources to it, all I can seem to do is map very easy and genera…

Setting initial Django form field value in the __init__ method

Django 1.6I have a working block of code in a Django form class as shown below. The data set from which Im building the form field list can include an initial value for any of the fields, and Im having…

Should I use a main() method in a simple Python script?

I have a lot of simple scripts that calculate some stuff or so. They consist of just a single module.Should I write main methods for them and call them with the if __name__ construct, or just dump it a…

Where can I find mad (mean absolute deviation) in scipy?

It seems scipy once provided a function mad to calculate the mean absolute deviation for a set of numbers:http://projects.scipy.org/scipy/browser/trunk/scipy/stats/models/utils.py?rev=3473However, I c…

Map of all points below a certain time of travel?

My question is very simple and can be understood in one line:Is there a way, tool, etc. using Google Maps to get an overlay of all surface which is below a certain time of travel?I hope the question i…