背景需求
之前做了手机二维码涂色,现在又做一份笔记本电脑涂色。
https://blog.csdn.net/reasonsummer/article/details/153045554?spm=1011.2415.3001.5331
https://blog.csdn.net/reasonsummer/article/details/153045554?spm=1011.2415.3001.5331
我想要一个笔记本电脑(只有屏幕和键盘)但是不能变成全部长方形的样子,都是有角度倾斜。
所以我只要"笔记本键盘"
简笔画,卡通。白色背景,一个电脑的键盘。水平摆放,垂直俯视图,长方形
下载代码
python
复制代码
'''
20250802通义万相2.2下载通义照片 copy
Python下载通义万相的图片(存在问题,不能停止,只能默认下载300张,删除多余)
星火讯飞,阿夏
200%
20251003
'''
import os,time
import pyautogui
import pyperclip
import re
import win32api
import win32con
import sys
import ctypes
import time
name='20251012电脑键盘屏幕'
# 先打开微信
num=1
def minimize_active_window():
try:
if sys.platform == 'win32':
# 获取当前活动窗口的句柄
hwnd = ctypes.windll.user32.GetForegroundWindow()
# 最小化窗口
ctypes.windll.user32.ShowWindow(hwnd, 6) # 6 对应 SW_MINIMIZE
return True
else:
print("此功能仅支持Windows系统")
return False
except Exception as e:
print(f"最小化窗口时出错: {e}")
return False
print("程序运行中...")
time.sleep(2) # 等待2秒,让你有时间切换到VS Code窗口
# 尝试最小化活动窗口
if minimize_active_window():
print("窗口已最小化")
else:
print("无法最小化窗口")
# 读取文件名称和路径
path=fr'D:\{name}'
os.makedirs(path,exist_ok=True)
# 打开第一图
# pyautogui.moveTo(646, 260)
# pyautogui.click()
# time.sleep(5)D:\20251003钥匙\089
# 预设照片数量D:\20250630手套\103
for i in range(num,num+300):
# 下载按钮
pyautogui.moveTo(1569, 302)
pyautogui.click()
time.sleep(1)
# 点击有,无水印要包月
pyautogui.moveTo(1573, 373)
pyautogui.click()
time.sleep(2)
# 输入图片名称,复制中文内容到剪贴板
name=path+fr'\{i:03}'
pyperclip.copy(name)
# 黏贴图片地址
pyautogui.hotkey('ctrl', 'v')
time.sleep(1)
pyautogui.press('enter')
# # 图片显示需要时间
time.sleep(1)
# 模拟按键"右箭头"
pyautogui.moveTo (989, 628)
pyautogui.click()
time.sleep(2)
# 'left'(左箭头)
# 'up'(上箭头)
# 'down'(下箭头)
import sys
import ctypes
import time
def minimize_active_window():
try:
if sys.platform == 'win32':
# 获取当前活动窗口的句柄
hwnd = ctypes.windll.user32.GetForegroundWindow()
# 最小化窗口
ctypes.windll.user32.ShowWindow(hwnd, 6) # 6 对应 SW_MINIMIZE
return True
else:
print("此功能仅支持Windows系统")
return False
except Exception as e:
print(f"最小化窗口时出错: {e}")
return False
print("程序运行中...")
time.sleep(2) # 等待2秒,让你有时间切换到VS Code窗口
# 尝试最小化活动窗口
if minimize_active_window():
print("窗口已最小化")
else:
print("无法最小化窗口")






PS处理图片,





