python - python从url和缩略图下载图像并调整大小
问题描述
如果我必须从网站上找到图像并将其保存到驱动器上的特定文件夹以及缩略图并将图像大小调整为更小,我仍然是编程和学校作业的新手。我不能对特定文件夹进行硬编码。它必须拉起搜索文件区域。任何帮助将不胜感激。这是我到目前为止得到的,但我从这里迷路了。
import urllib
def myCreate():
"""
myCreate(): function pulls a picture from the internet and creates a thumbnail and saves it to my computer.
"""
path = setMediaPath()
data = urllib.urlretrieve("https://www.catster.com/wp-content/uploads/2018/07/Savannah-cat-long-body-shot.jpg", path + "myPicture.jpg")
file = getMediaPath("myPicture.jpg")
picture = makePicture(file)
myCreate()
解决方案
首先,我们需要下载图像,然后将其转换为缩略图并将图像调整为更小:
# install glob using pip install glob3
# and PIL using pip install Pillow
import urllib.request as req
from PIL import Image
# dont forget to put the img url here
imgurl ="https://-------------.jpg"
req.urlretrieve(imgurl, "image_name.jpg")
import glob
# get all the jpg files from the current folder
for infile in glob.glob("*.jpg"):
im = Image.open(infile)
# convert to thumbnail image
im.thumbnail((128, 128), Image.ANTIALIAS)
# don't save if thumbnail already exists
if infile[0:2] != "T_":
# prefix thumbnail file with T_
im.save("T_" + infile, "JPEG")
推荐阅读
- opencv - 用于提取 I 帧的 OpenCv API
- javascript - 根据动态表中的另一个选择选项选择选项值
- javascript - 每次点击时按 Amount 增加 div 宽度
- python - 从经理那里获取字典作为全局变量
- angular - 如何在我的 Angular app.module 中导入我的 package.json?
- ruby-on-rails - 如何在 Rails 5 中使用 text_field 发送搜索查询(URL 参数)?
- c# - 检测活动 RDP 会话
- php - 使用数组和 PHP 查找匹配的相等顺序
- angular - 错误 TS2339:“Promise”类型上不存在属性“finally”
' - angular - 如何在 Angular 6 中使用 Observables 而不是 document.querySelector