首页 > 解决方案 > 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()

标签: python

解决方案


首先,我们需要下载图像,然后将其转换为缩略图并将图像调整为更小:

# 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")

推荐阅读