欢迎光临散文网 会员登陆 & 注册

百度批量下载图片,缩放图片为512×512,不改变图片原图

2023-04-04 16:57 作者:MakeYiKe  | 我要投稿

所用关键工具:

Open Web Scraper浏览器插件

懂点python

步骤:

百度搜索“猫”

鼠标右键,选择检查,或按F12

选择插件Web Scraper浏览器插件

选择Create new sitemap

复制搜索出来图片的网址,Sitempa name起个名称,Start URL搜索的网址地址复制粘贴

选择Add new selector

ID名称随便起,Type选择Image,Multiple勾选上(不勾上后期只能看到1个数据),然后点Select

出现这个按住Shift,然后鼠标选择图片,系统会自动选择相同的元素,选中会变红。选完后按Done selecting。

点击Element preview,会出现Selected element count:11,告诉你选择了多少个图片,然后按Data preview,

就会看到地址了,不过是webp格式,全选复制到excel表格,用下载工具直接无法下载。要把他们的后缀批量加上  .webp才能下载

下面就用python程序进行下载和保存。

import pandas as pd
import requests

保存到excel表格进行读取

df = pd.read_excel('image_temp.xlsx')
n=0

批量保存

ps = df.iloc[:, 0]
for x in ps:
   response = requests.get(x)
   n+=1
   with open(f'./image_in/'+str(n)+'.webp', 'wb') as f:
           f.write(response.content)


此程序AI直接给的,运行无报错一次通过

import os
from PIL import Image

从此文件夹读取图片,自己改图片文件夹所在位置

directory = r'./image_in'

缩放图片,缩放至512×512的尺寸,判断图片的长宽,大的就按512,小的不够部分用白色填充。

for filename in os.listdir(directory):
   if filename.endswith('.jpg') or filename.endswith('.png'):
       # Open the image file
       with Image.open(os.path.join(directory, filename)) as img:
           # Calculate the new size while maintaining the aspect ratio
           width, height = img.size
           aspect_ratio = width / height
           new_size = (512, 512)

# Determine which dimension to scale based on the aspect ratio
           if aspect_ratio >= 1:
               new_width = 512
               new_height = int(new_width / aspect_ratio)
           else:
               new_height = 512
               new_width = int(new_height * aspect_ratio)

# Create a new image with the desired size and fill color
           resized_img = Image.new('RGB', new_size, (255, 255, 255))

# Paste the resized image onto the new image with centered alignment
           x_offset = int((new_size[0] - new_width) / 2)
           y_offset = int((new_size[1] - new_height) / 2)
           resized_img.paste(img.resize((new_width, new_height), resample=Image.LANCZOS), (x_offset, y_offset))

# Save the resized image with the same filename and extension
           resized_filename = os.path.splitext(filename)[0] + '_resized' + os.path.splitext(filename)[1]
           resized_img.save(os.path.join("./image_out", resized_filename))


百度批量下载图片,缩放图片为512×512,不改变图片原图的评论 (共 条)

分享到微博请遵守国家法律