python:使用windows api使用ttf字体呈现文本

标签 python windows winapi fonts rendering

什么是一个完整的例子,从什么都没有到内存中的位图,打开一个特定的 .ttf 文件并使用该字体渲染一些文本,使用 native Windows API?我目前正在努力研究 Windows API,所以这是我和其他 stackoverflow 之间的竞赛。

最佳答案

完成渲染字体(需要 PyWin32):

import ctypes
import struct
import win32con
import win32gui
import win32ui

from PIL import Image


def RGB(r, g, b):    
    return r | (g << 8) | (b << 16)

def native_bmp_to_pil(hdc, bitmap_handle, width, height):
    bmpheader = struct.pack("LHHHH", struct.calcsize("LHHHH"),
                            width, height, 1, 24) #w,h, planes=1, bitcount)
    c_bmpheader = ctypes.c_buffer(bmpheader)

    #3 bytes per pixel, pad lines to 4 bytes    
    c_bits = ctypes.c_buffer(" " * (height * ((width*3 + 3) & -4)))

    res = ctypes.windll.gdi32.GetDIBits(
        hdc, bitmap_handle, 0, height,
        c_bits, c_bmpheader,
        win32con.DIB_RGB_COLORS)
    if not res:
        raise IOError("native_bmp_to_pil failed: GetDIBits")

    im = Image.frombuffer(
        "RGB", (width, height), c_bits,
        "raw", "BGR", (width*3 + 3) & -4, -1)
    return im    


class Win32Font:
    def __init__(self, name, height, weight=win32con.FW_NORMAL,
                 italic=False, underline=False):
        self.font = win32ui.CreateFont({
            'name': name, 'height': height,
            'weight': weight, 'italic': italic, 'underline': underline})

        #create a compatible DC we can use to draw:
        self.desktopHwnd = win32gui.GetDesktopWindow()
        self.desktopDC = win32gui.GetWindowDC(self.desktopHwnd)
        self.mfcDC = win32ui.CreateDCFromHandle(self.desktopDC)         
        self.drawDC = self.mfcDC.CreateCompatibleDC()

        #initialize it
        self.drawDC.SelectObject(self.font)

    def renderText(self, text):
        """render text to a PIL image using the windows API."""
        self.drawDC.SetTextColor(RGB(255,0,0))

        #create the compatible bitmap:
        w,h = self.drawDC.GetTextExtent(text)
        
        saveBitMap = win32ui.CreateBitmap()
        saveBitMap.CreateCompatibleBitmap(self.mfcDC, w, h)        
        self.drawDC.SelectObject(saveBitMap)

        #draw it
        self.drawDC.DrawText(text, (0, 0, w, h), win32con.DT_LEFT)

        #convert to PIL image
        im = native_bmp_to_pil(self.drawDC.GetSafeHdc(), saveBitMap.GetHandle(), w, h)

        #clean-up
        win32gui.DeleteObject(saveBitMap.GetHandle())

        return im        

    def __del__(self):
        self.mfcDC.DeleteDC()
        self.drawDC.DeleteDC()
        win32gui.ReleaseDC(self.desktopHwnd, self.desktopDC)
        win32gui.DeleteObject(self.font.GetSafeHandle())

    def __del__(self):
        win32gui.DeleteObject(self.font.GetSafeHandle())

用法:

>>> f = Win32Font("Arial", 15)
>>> im = f.renderText("this is just a test")
>>> im.save("c:/hope.png")

结果:

GLORY

太棒了!!!

要呈现特定的 .ttf 文件,我需要深入挖掘。

更新:已更新以计算 bmp 大小:

woot

关于python:使用windows api使用ttf字体呈现文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5750887/

相关文章:

python - 如何在没有换行符的情况下读取文件?

c - 在C中查找机器的IP地址?

python - Plotly:如何使用下拉菜单在每日和每小时烛台之间进行更改?

Python 多处理。你如何从 child 那里得到 parent 的地位?

python - 操作系统错误: [Errno 22] Invalid argument (Paramiko)

windows - 在 Windows 7 中使用 .NET Windows 服务显示消息框

delphi - 如何在 Delphi 中使用 "Native Wifi API"Windows API 函数

c++ - 在 Windows 上,命名管道文件存储在哪里?

python - 如何在 flask 中写复选框?

windows - 通过 OpenSSL 使用来自 Windows 证书库的证书和私钥