首页 > 编程问答 >表情符号未用颜色渲染

表情符号未用颜色渲染

时间:2024-07-25 04:59:22浏览次数:6  
标签:python python-imaging-library

我正在尝试将彩色表情符号作为叠加层添加到图像上,但表情符号似乎一直以黑白渲染,并且也是透明的:

example output

这就是我当前正在使用的:

def add_text_overlay(image_path, text, font_path, emoji_font_path, font_size, text_spacing, x_padding, output_path,
                     text_position, offset_x, offset_y):
    with PILImage.open(image_path) as img:
        img = crop_and_resize(img, 1080, 1440)

        draw = ImageDraw.Draw(img)
        font = ImageFont.truetype(font_path, font_size)

        # Load the emoji font using PIL
        emoji_font = None
        try:
            emoji_font = ImageFont.truetype(emoji_font_path, 137)  # Adjust pixel size as needed
        except OSError as e:
            logging.error(f"Unable to load the emoji font: {e}")
            logging.error(f"Path checked: {os.path.abspath(emoji_font_path)}")
            emoji_font = font  # Fallback to regular font if emoji font fails

        lines = wrap_text(text, 28)
        fixed_line_height = font_size + text_spacing
        total_text_height = fixed_line_height * len(lines)

        initial_text_y = (img.height - total_text_height) / 2 + offset_y

        for i, line in enumerate(lines):
            text_bbox = draw.textbbox((0, 0), line, font=font)
            text_width = text_bbox[2] - text_bbox[0]

            if text_position == 'left':
                text_x = x_padding + offset_x
            elif text_position == 'right':
                text_x = img.width - text_width - x_padding + offset_x
            else:
                text_x = (img.width - text_width) / 2 + offset_x

            text_y = initial_text_y + i * fixed_line_height
            if text_x < 0:
                text_x = 0
            if text_x + text_width > img.width:
                text_x = img.width - text_width

            # Draw each character with the appropriate font
            for char in line:
                char_font = emoji_font if is_emoji(char) else font  # Use emoji font for emoji characters
                draw.text((text_x, text_y), char, font=char_font, fill="black")
                text_x += char_font.getbbox(char)[2]  # Update this line to use getbbox

        img.save(output_path)

我有“无效的像素大小”错误有一段时间,直到我将像素大小更改为 137。然后它只绘制了单色透明表情符号。


问题在于正在使用 fill="black" 为表情符号着色。为了保留表情符号的颜色,需要对文本和表情符号使用不同的绘制方法。

可以使用 PIL 的 Image.alpha_composite() 方法将表情符号作为单独的图像绘制在文本的顶部。这将保留表情符号的原始颜色和透明度。

以下是更新后的代码:

def add_text_overlay(image_path, text, font_path, emoji_font_path, font_size, text_spacing, x_padding, output_path,
                     text_position, offset_x, offset_y):
    with PILImage.open(image_path) as img:
        img = crop_and_resize(img, 1080, 1440)

        draw = ImageDraw.Draw(img)
        font = ImageFont.truetype(font_path, font_size)

        # Load the emoji font using PIL
        emoji_font = None
        try:
            emoji_font = ImageFont.truetype(emoji_font_path, 137)  # Adjust pixel size as needed
        except OSError as e:
            logging.error(f"Unable to load the emoji font: {e}")
            logging.error(f"Path checked: {os.path.abspath(emoji_font_path)}")
            emoji_font = font  # Fallback to regular font if emoji font fails

        lines = wrap_text(text, 28)
        fixed_line_height = font_size + text_spacing
        total_text_height = fixed_line_height * len(lines)

        initial_text_y = (img.height - total_text_height) / 2 + offset_y

        for i, line in enumerate(lines):
            text_x = x_padding + offset_x
            text_y = initial_text_y + i * fixed_line_height

            for char in line:
                if is_emoji(char):
                    # Draw emoji as a separate image
                    emoji_img = Image.new("RGBA", emoji_font.getsize(char))
                    emoji_draw = ImageDraw.Draw(emoji_img)
                    emoji_draw.text((0, 0), char, font=emoji_font, fill="white")  # Use white or any color you prefer for emoji

                    # Calculate emoji position and paste onto the main image
                    img.paste(emoji_img, (text_x, text_y), emoji_img)
                    text_x += emoji_img.width
                else:
                    # Draw regular text
                    draw.text((text_x, text_y), char, font=font, fill="black")
                    text_x += font.getbbox(char)[2] 

        img.save(output_path)

