gpt4 book ai didi

python - 调用函数时,try/except语句在哪里?

转载 作者:行者123 更新时间:2023-12-03 09:12:39 24 4
gpt4 key购买 nike

我有我要调用函数的主要Python脚本。我想捕获函数执行期间发生的任何错误,如果有任何错误,我想将error变量设置为true。是否在主脚本中完成了try/except语句,如下所示:

try:
image_convert(filepath,'.jpg','RGB',2500,2500)

except:
error = true
还是在这样的函数内部完成:
def image_convert(filepath,imageType,colorMode,height,width):
try:
imwrite(filepath[:-4] + imageType, imread(filepath)[:,:,:3].copy()) # <-- using the imagecodecs library function of imread, make a copy in memory of the TIFF File.
# The :3 on the end of the numpy array is stripping the alpha channel from the TIFF file if it has one so it can be easily converted to a JPEG file.
# Once the copy is made the imwrite function is creating a JPEG file from the TIFF file.
# The [:-4] is stripping off the .tif extension from the file and the + '.jpg' is adding the .jpg extension to the newly created JPEG file.
img = Image.open(filepath[:-4] + imageType) # <-- Using the Image.open function from the Pillow library, we are getting the newly created JPEG file and opening it.
img = img.convert(colorMode) # <-- Using the convert function we are making sure to convert the JPEG file to RGB color mode.
imageResize = img.resize((height, width)) # <-- Using the resize function we are resizing the JPEG to 2500 x 2500
imageResize.save(filepath[:-4] + imageType) # <-- Using the save function, we are saving the newly sized JPEG file over the original JPEG file initially created.
return(imageResize)
except:
error = true

最佳答案

第一种方法有效

try:
image_convert(filepath,'.jpg','RGB',2500,2500)
except:
error = true

关于python - 调用函数时,try/except语句在哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63526005/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com