How to convert a string to an image?

后端 未结 2 1789
渐次进展
渐次进展 2020-12-04 22:39

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

相关标签:
2条回答
  • 2020-12-04 22:50
    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()
      
    0 讨论(0)
  • 2020-12-04 23:09

    The first 3 lines are not complete, when I'm not wrong. The correct code would be:

    from PIL import Image
    from PIL import ImageDraw
    from PIL import ImageFont
    
    0 讨论(0)
提交回复
热议问题