PDF转高清图片的方法

好像是要调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()


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要将 PDF 文件换成高清图片,可以使用 Java 库 Apache PDFBox。以下是一个简单的示例代码: ```java import java.io.File; import java.io.IOException; import java.util.List; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.rendering.PDFRenderer; import org.apache.pdfbox.rendering.RenderDestination; import org.apache.pdfbox.rendering.RenderRequest; import org.apache.pdfbox.rendering.RenderResult; import org.apache.pdfbox.rendering.Renderer; import org.apache.pdfbox.rendering.image.BufferedImageRenderer; import org.apache.pdfbox.rendering.image.BufferedImageWriter; import javax.imageio.ImageIO; public class PDFToImageConverter { public static void main(String[] args) throws IOException { String sourcePdf = "path/to/source.pdf"; String destFolder = "path/to/destination/folder"; convertPDFToImages(sourcePdf, destFolder); } public static void convertPDFToImages(String sourcePdf, String destFolder) throws IOException { File file = new File(sourcePdf); PDDocument document = PDDocument.load(file); PDFRenderer pdfRenderer = new PDFRenderer(document); int pageCount = document.getNumberOfPages(); for (int i = 0; i < pageCount; i++) { BufferedImage image = pdfRenderer.renderImageWithDPI(i, 300); File output = new File(destFolder + "/image" + (i + 1) + ".png"); ImageIO.write(image, "png", output); } document.close(); } } ``` 这段代码将 PDF 文件换成多个 PNG 格式的图片,存储在指定的文件夹中。其中,`pdfRenderer.renderImageWithDPI(i, 300)` 方法可以指定图片的 DPI(每英寸点数),这里设置为 300dpi,可以根据需要进行调整。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值