目前,我正在從網路上洗掉影像,但這絕對是一個漏洞。將不勝感激有關將影像從靜態檔案夾傳遞到 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
uj5u.com熱心網友回復:
您可以創建一個函式,該函式將嘗試從靜態檔案夾打開它,除非它不存在,在這種情況下,它將從 Web 獲取。這是一個簡單的快取機制。確保創建一個/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
uj5u.com熱心網友回復:
通常,影像的路徑(無論您將它們存盤在檔案系統中還是在 s3 中)都存盤在資料庫中。如果您不想使用資料庫,您可以按檔案的唯一名稱選擇檔案夾中的檔案。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/413568.html
標籤:
下一篇:具有高布局的SwiftUI影像
