python从URL和缩略图下载图像并调整大小

时间:2019-03-09 20:51:21

标签: python

对于编程和从事学校作业,我还是很陌生,因为我必须从网站上查找图像,并将其保存到驱动器上的特定文件夹以及缩略图中,然后将图像调整为较小的尺寸。我无法对特定文件夹进行硬编码。它必须拉起对文件区域的搜索。任何帮助将不胜感激。这是我到目前为止所取得的成就,但我从这里迷失了。

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()

1 个答案:

答案 0 :(得分:0)

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

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