简体   繁体   中英

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

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. See here . You should be able to replace url with filepath and put that in Image.open

pil_image = Image.open(filepath)

Just pass the filepath in as the argument and read from 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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