在 App Engine 上将文本转换为 PNG (Python)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2431345/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-04 00:38:07  来源:igfitidea点击:

Text to a PNG on App Engine (Python)

pythonimagegoogle-app-engineunicode

提问by Bemmu

Note: I am cross-posting this from App Engine group because I got no answers there.

注意:我是从 App Engine 小组交叉发布这个的,因为我在那里没有得到答案。

As part of my site about Japan, I have a feature where the user can get a large PNG for use as desktop background that shows the user's name in Japanese. After switching my site hosting entirely to App Engine, I removed this particular feature because I could not find any way to render text to a PNG using the image API.

作为我关于日本的网站的一部分,我有一个功能,用户可以获得一个大的 PNG 作为桌面背景,用日语显示用户的名字。将我的网站托管完全切换到 App Engine 后,我删除了此特定功能,因为我找不到任何使用图像 API 将文本呈现为 PNG 的方法。

In other words, how would you go about outputting an unicode string on top of an image of known dimensions (1024x768 for example), so that the text will be as large as possible horizontally, and centered vertically? Is there a way to do this is App Engine, or is there some external service besides App Engine that could make this easier for me, that you could recommend (besides running ImageMagick on your own server)?

换句话说,您将如何在已知尺寸(例如 1024x768)的图像上输出 unicode 字符串,以便文本在水平方向尽可能大,并垂直居中?有没有办法做到这一点是 App Engine,或者除了 App Engine 之外,是否还有一些外部服务可以让我更轻松,您可以推荐(除了在您自己的服务器上运行 ImageMagick)?

回答by sastanin

Solution #1. Pure Python image library.

解决方案#1。纯 Python 图像库。

You can try to bundle PyPNGwith your application. PyPNG is a pure Python library to create PNG images. It depends on zlib module, which is allowed on AppEngine, so PyPNG should work on AppEngine. Just use StringIO objects instead of files and write PNG data to them.

您可以尝试将PyPNG与您的应用程序捆绑在一起。PyPNG 是一个纯 Python 库,用于创建 PNG 图像。它依赖于 AppEngine 上允许的 zlib 模块,因此 PyPNG 应该可以在 AppEngine 上运行。只需使用 StringIO 对象而不是文件并将 PNG 数据写入它们。

Shamelessly adapting PyPNG example how to make a bitmap PNG image:

无耻地改编 PyPNG 示例如何制作位图 PNG 图像:

import png
from StringIO import StringIO

# bitmap data
s = ['110010010011',
     '101011010100',
     '110010110101',
     '100010010011']
s = map(lambda x: map(int, x), s)

f = StringIO()
w = png.Writer(len(s[0]), len(s), greyscale=True, bitdepth=1)
w.write(f, s)

# binary PNG data
print f.getvalue()

I suspect suboptimal performance, but as far as I know there is no other way to generate images on GAE.

我怀疑性能欠佳,但据我所知,没有其他方法可以在 GAE 上生成图像。

And you still need to figure out how to rasterize text to produce bitmap data. The easiest way, probably, is just to keep bitmaps of all the symbols around (essentially, using a bitmap font).

而且您仍然需要弄清楚如何光栅化文本以生成位图数据。最简单的方法可能就是保留所有符号的位图(本质上,使用位图字体)。

To render ASCII text with PyPNG take a look at texttopngscript.

要使用 PyPNG 呈现 ASCII 文本,请查看texttopng脚本。

So, limitations are:

所以,限制是:

  • Probably slow (needs to be checked)
  • Glyph rasterization is to be addressed
  • 可能很慢(需要检查)
  • 字形光栅化有待解决

Solution #2. Off-site text-to-image rendering.

解决方案#2。场外文本到图像的渲染。

Google AppEngine does not provide tools to render text as raster images, but Google Charts does. With a proper choice of parameters, the outline textchart just renders simple text to PNG images.

Google AppEngine 不提供将文本呈现为光栅图像的工具,但 Google Charts 提供。通过正确选择参数,轮廓文本图表仅将简单文本呈现为 PNG 图像。

For example, http://chart.apis.google.com/chart?chst=d_text_outline&chld=000000|32|h|FFFFFF|_|Render text to image|with Google Charts.|Some Unicode too:|Здра?вствуйте|こんにちは|??????|你好|???produces this:

例如,http://chart.apis.google.com/chart?chst=d_text_outline&chld=000000|32|h|FFFFFF|_|Render text to image|with Google Charts.|Some Unicode too:|Здра?вствуйте|こんにちは|??????|你好|???产生这个:

text-to-image on Google Charts

Google Charts 上的文字转图片

Limitations:

