简体   繁体   English

将预定义函数的输入从url更改为本地文件

[英]change the input of a pre-defined function from a url to a local file

I need to change this function from url input to a local file input 我需要将此功能从url输入更改为本地文件输入

def download_and_resize_image(url, new_width=256, new_height=256,display=False):

    _, filename = tempfile.mkstemp(suffix=".jpg")
    response = urlopen(url)
    image_data = response.read()
    image_data = BytesIO(image_data)
    pil_image = Image.open(image_data)
    pil_image = ImageOps.fit(pil_image, (new_width, new_height), Image.ANTIALIAS)
    pil_image_rgb = pil_image.convert("RGB")
    pil_image_rgb.save(filename, format="JPEG", quality=90)
    print("Image downloaded to %s." % filename)
    if display:
      display_image(pil_image)
    return filename

This code was given to me by my teacher. 这段代码是我老师给我的。 How can I change the input to a local file? 如何将输入更改为本地文件?

I looked in the request library but I was not lucky with a function. 我查看了请求库,但对函数感到不满意。 Is there a predefined function to grab a local file or how /what changes should I make on the predefined function? 是否有预定义的函数来获取本地文件,或者应该如何对预定义的函数进行哪些更改?

The Image.open method takes a file-path and a mode. Image.open方法采用文件路径和模式。 See here . 看这里 You should be able to replace url with filepath and put that in Image.open 您应该能够用文件路径替换url并将其放在Image.open中

pil_image = Image.open(filepath)

Just pass the filepath in as the argument and read from fileapth . 只需传入filepath作为参数,然后从fileapth读取。 Try this. 尝试这个。

def download_and_resize_image(filepath, new_width=256, new_height=256,display=False):

# _, filename = tempfile.mkstemp(suffix=".jpg")
# response = urlopen(url)
# image_data = response.read()
# image_data = BytesIO(image_data)
pil_image = Image.open(filepath)
pil_image = ImageOps.fit(pil_image, (new_width, new_height), Image.ANTIALIAS)
pil_image_rgb = pil_image.convert("RGB")
pil_image_rgb.save(filename, format="JPEG", quality=90)
print("Image downloaded to %s." % filename)
if display:
display_image(pil_image)
return filename

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM