如何将 flask 中的图像从静态文件夹传递到 python 中进行处理?

How do you pass the image in flask to processing in python from static folder?

目前,我正在从网上抓取图像,但这绝对是一个漏洞。希望获得有关将图像从静态文件夹传递到 python 脚本中处理的指导。

from PIL import Image
from io import BytesIO
import requests

def generate_image(yel_stars,r=250,g=250,b=250):
    #generate background color
    first_im = Image.new(mode="RGBA", size=(300, 300), color = (r,g,b))

    #get star image        
    star_url='https://cdn.pixabay.com/photo/2017/01/07/21/22/stars-1961613_1280.png'
    img = requests.get(star_url).content
    #preprocess star image
    team_img = Image.open(BytesIO(img)).convert("RGBA")
    team_img = team_img.resize((40, 20), resample=Image.NEAREST)

    #generate the location of stars *2 for x and y axis
    hor = generateRandomNumber(0, 280, yel_stars*2)
    #put on the image
    for x in range(yel_stars):
        first_im.paste(team_img,(hor[x],hor[x+yel_stars]), team_img)
    return first_im

您可以创建一个函数,尝试从静态文件夹中打开它,除非它不存在,在这种情况下,它将从网络上获取。这是一个简单的缓存机制。确保创建 /static 文件夹或相应地更改路径。

例如:

from PIL import Image
import requests


STAR_URL = 'https://cdn.pixabay.com/photo/2017/01/07/21/22/stars-1961613_1280.png'
STATC_STAR_LOCATION = "./static/star.png"
def open_star():
    try:
        # Attempt to open if exists
        return open(STATC_STAR_LOCATION, 'rb')
    except FileNotFoundError:
        # Otherwise, fetch from web
        request = requests.get(STAR_URL, stream=True)
        file = open(STATC_STAR_LOCATION, 'w+b')
        for chunk in request.iter_content(chunk_size=1024):
            file.write(chunk)
        file.flush()
        file.seek(0)
        return file

def generate_image(yel_stars,r=250,g=250,b=250):
    #generate background color
    first_im = Image.new(mode="RGBA", size=(300, 300), color = (r,g,b))

    #get star image        
    star_file = open_star()
    #preprocess star image
    team_img = Image.open(star_file).convert("RGBA")
    team_img = team_img.resize((40, 20), resample=Image.NEAREST)

    #generate the location of stars *2 for x and y axis
    hor = generateRandomNumber(0, 280, yel_stars*2)
    #put on the image
    for x in range(yel_stars):
        first_im.paste(team_img,(hor[x],hor[x+yel_stars]), team_img)
    return first_im

一般来说,图片的路径(无论是存储在文件系统中还是s3中)都存储在数据库中。 如果您不想使用数据库,您可以 select 文件夹中的文件按其唯一名称。