python
复制代码
'''
把手机二维码背景透明,去掉白边,最大化
AI对话大师,阿夏
2025年10月10日
'''
import os
from PIL import Image
import numpy as np
def crop_transparent_edges(image, margin=10):
"""
裁剪掉图片的透明边缘,并保留指定的间距
参数:
image: PIL Image对象(RGBA模式)
margin: 要保留的间距(磅/像素)
返回:
裁剪后的PIL Image对象
"""
# 转换为numpy数组
data = np.array(image)
# 获取alpha通道
alpha = data[:, :, 3]
# 找到非透明像素的位置
non_transparent = np.where(alpha > 0)
if len(non_transparent[0]) == 0:
# 如果全是透明像素,返回原图
return image
# 获取非透明区域的边界
top = np.min(non_transparent[0])
bottom = np.max(non_transparent[0])
left = np.min(non_transparent[1])
right = np.max(non_transparent[1])
# 添加间距
top = max(0, top - margin)
bottom = min(image.height - 1, bottom + margin)
left = max(0, left - margin)
right = min(image.width - 1, right + margin)
# 裁剪图片
cropped_image = image.crop((left, top, right + 1, bottom + 1))
return cropped_image
def make_background_transparent(image_path, output_path, tolerance=30, margin=10):
"""
将图片背景变为透明并裁剪透明边缘
参数:
image_path: 输入图片路径
output_path: 输出图片路径
tolerance: 颜色容差,控制背景识别的灵敏度
margin: 裁剪后保留的间距(磅/像素)
"""
# 打开图片并转换为RGBA模式
with Image.open(image_path) as img:
# 如果图片不是RGBA模式,转换为RGBA
if img.mode != 'RGBA':
img = img.convert('RGBA')
# 获取图片数据
data = np.array(img)
red, green, blue, alpha = data.T
# 获取左上角像素作为背景色参考(假设图片左上角是背景色)
bg_color = (red[0, 0], green[0, 0], blue[0, 0])
# 创建背景掩码:判断像素是否在背景色容差范围内
mask = (
(red >= bg_color[0] - tolerance) & (red <= bg_color[0] + tolerance) &
(green >= bg_color[1] - tolerance) & (green <= bg_color[1] + tolerance) &
(blue >= bg_color[2] - tolerance) & (blue <= bg_color[2] + tolerance)
)
# 将背景像素的alpha通道设为0(透明)
data[mask.T] = (0, 0, 0, 0)
# 转换回Image
result = Image.fromarray(data)
# 裁剪透明边缘并保留间距
cropped_result = crop_transparent_edges(result, margin)
# 保存结果
cropped_result.save(output_path, 'PNG')
def batch_process_images(input_dir, output_dir, tolerance=30, margin=10):
"""
批量处理文件夹中的所有图片
参数:
input_dir: 输入文件夹路径
output_dir: 输出文件夹路径
tolerance: 颜色容差
margin: 裁剪后保留的间距(磅/像素)
"""
# 创建输出文件夹(如果不存在)
os.makedirs(output_dir, exist_ok=True)
# 支持的图片格式
supported_formats = ('.png', '.jpg', '.jpeg', '.gif', '.bmp')
# 遍历输入文件夹中的所有文件
for filename in os.listdir(input_dir):
# 检查文件是否为支持的图片格式
if filename.lower().endswith(supported_formats):
input_path = os.path.join(input_dir, filename)
# 构建输出文件路径,统一保存为PNG格式以支持透明
output_filename = os.path.splitext(filename)[0] + '.png'
output_path = os.path.join(output_dir, output_filename)
try:
make_background_transparent(input_path, output_path, tolerance, margin)
print(f"已处理: {filename} -> {output_filename}")
except Exception as e:
print(f"处理 {filename} 时出错: {str(e)}")
if __name__ == "__main__":
# 输入文件夹(123)
path = r'D:\20251012电脑键盘屏幕\00键盘\水平'
a = '00原图'
input_directory = path + fr'\{a}'
# 输出文件夹(processed)
output_directory = os.path.join(path, f"{a}透明裁剪")
# 检查输入文件夹是否存在
if not os.path.exists(input_directory):
print(f"错误: 文件夹 '{input_directory}' 不存在")
else:
# 执行批量处理
# tolerance: 背景识别容差(可根据需要调整)
# margin: 保留的间距,这里设为10磅/像素
batch_process_images(input_directory, output_directory, tolerance=30, margin=10)
print("批量处理完成!处理后的图片保存在输出文件夹中")
屏幕图片总是带着键盘的,所以我还是只做一个一模一样的屏幕
可是每个键盘的大小不同
用文本框形状做一个屏幕。中间会有缝隙。
还是把键盘都统一大小
python
复制代码
'''
把电脑键盘背景透明,去掉白边,最大化,统一大小
AI对话大师,阿夏
2025年10月12日
'''
import os
from PIL import Image
import numpy as np
def crop_transparent_edges(image, margin=0):
"""
裁剪掉图片的透明边缘,并保留指定的间距
参数:
image: PIL Image对象(RGBA模式)
margin: 要保留的间距(磅/像素)
返回:
裁剪后的PIL Image对象
"""
# 转换为numpy数组
data = np.array(image)
# 获取alpha通道
alpha = data[:, :, 3]
# 找到非透明像素的位置
non_transparent = np.where(alpha > 0)
if len(non_transparent[0]) == 0:
# 如果全是透明像素,返回原图
return image
# 获取非透明区域的边界
top = np.min(non_transparent[0])
bottom = np.max(non_transparent[0])
left = np.min(non_transparent[1])
right = np.max(non_transparent[1])
# 添加间距
top = max(0, top - margin)
bottom = min(image.height - 1, bottom + margin)
left = max(0, left - margin)
right = min(image.width - 1, right + margin)
# 裁剪图片
cropped_image = image.crop((left, top, right + 1, bottom + 1))
return cropped_image
def make_background_transparent(image_path, output_path, tolerance=30, margin=0):
"""
将图片背景变为透明并裁剪透明边缘
参数:
image_path: 输入图片路径
output_path: 输出图片路径
tolerance: 颜色容差,控制背景识别的灵敏度
margin: 裁剪后保留的间距(磅/像素)
"""
# 打开图片并转换为RGBA模式
with Image.open(image_path) as img:
# 如果图片不是RGBA模式,转换为RGBA
if img.mode != 'RGBA':
img = img.convert('RGBA')
# 获取图片数据
data = np.array(img)
red, green, blue, alpha = data.T
# 获取左上角像素作为背景色参考(假设图片左上角是背景色)
bg_color = (red[0, 0], green[0, 0], blue[0, 0])
# 创建背景掩码:判断像素是否在背景色容差范围内
mask = (
(red >= bg_color[0] - tolerance) & (red <= bg_color[0] + tolerance) &
(green >= bg_color[1] - tolerance) & (green <= bg_color[1] + tolerance) &
(blue >= bg_color[2] - tolerance) & (blue <= bg_color[2] + tolerance)
)
# 将背景像素的alpha通道设为0(透明)
data[mask.T] = (0, 0, 0, 0)
# 转换回Image
result = Image.fromarray(data)
# 裁剪透明边缘并保留间距
cropped_result = crop_transparent_edges(result, margin)
# 保存结果
cropped_result.save(output_path, 'PNG')
def batch_process_images(input_dir, output_dir, tolerance=30, margin=0):
"""
批量处理文件夹中的所有图片
参数:
input_dir: 输入文件夹路径
output_dir: 输出文件夹路径
tolerance: 颜色容差
margin: 裁剪后保留的间距(磅/像素)
"""
# 创建输出文件夹(如果不存在)
os.makedirs(output_dir, exist_ok=True)
# 支持的图片格式
supported_formats = ('.png', '.jpg', '.jpeg', '.gif', '.bmp')
# 遍历输入文件夹中的所有文件
for filename in os.listdir(input_dir):
# 检查文件是否为支持的图片格式
if filename.lower().endswith(supported_formats):
input_path = os.path.join(input_dir, filename)
# 构建输出文件路径,统一保存为PNG格式以支持透明
output_filename = os.path.splitext(filename)[0] + '.png'
output_path = os.path.join(output_dir, output_filename)
try:
make_background_transparent(input_path, output_path, tolerance, margin)
print(f"已处理: {filename} -> {output_filename}")
except Exception as e:
print(f"处理 {filename} 时出错: {str(e)}")
if __name__ == "__main__":
# 输入文件夹(123)
path = r'D:\20251012电脑键盘屏幕\00键盘\水平'
a = '00原图'
input_directory = path + fr'\{a}'
# 输出文件夹(processed)
output_directory = os.path.join(path, f"{a}透明裁剪")
# 检查输入文件夹是否存在
if not os.path.exists(input_directory):
print(f"错误: 文件夹 '{input_directory}' 不存在")
else:
# 执行批量处理
# tolerance: 背景识别容差(可根据需要调整)
# margin: 保留的间距,这里设为10磅/像素
batch_process_images(input_directory, output_directory, tolerance=30, margin=0)
print("批量处理完成!处理后的图片保存在输出文件夹中")


