python image show()方法的预览问题

本文介绍了解决Windows环境下使用Python PIL库中Image模块的show()函数无法正常显示图片的问题。通过修改ImageShow.py文件中的指定行代码,使得图片能够正确预览。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

 

在windows下面使用PIL中Image的show()函数时,执行下列代码:

       from PIL import Image

       img = Image.open("1.png")

       img.show()

       发现图片不能够正常的显示,windows自带的图片查看器显示图片内容不存在。

       

       C:\Python27\lib\site-packages\PIL\ImageShow.py, 第99行替换为:

       return "start /wait %s && PING 127.0.0.1 -n 5 > NUL && del /f %s" % (file, file)

 

转载于:https://www.cnblogs.com/guohan/p/5520559.html

### 使用Python实现图像预览方法 要通过Python实现图像预览,可以采用多种方法和技术栈。以下是几种常见的解决方案: #### 方法一:基于Matplotlib的静态图像显示 如果目标是在脚本运行环境中快速查看图像内容,则可以使用`matplotlib.pyplot`模块来加载并展示图像。 ```python import matplotlib.pyplot as plt from PIL import Image # 加载图像 image_path = 'example.jpg' # 替换为实际路径 img = Image.open(image_path) # 显示图像 plt.figure(figsize=(8, 6)) plt.axis('off') # 关闭坐标轴 plt.imshow(img) plt.show() ``` 这种方法适用于简单的图像浏览需求[^1]。 --- #### 方法二:基于Flask构建Web端实时图像预览服务 为了支持更灵活的应用场景(如远程访问或动态交互),可借助Flask框架创建一个轻量级服务器用于提供图像预览功能。 ##### 实现步骤说明: 1. **安装依赖包** 需要先安装必要的库,例如`flask`和`Pillow`。 ```bash pip install flask pillow ``` 2. **编写核心代码** 下面是一个完整的示例程序,允许用户上传图片并通过浏览器查看其缩略图版本。 ```python from flask import Flask, request, render_template_string, send_from_directory from werkzeug.utils import secure_filename from PIL import Image import os app = Flask(__name__) UPLOAD_FOLDER = './uploads' THUMBNAIL_SIZE = (200, 200) # 缩略图尺寸设置 if not os.path.exists(UPLOAD_FOLDER): os.makedirs(UPLOAD_FOLDER) @app.route('/') def index(): html_content = ''' <!doctype html> <title>Upload new File</title> <h1>Upload an image to preview:</h1> <form method=post enctype=multipart/form-data> <input type=file name=file> <input type=submit value=Preview> </form> ''' return render_template_string(html_content) @app.route('/upload', methods=['POST']) def upload_file(): file = request.files['file'] filename = secure_filename(file.filename) filepath = os.path.join(UPLOAD_FOLDER, filename) file.save(filepath) img = Image.open(filepath) thumbnail_filepath = f"{os.path.splitext(filepath)[0]}_thumbnail{os.path.splitext(filepath)[1]}" img.thumbnail(THUMBNAIL_SIZE) img.save(thumbnail_filepath) return f'<p><b>{filename}</b> has been uploaded successfully!</p>' \ f'<a href="/preview/{secure_filename(filename)}">View Thumbnail</a>' @app.route('/preview/<path:filename>') def preview_image(filename): original_filepath = os.path.join(UPLOAD_FOLDER, filename) thumbnail_filepath = f"{os.path.splitext(original_filepath)[0]}_thumbnail{os.path.splitext(original_filepath)[1]}" with open(thumbnail_filepath, "rb") as thumb: response_data = thumb.read() mimetype = 'image/jpeg' if filename.lower().endswith('.jpg') or filename.lower().endswith('.jpeg') else 'image/png' return response_data, {'Content-Type': mimetype} if __name__ == '__main__': app.run(debug=True) ``` 此方案不仅能够满足基本的图像预览需求,还提供了额外的功能扩展空间,比如裁剪、旋转或其他编辑操作[^4]。 --- #### 方法三:集成PDF文档内的嵌入式图像预览 当涉及到复杂的数据形式——例如包含图表或者扫描件在内的PDF文件时,可能还需要考虑如何从中抽取特定页面上的图形资源供进一步分析处理。此时推荐结合PyMuPDF(Fitz)完成此类任务。 ```python import fitz # PyMuPDF alias def extract_images(pdf_path): doc = fitz.open(pdf_path) images_list = [] for page_num in range(len(doc)): page = doc.load_page(page_num) image_list = page.get_images(full=True) for img_index, img in enumerate(image_list): xref = img[0] base_image = doc.extract_image(xref) image_bytes = base_image["image"] # Save the extracted image temporarily. temp_img_name = f"temp_{page_num}_{img_index}.png" with open(temp_img_name, "wb") as binary_file: binary_file.write(image_bytes) images_list.append(temp_img_name) return images_list if __name__ == "__main__": pdf_file = "./sample.pdf" # Replace this path accordingly. imgs = extract_images(pdf_file) print(f"Extracted {len(imgs)} images.") ``` 上述片段展示了从指定PDF中检索所有可用插图的过程概述[^2]。 --- #### 总结 以上介绍了三种不同层次上利用Python达成图像可视化目的的技术路线。具体选择取决于项目背景以及最终用户体验期望等因素综合考量决定。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值