【问题标题】:Convert HTML string to image data and display it as an image in a template using Python将 HTML 字符串转换为图像数据并使用 Python 在模板中将其显示为图像
【发布时间】:2017-04-24 02:39:21
【问题描述】:

将 HTML 字符串转换为图像数据,并使用 Python 在模板中将其显示为图像。我有一个像下面这样的字符串

text = """< html>< body>< p style='color:red'>Stack Overflow< /p>< /body>< /html> 
       """

我需要将其转换为图像数据并将该图像显示到模板页面中。

【问题讨论】:

    标签: python


    【解决方案1】:

    你可以这样使用:

    from PIL import ImageFont
    from PIL import Image
    from PIL import ImageDraw
    
    text = """< html>< body>< p style='color:red'>Stackoverflow< /p>< /body>< /html> """
    
    bgcolor = 'white'
    text_color = 'black'
    rightpadding = 10
    leftpadding = 5
    
    font = ImageFont.load_default() # or ImageFont.truetype(font=font_name, size=font_size)
    line_width = font.getsize(text)[0]
    img_height = font.getsize(text)[1]
    
    img = Image.new("RGBA", (line_width + rightpadding , img_height), bgcolor)
    draw = ImageDraw.Draw(img)
    
    draw.text((leftpadding, 0), text, text_color)
    
    img.show()
    

    【讨论】:

      猜你喜欢
      • 2013-07-23
      • 1970-01-01
      • 2019-02-12
      • 2011-08-03
      • 1970-01-01
      • 2011-08-10
      • 2018-11-24
      • 2021-06-23
      • 1970-01-01
      相关资源
      最近更新 更多