You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在AWS Lambda中搭配libraqm使用PIL(Pillow)?

解决PIL依赖libraqm的Lambda层构建问题

核心原因

Lambda运行环境基于Amazon Linux系列系统,你本地用apt安装的Debian系libraqm库和Lambda环境不兼容,这是之前尝试非官方RPM、源码编译失败的关键。必须在匹配的Amazon Linux环境下编译依赖再打包成层。

可行解决方案

方法1:用Amazon Linux容器编译(最可靠)

  1. 启动Amazon Linux 2容器模拟Lambda环境:
    docker run -it amazonlinux:2 bash
    
  2. 安装编译所需的系统依赖:
    yum install -y gcc gcc-c++ make git autoconf automake libtool pkgconfig freetype-devel harfbuzz-devel fribidi-devel
    
  3. 编译安装libraqm:
    git clone https://github.com/HOST-Oman/libraqm.git
    cd libraqm
    ./autogen.sh
    ./configure --prefix=/opt/libraqm
    make && make install
    
  4. 编译安装Pillow并指定libraqm路径:
    # 替换python3.x为你Lambda使用的Python版本(如3.9、3.10)
    pip install pillow --global-option=build_ext --global-option="-L/opt/libraqm/lib" --global-option="-I/opt/libraqm/include" -t /opt/python/lib/python3.x/site-packages
    
  5. 打包层:
    • 将/opt/python目录打包为zip,作为Pillow的依赖层。
    • 将/opt/libraqm/lib下的.so文件(如libraqm.so.0)放入层的lib目录,单独打包或合并到Pillow层的lib目录中。

方法2:用AWS SAM简化层构建

借助AWS SAM的自动构建能力,在匹配环境中生成兼容层:

  1. 创建SAM模板template.yaml:
    AWSTemplateFormatVersion: '2010-09-09'
    Transform: AWS::Serverless-2016-10-31
    Resources:
      PillowLibraqmLayer:
        Type: AWS::Serverless::LayerVersion
        Properties:
          ContentUri: layer/
          CompatibleRuntimes:
            - python3.9 # 替换为你的Lambda Python版本
        Metadata:
          BuildMethod: python3.9
    
  2. 在layer目录下创建requirements.txt:
    pillow
    
  3. 执行构建命令,SAM会自动在Amazon Linux环境中编译带libraqm支持的Pillow:
    sam build
    
    构建完成后,.aws-sam/build/PillowLibraqmLayer下的内容即可直接上传为Lambda层。

验证步骤

上传层到Lambda后,用以下代码测试复杂文本渲染:

from PIL import Image, ImageDraw, ImageFont

def lambda_handler(event, context):
    img = Image.new('RGB', (300, 150), color='white')
    draw = ImageDraw.Draw(img)
    # 测试带连字/RTL的文本(如阿拉伯语)
    draw.text((20,20), "السلام عليكم", fill='black', font=ImageFont.truetype('arial.ttf', 24))
    return {"status": "success"}

若能正常执行,说明libraqm依赖已生效。

内容的提问来源于stack exchange,提问作者Gibreel Abdullah

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 12:15:43