好像是要调PyMuPDF里的zoom参数
import PySimpleGUI as sg
from PIL import Image, ImageTk
from datetime import datetime
def main():
# Set up the drawing colors and line width
draw_color = 'black'
line_width = 2
# Define the layout
layout = [
[sg.Canvas(size=(800, 600), background_color='white', key='CANVAS')],
[sg.Text('Color:'), sg.Button('Black', button_color=('white', 'black'), key='Black'),
sg.Button('Red', button_color=('white', 'red'), key='Red'),
sg.Button('Blue', button_color=('white', 'blue'), key='Blue')],
[sg.Button('Open'), sg.Button('Show Cursor Position'), sg.Button('Clear'), sg.Button('Exit')],
[sg.Text('', key='MESSAGE', size=(20, 1), text_color='green')],
[sg.Text('Cursor Position:', size=(12, 1)), sg.Text('', key='CURSOR_POS', size=(20, 1))],
[sg.Text('Clicks within circle:', size=(20, 1)), sg.Listbox([], size=(50, 5), key='CLICKS', enable_events=True, bind_return_key=True)]
]
# Create the window
window = sg.Window('Paint', layout, finalize=True, resizable=True)
canvas = window['CANVAS'].TKCanvas
# Initialize the starting point for the line and click counter
drag_data = {'x': None, 'y': None}
click_counter = 0
# Function to draw on the canvas
def draw_line(event):
x, y = event.x, event.y
window['CURSOR_POS'].update(f'({x}, {y})')
if drag_data['x'] is not None and drag_data['y'] is not None:
canvas.create_line(drag_data['x'], drag_data['y'], x, y, fill=draw_color, width=line_width)
drag_data['x'], drag_data['y'] = x, y
# Function to reset the starting point for the next line
def start_line(event):
drag_data['x'], drag_data['y'] = event.x, event.y
# Function to show the cursor position on the canvas and check if the cursor is near the center
def show_cursor_position(event):
x, y = event.x, event.y
window['CURSOR_POS'].update(f'({x}, {y})')
# Check if the cursor is near the center (within +/- 10% offset)
center_x, center_y = 400, 300
tolerance = 0.1
if (center_x - center_x * tolerance) <= x <= (center_x + center_x * tolerance) and \
(center_y - center_y * tolerance) <= y <= (center_y + center_y * tolerance):
canvas.create_oval(center_x - 50, center_y - 50, center_x + 50, center_y + 50, outline='green', width=3, tags='center_circle')
window['MESSAGE'].update('You got it!')
else:
canvas.delete('center_circle')
window['MESSAGE'].update('')
# Function to count clicks inside the circle
def count_click(event):
nonlocal click_counter
x, y = event.x, event.y
center_x, center_y = 400, 300
tolerance = 0.1
if (center_x - center_x * tolerance) <= x <= (center_x + center_x * tolerance) and\
(center_y - center_y * tolerance) <= y <= (center_y + center_y * tolerance):
click_counter += 1
timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
window['CLICKS'].update([f'{click_counter}: {timestamp}'] + window['CLICKS'].get_list_values())
# Bind the mouse events to the canvas
canvas.bind('<B1-Motion>', draw_line)
canvas.bind('<ButtonPress-1>', start_line)
canvas.bind('<ButtonPress-1>', count_click, add='+')
canvas.bind('<Motion>', show_cursor_position)
while True:
event, values = window.read()
if event in (sg.WIN_CLOSED, 'Exit'):
break
if event in ('Black', 'Red', 'Blue'):
draw_color = event.lower()
if event == 'Clear':
canvas.delete('all')
drag_data = {'x': None, 'y': None}
if event == 'Open':
image_file = sg.popup_get_file('Select an image file', file_types=(('Image Files', '*.png;*.jpg;*.jpeg;*.bmp;*.gif'),))
if image_file:
img = Image.open(image_file)
img.thumbnail((800, 600))
img_tk = ImageTk.PhotoImage(img)
canvas.create_image(0, 0, anchor='nw', image=img_tk, tags='image')
canvas.image = img_tk
window.close()
if __name__ == '__main__':
main()
pdftoimage
```python
import fitz # PyMuPDF
import io
from PIL import Image
def pdf_page_to_image(pdf_path, page_number, output_path, zoom=2):
# Open the PDF file
pdf_file = fitz.open(pdf_path)
# Access the specific page
pdf_page = pdf_file[page_number]
# Set the zoom level
matrix = fitz.Matrix(zoom, zoom)
# Render the page as a PNG image
png_image = pdf_page.get_pixmap(matrix=matrix, alpha=False)
# Save the image to a file
with open(output_path, 'wb') as f:
f.write(png_image.tobytes('png'))
if __name__ == '__main__':
pdf_path = 'path/to/your/pdf_file.pdf'
page_number = 0 # 0-based index, set the desired page number
output_path = 'path/to/output/image.png'
zoom = 2 # increase for better quality, but larger image sizes
pdf_page_to_image(pdf_path, page_number, output_path, zoom=zoom)
# another method
import io
from PIL import Image
import PyPDF2
pdf_file = open('your_file.pdf', 'rb')
pdf_reader = PyPDF2.PdfFileReader(pdf_file)
page_number = 0 # Choose the page number you want to convert
page = pdf_reader.getPage(page_number)
xObject = page['/Resources']['/XObject'].getObject()
image = None
for obj in xObject:
if xObject[obj]['/Subtype'] == '/Image':
size = (xObject[obj]['/Width'], xObject[obj]['/Height'])
data = xObject[obj].getData()
mode = 'RGB' if xObject[obj]['/ColorSpace'] == '/DeviceRGB' else 'P'
image = Image.frombytes(mode, size, data)
break
if image is not None:
# Increase image resolution
dpi = (300, 300)
image = image.resize((int(image.size[0]*2), int(image.size[1]*2)), resample=Image.BICUBIC)
image.save('output.png', dpi=dpi)
image.show()
pdf_file.close()