在这个更新后的代码中: - 我们为每个表情符号字符创建了一个新的 Image 对象。 - 我们在这个新图像上绘制了表情符号,填充颜色为白色(或喜欢的任何颜色)。 - 然后,我们使用 img.paste() 将表情符号图像粘贴到主图像上的计算位置。

此方法应该在不影响其颜色或透明度的情况下正确呈现表情符号。

标签:python,python-imaging-library
From: 78789921

相关文章

  • Python XML 解析:字符串中的“<”被阻塞
    我有一个使用ET.XMLParser来解析CppCheckXML报告文件的Python模块。当尝试解析字符串中包含“<”的XML元素中的属性之一时,它会令人窒息,它会将其解释为格式错误的XML,例如:<errormsg="Includefile<iostream>notfound.">(注意字符和“iostream”之间的空格必须放......
  • 任意几行代码要成为Python中的函数需要什么?
    我正在上一门计算机科学课,我的任务是创建一个程序来实现一个带有参数的函数。我的老师告诉我,下面的代码不是一个函数,这让我很困惑,对于将某些代码行归类为“函数”所需的条件,我感到很困惑。defgame(numbers,max_turns,pfl,tgl):turns=0flag=Falseprint("You......
  • 如何使用 Python 创建新的 Azure 订阅?
    我正在尝试使用PythonSDK以编程方式创建新的Azure订阅。我发现的对AzurePythonSDK的唯一引用是这个这是我最终得到的结果:importazure.mgmt.billingimportazure.mgmt.subscriptioncreds=AzureCliCredential()client_name='test'defcreat......
  • 用于打印脚本输出的 Python 实用程序
    我可以发誓有一个实用程序可以打印一个python脚本,其输出交织在一起。例如,给定一个脚本:a=2b=3print(a+b)print(a*b)该实用程序将输出a=2b=3print(a+b)#>5print(a*b)#>6有人知道该实用程序的名称吗?我最难找到它。谢谢你!描述的实用程序没有标......
  • a method to make some handy tools with python
    Inmyworkingofcomputer,therearealotofsimplejobsthatarefrequentlyrepeated.Itriedtofindawaytomakethesejobbeenprocessedeasily.Method1:Themethodiswritingascripttodothejob,andexecutingthescriptbyutoolsextensionuto......
  • Python网络爬虫详解:实战豆瓣电影信息采集
    文章目录前言一、爬虫是什么?二、常用库及其作用1.Requests2.BeautifulSoup3.lxml4.Scrapy5.Selenium6.PyQuery7.Pandas8.JSON9.Time三、实现步骤步骤一:环境准备步骤二:数据采集步骤三:数据处理步骤四:数据存储总结前言随着互联网的迅猛发展和数据分析需求的不......
  • python学习之内置函数
    Python拥有许多内置函数,这些函数是Python的一部分,不需要额外导入即可直接使用。这些函数提供了对Python解释器功能的直接访问,涵盖了从数学计算到类型检查、从内存管理到异常处理等各个方面。下面是一些常用的Python内置函数及其简要说明:一、Printprint函数大家都不会......
  • Python中以函数为作用域
    点击查看代码#第一题foriteminrange(10):#不报错,没有函数,所有操作在全局作用域里面执行,item最后赋值为:9,此时item在缩进与全局都可以使用passprint(item)#第二题item=10deffunc():foriteminrange(10):#优先在本地查找,找不到在到全局查找p......
  • 掌握IPython宏:%%macro命令的高效使用指南
    掌握IPython宏:%%macro命令的高效使用指南在编程中,宏是一种允许你定义可重用代码片段的强大工具。IPython,这个增强版的Python交互式环境,提供了一个名为%%macro的魔术命令,允许用户创建宏,从而提高代码的可重用性和效率。本文将详细介绍如何在IPython中使用%%macro命令创建宏,并......
  • 7月24号python:库存管理
    7月24号python:库存管理题目:​ 仓库管理员以数组stock形式记录商品库存表。stock[i]表示商品id,可能存在重复。原库存表按商品id升序排列。现因突发情况需要进行商品紧急调拨,管理员将这批商品id提前依次整理至库存表最后。请你找到并返回库存表中编号的最小的元素以便及......