限制:

  • You cannot generate images bigger than 300000 pixels
  • Style and font customizations are limited
  • Some Unicode scripts are not available
  • White background only
  • 您不能生成大于 300000 像素的图像
  • 样式和字体自定义有限
  • 某些 Unicode 脚本不可用
  • 仅白色背景

回答by Derek Dahmer

I ran into this same problem with writing text to an image. The issue at hand is that any imaging libraries used on google app engine must be pure python, which rules out PIL.

我在将文本写入图像时遇到了同样的问题。手头的问题是谷歌应用引擎上使用的任何图像库都必须是纯python,这排除了PIL。

PyBMP

PyBMP

PyBMPis a pure-python library that can do simple text rendering. From there you can use google's imaging library to composite the resulting bitmap onto your other pictures. There's some sample code below. The downside is the library lacks nicer features like anti-aliasing and fine control over fonts so the text that it renders looks kind of crappy. It also may or may not handle unicode well.

PyBMP是一个纯 python 库,可以进行简单的文本渲染。从那里您可以使用谷歌的图像库将生成的位图合成到您的其他图片上。下面有一些示例代码。缺点是该库缺乏更好的功能,例如抗锯齿和对字体的精细控制,因此它呈现的文本看起来有点蹩脚。它也可能会也可能不会很好地处理 unicode。

# Create the image
text_img = bmp.BitMap(300,35,bmp.Color.WHITE)
# bmpfont_Tw_Cen_MT_30 is a generated file using PyBMP's tool
text_img.setFont(bmpfont_Tw_Cen_MT_30.font_data)
text_img.setPenColor( bmp.Color.BLACK )
text_img.drawText(name, 0, 0)

After this you can use google's compositefunction on text_img.getBitmap()as you would any other image.

在此之后,您可以像使用任何其他图像一样使用 google 的composite功能text_img.getBitmap()

External Image Processing

外部图像处理

If the text isn't good enough (it wasn't for my project), an alternative solution is to set up an external server on a service like Rackspace purely for image processing. Set up an HTTP handler that does your image processing with PIL, and then returns the resulting image. From there you can either

如果文本不够好(不适合我的项目),另一种解决方案是在 Rackspace 等服务上设置外部服务器,纯粹用于图像处理。设置一个 HTTP 处理程序,使用 PIL 进行图像处理,然后返回结果图像。从那里你可以

  • upload the result straight to your static file hosting server (like s3) or
  • get the generated-text image result with app engine's urlfetch library and do the rest of your compositing in app engine
  • 将结果直接上传到您的静态文件托管服务器(如 s3)或
  • 使用应用引擎的 urlfetch 库获取生成的文本图像结果,并在应用引擎中完成其余的合成

Not pretty, but it gets the job done.

不漂亮,但它完成了工作。

回答by user1327133

It's a bit too late but I was looking for the same. I managed to draw unicode string (here Devanagari) onto an image and save it as a '.png' file by doing the following:

为时已晚,但我一直在寻找相同的东西。我设法通过执行以下操作将 unicode 字符串(此处为天城文)绘制到图像上并将其保存为“.png”文件:

# -*- coding: utf-8 -*-
import Image, ImageDraw, ImageFont

img = Image.new('L', (16,16), 255)
draw = ImageDraw.Draw(img)
text_to_draw = unicode('?','utf-8')
font = ImageFont.truetype('Path/to/font/file',12)
draw.text((2,2), text_to_draw, font = font)
del draw

img.save('image.png')

P.S. got help from other posts on stackoverflow

PS 从 stackoverflow 上的其他帖子中得到了帮助

回答by Oddthinking

[Stop press: As comment suggests - this answer doesn't work in Googe App Engine.]

[停止新闻:正如评论所暗示的那样 - 这个答案在 Googe App Engine 中不起作用。]

The Python Imaging Library (PIL) can accomplish this.

Python 图像库 ( PIL) 可以实现这一点。

You can load in the image, draw Unicode text on it with the ImageDraw.text() function.

您可以加载图像,使用 ImageDraw.text() 函数在其上绘制 Unicode 文本。

You may need to call ImageDraw.textsize() a few times with different font sizes to find thelargest font that will fit.

您可能需要使用不同的字体大小多次调用 ImageDraw.textsize() 以找到适合的最大字体。

Finally, you can save the .png image to a file (or serve it back directly).

最后,您可以将 .png 图像保存到文件中(或直接将其返回)。

Test with large images if you are running it from within the context of a web-server, to make sure you can allocate sufficient memory to processs large PNG files.

如果您在 Web 服务器的上下文中运行它,请使用大图像进行测试,以确保您可以分配足够的内存来处理大型 PNG 文件。

(Have I answered your question appropriately? I don't know if PIL is an option from within the Google App Engine.)

(我是否正确回答了您的问题?我不知道 PIL 是否是 Google App Engine 中的一个选项。)