问题描述
我正在尝试使用 Blob 触发器在本地调试 Azure 函数。将图像文件上传到 Azure 时,我在本地运行的函数会收到触发器。
def main(blobin: func.InputStream,blobout: func.Out[bytes],context: func.Context):
logging.info(f"Python blob trigger function processed blob \n"
f"Name: {blobin.name}\n"
f"Blob Size: {blobin.length} bytes")
image_file = Image.open(blobin)
我的函数.json
{
"scriptFile": "__init__.py","bindings": [
{
"name": "blobin","type": "blobTrigger","direction": "in","path": "uploads/{name}","connection": "STORAGE"
},{
"name": "blobout","type": "blob","direction": "out","path": "uploads/{blob_name}_resized.jpg","connection": "STORAGE"
}
]
}
运行 Image.open(blobin)
行时出现的错误是:
System.Private.CoreLib:执行函数时出现异常: 函数。调整大小照片。 System.Private.CoreLib:结果:失败 异常:UnidentifiedImageError:无法识别图像文件 <_io.bytesio>
有趣的是,图像本身确实在 VSCode 监视窗口中打开,但在运行代码时失败。如果我再次将其添加到手表中,它也会出现与上述相同的错误(可能触发手表刷新)。
解决方法
如果要调整图像大小然后通过函数 blob 触发器保存,请尝试以下代码:
import logging
from PIL import Image
import azure.functions as func
import tempfile
import ntpath
import os
def main(blobin: func.InputStream,blobout:func.Out[func.InputStream],context: func.Context):
logging.info(f"Python blob trigger function processed blob \n"
f"Name: {blobin.name}\n"
f"Blob Size: {blobin.length} bytes")
temp_file_path = tempfile.gettempdir() + '/' + ntpath.basename(blobin.name)
print(temp_file_path)
image_file = Image.open(blobin)
image_file.resize((50,50)).save(temp_file_path)
blobout.set(open(temp_file_path,"rb").read())
os.remove(temp_file_path)
function.json :
{
"scriptFile": "__init__.py","bindings": [
{
"name": "blobin","type": "blobTrigger","direction": "in","path": "samples-workitems/{name}","connection": "STORAGE"
},{
"name": "blobout","type": "blob","direction": "out","path": "resize/{name}","connection": "STORAGE"
}
]
}
请注意,您不应将调整大小的图像存储在同一个容器中,因为它会导致无限循环(新图像触发 blob 触发器并一次又一次地调整大小),并且您的问题是由于新调整大小的图像输出不正确以便在运行时发生异常:Image.open(blobin)
无论如何,上面的代码非常适合我,请看下面的结果:
,事实证明,在 Image.open(blobin)
行设置断点会以某种方式中断函数。从那里删除它并将其添加到下一行不再提示错误。可能 Azure 不喜欢等待并超时流?谁知道呢。