【发布时间】:2022-08-08 23:43:05
【问题描述】:
我在 Google Cloud Functions 中有一个 Python 脚本。
脚本的其中一个部分获取了一个 URL 列表(以字符串格式),我当前正在按原样存储该列表。
我遇到的问题是,在该脚本的本地版本(我在计算机上运行的那个)中,我将这些 URL 的文件下载到本地文件夹中,因为我需要将这些文件存储在 Firebase 存储中,但是具有较低的分辨率和尺寸。
这是我用来下载图像的代码:
在这里,我运行完整的东西来获取 url,然后将这些 URL 更改为 jpg。
#Images Section
imagesRaw = []
imagesSection = soup.find(\'div\', {\'class\': \'src__GalleryContainer-sc-bdjcm0-7\'})
imagesInfo = imagesSection.find_all(\'img\', {\'class\': \'gallery-image__StyledImg-sc-jtk816-0\'})
image1 = imagesInfo[0].get(\'src\')
for image in imagesInfo:
img = image.get(\'data-flickity-lazyload-src\')
imagesRaw.append(img)
imagesRaw.pop(0)
imagesRaw.insert(0, image1)
images = imagesRaw[:12]
imageFile = []
#Here we will store the images in local file
for image in images:
#First we change the ending from webp to jpg
newURL = image[:-4] + \'jpg\'
print(newURL)
name = find_between(newURL, \"_img\", \"/origin.jpg\")
if name == \"\":
name = random_name()
print(name)
#Here the function to download the image
try:
dl_jpg(newURL, \'images/\', name)
except:
break
#Here we Optimize the image to size 500 x 394 pixels
# And get the location for the new image
try:
path = optimizeImage(name)
except:
break
# We append the path to the Array of paths
imageFile.append(path)
这是我用来从 URL 下载图像的功能:
def dl_jpg(url, file_path, file_name):
full_path = file_path + file_name + \'.jpg\'
path = urllib.request.urlretrieve(url, full_path)
这是我根据需要优化图像的功能:
def optimizeImage(name) -> str:
foo = Image.open(os.path.join(\'images/\', name + \'.jpg\'))
foo = foo.resize((525,394),Image.ANTIALIAS)
foo.save(\'images/\' + name + \'.jpg\',optimize=True,quality=50)
print(\'Optimized Image: \' + name)
return \'images/\' + name + \'.jpg\'
最后,我得到了存储在 Firebase Storage 中的图像,如下所示:
photos = []
for image in listing.photos:
fullpath = image #find_between(image, \'scrapping/\', \'.jpg\') + \'.jpg\'
filename = fullpath[7:]
path = fullpath[0:6]
imagePath = path + \'/\' + filename
bucket = storage.bucket()
blob = bucket.blob(\'ListingImages/\' + ref.id + \'/\' + filename)
blob.upload_from_filename(imagePath)
blob.make_public()
photos.append(blob.public_url)
我看到的问题是,在我的本地脚本旁边确实有一个名为 Images 的文件夹,但是在 Cloud Functions 中,我不知道如何拥有类似的东西来帮助我在优化和上传,然后删除文件。
有任何想法吗?
-
您可以将图片保存在云功能中
/tmp。请注意,/tmp加载到内存中而不是磁盘中,因此请尽量防止内存不足 -
你可能有这个教程吗?
-
你可以检查这个medium.com/@hpoleselo/…
-
嘿,我在使用 /tmp/ 时遇到了一个新问题,基本上我将 images/ 更改为 /tmp/,它似乎进行了下载和优化,但最后在上传到 firestorage 时给出了这个错误:\"[Errno 2] No such file or directory:\'/tmp/h/cabujfoh.jpg\'\" 就像它在这种情况下添加了一个子文件夹 h 不知道它为什么添加它,一个想法?我在哪里可以直观地看到 tmp 中的文件?
-
使用这些详细信息编辑或创建新问题
标签: python google-cloud-functions google-cloud-storage