当前位置: 首页 > news >正文

【教学类-91-02】20251012笔记本电脑

背景需求

之前做了手机二维码涂色,现在又做一份笔记本电脑涂色。

https://blog.csdn.net/reasonsummer/article/details/153045554?spm=1011.2415.3001.5331https://blog.csdn.net/reasonsummer/article/details/153045554?spm=1011.2415.3001.5331

我想要一个笔记本电脑(只有屏幕和键盘)但是不能变成全部长方形的样子,都是有角度倾斜。

所以我只要“笔记本键盘”

简笔画,卡通。白色背景,一个电脑的键盘。水平摆放,垂直俯视图,长方形

下载代码

'''
20250802通义万相2.2下载通义照片 copy
Python下载通义万相的图片(存在问题,不能停止,只能默认下载300张,删除多余)
星火讯飞,阿夏
200%
20251003
'''import os,time
import pyautogui
import pyperclip
import re
import win32apiimport win32con
import sys
import ctypesimport timename='20251012电脑键盘屏幕'
# 先打开微信num=1def minimize_active_window():try:if sys.platform == 'win32':# 获取当前活动窗口的句柄hwnd = ctypes.windll.user32.GetForegroundWindow()# 最小化窗口ctypes.windll.user32.ShowWindow(hwnd, 6)  # 6 对应 SW_MINIMIZEreturn Trueelse:print("此功能仅支持Windows系统")return Falseexcept Exception as e:print(f"最小化窗口时出错: {e}")return Falseprint("程序运行中...")
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手套\103for 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 timedef minimize_active_window():try:if sys.platform == 'win32':# 获取当前活动窗口的句柄hwnd = ctypes.windll.user32.GetForegroundWindow()# 最小化窗口ctypes.windll.user32.ShowWindow(hwnd, 6)  # 6 对应 SW_MINIMIZEreturn Trueelse:print("此功能仅支持Windows系统")return Falseexcept Exception as e:print(f"最小化窗口时出错: {e}")return Falseprint("程序运行中...")
time.sleep(2)  # 等待2秒,让你有时间切换到VS Code窗口# 尝试最小化活动窗口
if minimize_active_window():print("窗口已最小化")
else:print("无法最小化窗口")

PS处理图片,

'''
把手机二维码背景透明,去掉白边,最大化
AI对话大师,阿夏
2025年10月10日'''import os
from PIL import Image
import numpy as npdef 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_imagedef 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模式,转换为RGBAif 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)# 转换回Imageresult = 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("批量处理完成!处理后的图片保存在输出文件夹中")

屏幕图片总是带着键盘的,所以我还是只做一个一模一样的屏幕

可是每个键盘的大小不同

用文本框形状做一个屏幕。中间会有缝隙。

还是把键盘都统一大小

'''
把电脑键盘背景透明,去掉白边,最大化,统一大小
AI对话大师,阿夏
2025年10月12日'''import os
from PIL import Image
import numpy as npdef 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_imagedef 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模式,转换为RGBAif 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)# 转换回Imageresult = 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("批量处理完成!处理后的图片保存在输出文件夹中")

'''
把电脑屏幕与键盘拼图
Deepseek,阿夏
2025年10月10日
'''
import os
from PIL import Imagedef 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}' 中没有找到图片文件")returnprint(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("批量拼接完成!")

但是屏幕和键盘中间有白色缝隙(键盘边缘线不是水平的)

'''
把电脑做成一页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.14def check_and_repair_image(image_path):"""检查并修复图片文件"""try:with Image.open(image_path) as img:img.verify()  # 验证图片完整性return Trueexcept (IOError, SyntaxError, Exception) as e:print(f"图片文件损坏: {image_path}, 错误: {e}")return Falsedef 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_filesprint('----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 * colsprint(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 // colscol = cell_index % cols# 获取单元格cell = table.cell(row, col)# 清除单元格内容for paragraph in cell.paragraphs:p = paragraph._elementp.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 Trueexcept 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 += 1print(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()# 合并PDFmerger = 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}")# 保存合并后的PDFpdf_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('----程序执行完成------------')

http://www.dtcms.com/a/475014.html

相关文章:

  • 建站的公司浙江建设继续教育网站
  • 医院网站规划方案网站一定备案
  • 医疗器械网站建设策划书成都哪些公司做网站好
  • 【图像处理基石】遥感图像高度信息提取:Python实战全流程+常用库汇总
  • 大型网站要多少钱软文例文 经典软文范例
  • 苏州城乡建设网站电子商务网站建设设计原则
  • 加强普法网站和普法网络集群建设免费空间大的云盘
  • 旅游门户网站方案游戏编程怎么学
  • 网站开发款计入什么科目购物网站排名大全
  • 网站建设需求文章微信里借钱的小程序
  • Python 3.14(πthon)中的最佳新功能和修复内容
  • 【系统分析师】写作框架:信息系统开发方法及应用
  • 模式管理与网络通信管理笔记
  • 创建一个免费网站商城类网站风格
  • 翼城网站建设做音乐头像网站
  • commons-digester3(XML解析框架)
  • 静态网站开发学网站开发看什么书
  • OpenAI Agents 记忆管理示例
  • 网站 做 app开发工具wordpress页眉插件
  • 做网站用的什么服务器建筑模板怎么装
  • 网站后台文档深圳做h5网站设计
  • Git版本控制的讲解及详细的安装流程
  • 珠海市手机网站建设公司邗江区做网站
  • 深圳营销型网站建设服务商网站开发与部署
  • 北京建网站 优帮云建设企业网站地址
  • 邢台住房和城乡建设部网站西安网页设计工资
  • 网站加后台广州建设外贸网站
  • Ape.Volo项目启动前端项目时报错“digital envelope routines::unsupported”
  • 全球算力投资激增与人工智能产业演进:多维度分析与未来展望
  • 网站建设岗位廉政风险防控正规的网页制作