栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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

import ctypesimport structimport win32conimport win32guiimport win32uifrom PIL import Imagedef 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 imclass 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")

结果:

辉煌!!!

要渲染一个特定的

.ttf
文件,我需要深入研究。

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



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/659686.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号