下载图片
def generate_random_filename(self):
return ''.join(random.choices(string.ascii_lowercase + string.digits, k=8)) + '.jpg'
def download_image(self, url,download_path):
response = requests.get(url)
if response.status_code == 200:
random_filename = self.generate_random_filename()
with open(f"{download_path}/{random_filename}", "wb") as f:
f.write(response.content)
return random_filename
else:
return None
def download_images_from_baidu(self, word,download_path):
url = f"https://image.baidu.com/search/acjson?tn=resultjson_com&logid=7737487311581226922&ipn=rj&ct=201326592&is=&fp=result&fr=&word={word}&lm=&ie=utf-8&oe=utf-8&adpicid=&st=-1&z=&ic=&hd=&latest=©right=&s=&se=&tab=&width=&height=&face=0&istype=3&qc=&nc=1&expermode=&nojc=&isAsync=&pn=100&rn=100&gsm=1e"
headers = {
"accept": "text/plain, */*; q=0.01",
"accept-encoding": "gzip, deflate, br, zstd",
"accept-language": "zh-CN,zh;q=0.9",
"connection": "keep-alive",
"cookie": "winWH=%5E6_1560x842; BDIMGISLOGIN=0; BIDUPSID=95F77228242EE62B5E760ED478E739D3; PSTM=1662458358; MCITY=-233%3A; H_PS_PSSID=60271_60677_60682_60360_60749; MAWEBCUID=web_qcjjflMFpajZYpWYDGMJAVLfWvGZIcWcAeRgAHbikKKSPuVTOi; BDSFRCVID=MsDOJeC62lIT9DotIJBSEHtYogxSd2jTH6aoS3tXKcf01TbOLNCWEG0Pvx8g0KuhqIqcogKKy2OTH9jx_gt2OtLms_Abmyl9t66qtf8g0x5; H_BDCLCKID_SF=JRFeoCD5tI03fP36qRro5JF_hGbbetJyaR3XBfJvWJ5TMC_wM6jWLl03yqOqtxQ7bN5y3MO8Mpb-ShPC-tnMLP0IKeF835cmLC7WQlrJ3l02V-nEe-t2yUKJ0tb0tPRMW238oq7mWIT8JM7T555c5MADKnnC5tr8an5J_DQhbnLWeIJ9jjChe5oLDHD8J6nK2Cv2sJnX-KL_HnurMJOUXUI8LNDH2474-gj2LpT2bJRpO-bXhP4BKxjQhRO7ttoy2KTk0JrybnoaDJ8lXxo2yML1Db3OhTvMtg3lBp6oy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902_620537_620590_620873_620924_621089_621350_621323_8000063_8000106_8000115_8000131_8000137_8000149_8000166_8000178_8000176_8000183_8000185_8000204; H_WISE_SIDS=60271_60677_60682_60360_60749; delPer=0; PSINO=6; BDSFRCVID_BFESS=MsDOJeC62lIT9DotIJBSEHtYogxSd2jTH6aoS3tXKcf01TbOLNCWEG0Pvx8g0KuhqIqcogKKy2OTH9jx_gt2OtLms_Abmyl9t66qtf8g0x5; H_BDCLCKID_SF_BFESS=JRFeoCD5tI03fP36qRro5JF_hGbbetJyaR3XBfJvWJ5TMC_wM6jWLl03yqOqtxQ7bN5y3MO8Mpb-ShPC-tnMLP0IKeF835cmLC7WQlrJ3l02V-nEe-t2yUKJ0tb0tPRMW238oq7mWIT8JM7T555c5MADKnnC5tr8an5J_DQhbnLWeIJ9jjChe5oLDHD8J6nK2Cv2sJnX-KL_HnurMJOUXUI8LNDH2474-gj2LpT2bJRpO-bXhP4BKxjQhRO7ttoy2KTk0JrybnoaDJ8lXxo2yML1Db3OhTvMtg3lBp6oyUJoepvo2j5c3Mv-Ml7dKb0HB5nrW4O70RoVJJ4w55D-KJ0EeMtjhTLEtbAfVCKbJID3jtOY5-__-4_tbh_X5-RLfbTC5l7F5l8-h43m0bKa-n0P5hCH0xvJyCOwXq6JaCOxOKQIDT8hyP00MptO0pDf5NLq2xJN3KJmJbL9bT3vQxukjPbM2-biW5KH2MbdfRcW_n3mDxnMX-uyBPQa2RcQf6Pq_tj25DnJh-PGe6_bDjjWDGuqqbo02TT00-5qajrjDCvMK53cy4LdjG5fb6bQf6rJa4b82q51fMTvb-Tz5tIp3-Aq54Rv-j5L-tQL5lLaj6695PvHQfbQ0b5hqP-jW2c3oqjHyR7JOpvwDxnxy5Fq2bnM-Tj9bgJLQM7pKJ6BDKTmj6ja5-5bbN3Ot6IttbFHoIIbtIvVetbpKPP_-P6MXqbRWMT-0bFHWpTmflbofhT_Llbpyb04hUJOQ-0H2Hn7_JjOLKOMohvnb60a3-DgX-TmLMQxtNRqXInjtpvhj-jVKtbobUPU2H59LUk82jbd0---B-bdDtO3Lt5V2t7-5aDqbR3hfIkjXIKLK-oj-D0lejrP; BA_HECTOR=84ahak0g2h0hak2kak002100b3n9i11je4hsp1u; ZFY=HV7JLJmMnrdMPdGIRXthLFpucYNS3H63URYYzhrwveQ:C; BAIDUID_BFESS=33D2F5416D36342A24F9ECF04B523384:FG=1; BDRCVFR[dG2JNJb_ajR]=mk3SLVN4HKm; BDRCVFR[-pGxjrCMryR]=mk3SLVN4HKm; BDRCVFR[tox4WRQ4-Km]=mk3SLVN4HKm; BDORZ=B490B5EBF6F3CD402E515D22BCDA1598; userFrom=ala; indexPageSugList=%5B%22%E7%86%8A%E7%8C%AB%22%2C%22%E9%BD%90%E7%99%BD%E7%9F%B3%E7%9A%84%E8%99%BE%22%2C%22%E5%8B%87%E6%B0%94%20%E4%B9%A6%E6%B3%95%22%2C%22%E7%81%AB%E5%BD%B1%20%20%E8%84%B8%E6%98%AF%E6%97%8B%E6%B6%A1%22%2C%22%E9%BB%91%E4%B8%9D%22%2C%22%E5%AE%9D%E9%A9%AC%E6%91%A9%E6%89%98%E8%BD%A6%E5%A5%B3%E9%AA%91%22%2C%22%E6%91%A9%E6%89%98%E8%BD%A6%E6%A8%A1%E7%89%B9%22%2C%22%E6%91%A9%E6%89%98%E8%BD%A6%E6%91%A9%E6%89%98%22%2C%22%E5%A5%B3%E9%AA%91%22%5D; cleanHistoryStatus=0; ab_sr=1.0.1_Y2VmZmU4MzM3NTExZGU3NWIwODc3OTE1MjRlMDFlOGQzYWViNmZkYTM0MjJhZmY4ZmJiZTJjZDg2OWVkMTVlZTFmZGZiMzNhYjY0NTk1OWRkMDExYWE2NjE0YmExZmJjMGQ0MDk3NTJjYTM4NjdjNDVkODdkMmZiMjYyYWRiMmI4NjY3ODAzMmIxMjM2MGQyYTI1ZDNlZjk0N2Q5ZDZiZWFiM2YxYzNlN2ViOTQ4YTMzZGFkZDhiMmFkNTgzMTliZTBhZjZiM2U2NjZlNjdmMWRmYTRlMzdjYjVkMWU4YjA=",
"referer": "https://image.baidu.com/search/index?tn=baiduimage&ipn=r&ct=201326592&cl=2&lm=&st=-1&fm=result&fr=&sf=1&fmq=1726112770097_R&pv=&ic=&nc=1&z=&hd=&latest=©right=&se=1&showtab=0&fb=0&width=&height=&face=0&istype=2&dyTabStr=&ie=utf-8&ctd=1726112770097%5E00_1903X540&sid=&word=%E7%86%8A%E7%8C%AB",
"sec-ch-ua": '"Not)A;Brand";v="99", "Google Chrome";v="127", "Chromium";v="127"',
"sec-ch-ua-mobile": "?0",
"sec-ch-ua-platform": "Windows",
"sec-fetch-dest": "empty",
"sec-fetch-mode": "cors",
"sec-fetch-site": "same-origin",
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36",
"x-requested-with": "XMLHttpRequest"
}
response = requests.get(url, headers=headers)
# print(response.text)
new_s = response.text.replace("", "123456")
json_data = json.loads(new_s)
# print(json_data)
count = 0
for img_url in json_data.get('data'):
if img_url.get('thumbURL') and count < 20:
self.download_image(img_url.get('thumbURL'),download_path)
count += 1
print('照片下载完成')
剪图片
def resize_image_to_3_4(self,image_path):
'''修改照片尺寸'''
img = Image.open(image_path)
width, height = img.size
target_height = int(width * 4 / 3)
if height != target_height:
if height > target_height:
# 高度大于目标高度,从上下裁剪
top = (height - target_height) // 2
bottom = top + target_height
cropped_img = img.crop((0, top, width, bottom))
else:
# 高度小于目标高度,从左右裁剪
target_width = int(height * 3 / 4)
left = (width - target_width) // 2
right = left + target_width
cropped_img = img.crop((left, 0, right, height))
# new_path = 'D:\\rj\python_code\seer_utils\Datas\picture\\new_tourism.png'
cropped_img.save(image_path)
print(f"裁剪后的尺寸:{cropped_img.size[0]}x{cropped_img.size[1]}")
else:
print("图片已经是 3:4 的比例。")
print(f"当前尺寸:{width}x{height}")
加文字
def draw_text_on_image_word(self, texts, target_image):
try:
img = Image.open(target_image).convert("RGB")
draw = ImageDraw.Draw(img)
try:
font = ImageFont.truetype("simsun.ttc", 60)
bold_font = ImageFont.truetype("simsun.ttc", 60, index=1)
except OSError as e:
print(f"字体加载失败:{e}。使用默认字体。")
font = ImageFont.load_default()
bold_font = ImageFont.load_default()
text1, text2 = texts
text_height = bold_font.size
# 第一列位置
column1_x = img.width - text_height - 10
column1_y = 10
y_pos = column1_y + 5
for char in text1:
# 设置红色填充和加粗字体
draw.text((column1_x + 5, y_pos), char, fill=(255, 0, 0), font=bold_font)
y_pos += text_height
# 第二列位置,往左移一列
column2_x = column1_x - text_height - 10
column2_y = 10
y_pos = column2_y + 5
for char in text2:
# 设置红色填充和加粗字体
draw.text((column2_x + 5, y_pos), char, fill=(255, 0, 0), font=bold_font)
y_pos += text_height
img.save(target_image, format='JPEG')
print('加字完成')
except Exception as e:
print(f"处理图片时出现错误:{e}")
备注:word 入参是 【需要下载的关键词】,download_path 【下载的地址】,image_path【被剪裁图片路径】,texts【给图片添加的字 】