python
复制代码
'''
把电脑屏幕与键盘拼图
Deepseek,阿夏
2025年10月10日
'''
import os
from PIL import Image
def combine_images_stretch(top_image_path, bottom_image_path, output_path, canvas_size=(1594, 1414)):
"""
将两张图片上下拼接(直接拉伸填充)
参数:
top_image_path: 上方图片路径
bottom_image_path: 下方图片路径
output_path: 输出图片路径
canvas_size: 画布大小 (宽度, 高度)
"""
# 打开图片
top_image = Image.open(top_image_path)
bottom_image = Image.open(bottom_image_path)
# 确保图片都是RGBA模式
if top_image.mode != 'RGBA':
top_image = top_image.convert('RGBA')
if bottom_image.mode != 'RGBA':
bottom_image = bottom_image.convert('RGBA')
# 计算每张图片在画布中的高度
single_height = canvas_size[1] // 2
# 直接拉伸图片到画布宽度和指定高度
resized_top = top_image.resize((canvas_size[0], single_height), Image.Resampling.LANCZOS)
resized_bottom = bottom_image.resize((canvas_size[0], single_height), Image.Resampling.LANCZOS)
# 创建新的画布
canvas = Image.new('RGBA', canvas_size, (0, 0, 0, 0))
# 拼接图片
canvas.paste(resized_top, (0, 0))
canvas.paste(resized_bottom, (0, single_height))
# 保存结果
canvas.save(output_path, 'PNG')
def batch_combine_images_stretch(main_image_path, folder_path, output_dir, canvas_size=(1594, 1414)):
"""
批量拼接图片(直接拉伸版本)
"""
os.makedirs(output_dir, exist_ok=True)
supported_formats = ('.png', '.jpg', '.jpeg', '.gif', '.bmp', '.webp')
image_files = [f for f in os.listdir(folder_path)
if f.lower().endswith(supported_formats)]
if not image_files:
print(f"在文件夹 '{folder_path}' 中没有找到图片文件")
return
print(f"找到 {len(image_files)} 张图片进行拼接")
for i, filename in enumerate(image_files, 1):
bottom_image_path = os.path.join(folder_path, filename)
output_filename = f"combined_{i:03d}_{os.path.splitext(filename)[0]}.png"
output_path = os.path.join(output_dir, output_filename)
try:
combine_images_stretch(main_image_path, bottom_image_path, output_path, canvas_size)
print(f"已拼接: {filename} -> {output_filename}")
except Exception as e:
print(f"处理 {filename} 时出错: {str(e)}")
if __name__ == "__main__":
# 设置路径
base_dir = r'D:\20251012电脑键盘屏幕\00键盘\水平'
main_image_path = os.path.join(base_dir, 'screen.png')
bottom_folder = os.path.join(base_dir, '00原图透明裁剪')
output_dir = os.path.join(base_dir, '01拼图')
os.makedirs(output_dir,exist_ok=True)
canvas_size = (1414,1958)
if not os.path.exists(main_image_path):
print(f"错误: 主图片 '{main_image_path}' 不存在")
elif not os.path.exists(bottom_folder):
print(f"错误: 文件夹 '{bottom_folder}' 不存在")
else:
print("开始拼接图片(直接拉伸版本)...")
batch_combine_images_stretch(main_image_path, bottom_folder, output_dir, canvas_size)
print("批量拼接完成!")
但是屏幕和键盘中间有白色缝隙(键盘边缘线不是水平的)
python
复制代码
'''
把电脑做成一页2张
AI对话大师,阿夏
2025年10月10日
'''
'''
把电脑做成一页2张
AI对话大师,阿夏
2025年10月10日
'''
import random
import math
from PIL import Image, ImageDraw, ImageFont
import os
import time
from docx import Document
from docx.shared import Cm
from docx2pdf import convert
from PyPDF2 import PdfMerger
import shutil
# 测试图片59张
path = r'D:\20251012电脑键盘屏幕\00键盘\水平'
# 格子一共有几个
sl = 2
names = f'01拼图'
input_path = path + fr'\{names}'
mb = '电脑'
# 表格有2列
L = 2
# 高度和宽度是多少厘米
h = 19.26
w = 14.14
def check_and_repair_image(image_path):
"""检查并修复图片文件"""
try:
with Image.open(image_path) as img:
img.verify() # 验证图片完整性
return True
except (IOError, SyntaxError, Exception) as e:
print(f"图片文件损坏: {image_path}, 错误: {e}")
return False
def get_valid_image_files(input_path):
"""获取有效的图片文件列表"""
valid_files = []
for file in os.listdir(input_path):
if file.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp', '.gif')):
file_path = os.path.join(input_path, file)
if check_and_repair_image(file_path):
valid_files.append(file_path)
else:
print(f"跳过损坏的图片: {file}")
return valid_files
print('----1、检查图片文件------------')
file_paths = get_valid_image_files(input_path)
print(f"找到 {len(file_paths)} 张有效图片")
if len(file_paths) == 0:
print("没有找到有效的图片文件,程序退出")
exit()
grouped_files = [file_paths[i:i+sl] for i in range(0, len(file_paths), sl)]
print(f"分成 {len(grouped_files)} 组")
print('----2、创建临时文件夹------------')
new_folder = path + r'\零时文件夹'
if os.path.exists(new_folder):
shutil.rmtree(new_folder)
os.makedirs(new_folder, exist_ok=True)
print('----3、插入docx,制作pdf------------')
def create_document_with_images(group, group_index):
"""在已有模板中插入图片"""
try:
# 检查模板文件是否存在
template_path = path + fr'\{mb}.docx'
if not os.path.exists(template_path):
print(f"模板文件不存在: {template_path}")
return False
# 打开模板文档
doc = Document(template_path)
# 检查文档中是否有表格
if len(doc.tables) == 0:
print("模板文档中没有找到表格")
return False
# 获取第一个表格
table = doc.tables[0]
# 计算表格的行列数
rows = len(table.rows)
cols = len(table.columns)
total_cells = rows * cols
print(f"表格大小: {rows}行 x {cols}列, 共{total_cells}个单元格")
# 遍历每个单元格,并插入图片
for cell_index, image_file in enumerate(group):
if not image_file or not os.path.exists(image_file):
print(f"图片文件不存在: {image_file}")
continue
# 如果单元格索引超出表格范围,跳过
if cell_index >= total_cells:
print(f"图片数量超过表格容量,跳过第{cell_index + 1}张图片")
break
# 计算行和列的位置
row = cell_index // cols
col = cell_index % cols
# 获取单元格
cell = table.cell(row, col)
# 清除单元格内容
for paragraph in cell.paragraphs:
p = paragraph._element
p.getparent().remove(p)
# 添加新段落并插入图片
cell_paragraph = cell.add_paragraph()
cell_paragraph.alignment = 1 # 居中对齐
run = cell_paragraph.add_run()
try:
run.add_picture(image_file, width=Cm(w), height=Cm(h))
print(f"成功插入图片到表格位置({row+1},{col+1}): {os.path.basename(image_file)}")
except Exception as e:
print(f"插入图片失败 {image_file}: {e}")
continue
# 保存Word文档
docx_path = os.path.join(new_folder, f'{group_index + 1:03d}.docx')
doc.save(docx_path)
print(f"创建文档成功: {group_index + 1:03d}.docx")
return True
except Exception as e:
print(f"创建文档失败 组{group_index + 1}: {e}")
return False
# 处理每一组图片
success_count = 0
for group_index, group in enumerate(grouped_files):
if create_document_with_images(group, group_index):
success_count += 1
print(f"成功创建 {success_count} 个Word文档")
print('----4、转换为PDF------------')
pdf_files = []
if success_count > 0:
# 获取所有DOCX文件并按数字排序
docx_files = [f for f in os.listdir(new_folder) if f.endswith('.docx')]
docx_files.sort()
for docx_file in docx_files:
docx_path = os.path.join(new_folder, docx_file)
pdf_path = docx_path.replace('.docx', '.pdf')
try:
convert(docx_path, pdf_path)
pdf_files.append(pdf_path)
print(f"转换成功: {docx_file} -> {os.path.basename(pdf_path)}")
time.sleep(0.5) # 短暂等待避免冲突
except Exception as e:
print(f"转换失败 {docx_file}: {e}")
print('----5、合并PDF------------')
if pdf_files:
# 按文件名排序
pdf_files.sort()
# 合并PDF
merger = PdfMerger()
for pdf_file in pdf_files:
try:
merger.append(pdf_file)
print(f"添加PDF: {os.path.basename(pdf_file)}")
except Exception as e:
print(f"添加PDF失败 {pdf_file}: {e}")
# 保存合并后的PDF
pdf_output_path = path + fr'\{mb[:2]}{names[2:4]}{mb}(A4一页{sl}张)共{len(file_paths)}图.pdf'
try:
merger.write(pdf_output_path)
merger.close()
print(f"PDF合并完成: {pdf_output_path}")
except Exception as e:
print(f"PDF合并失败: {e}")
else:
print("没有可合并的PDF文件")
print('----6、清理临时文件------------')
try:
shutil.rmtree(new_folder)
print("临时文件夹已清理")
except Exception as e:
print(f"清理临时文件夹失败: {e}")
print('----程序执行完成------------')


