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

Time:01-17

Currently, I am scrapping the image from the web but it is definitely a vulnerability. Would appreciate guidance on passing the image from static folder to processing in the python script.

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

CodePudding user response:

You can create a function that will attempt to open it from the static folder unless it doesn't exist, in which case it will fetch from the web. It is a simple caching mechanism. Make sure you create a /static folder or change the path accordingly.

For example:

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

CodePudding user response:

In general, the paths to the images (whether you store them in the file system or in s3) store in the database. If you don't want to use a database, you can select files in a folder by their unique name.

  •  Tags:  
  • Related