Last active
April 6, 2025 13:36
-
-
Save shhommychon/823e7f590b3cd0e85ae40df6b6c55e2d to your computer and use it in GitHub Desktop.
내가 쓰려고 남겨놓는 PDF 이미지 유틸
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import fitz | |
| import os | |
| import zipfile | |
| # PDF에서 이미지를 추출하여 저장하는 함수 | |
| def extract_images_from_pdf(pdf_path, output_folder, *args, **kwargs): | |
| """PDF 파일에서 이미지 객체들을 추출하여 저장하는 함수 | |
| Args: | |
| pdf_path (str): PDF 파일 경로 | |
| output_folder (str): 이미지를 저장할 폴더 경로 | |
| *args: 추가 위치 인자 | |
| **kwargs: 추가 키워드 인자 | |
| """ | |
| # PDF 파일 열기 | |
| pdf_document = fitz.open(pdf_path) | |
| # PDF의 각 페이지를 순회 | |
| for page_number in range(len(pdf_document)): | |
| page = pdf_document[page_number] | |
| images = page.get_images(full=True) # 페이지 내 모든 이미지 가져오기 | |
| # 현재 페이지의 모든 이미지를 순회 | |
| for img_index, img in enumerate(images): | |
| xref = img[0] # XREF는 이미지 객체 참조를 가리킴 | |
| # 이미지 바이트 추출 | |
| base_image = pdf_document.extract_image(xref) | |
| image_bytes = base_image["image"] | |
| image_ext = base_image["ext"] # 이미지 형식 (예: "png", "jpeg") | |
| # 이미지를 출력 폴더에 저장 | |
| image_filename = f"page{page_number+1:0>3}_img{img_index+1:0>3}.{image_ext}" | |
| image_path = os.path.join(output_folder, image_filename) | |
| with open(image_path, "wb") as image_file: | |
| image_file.write(image_bytes) | |
| print(f"\tSaved image: {image_path}") | |
| # PDF의 각 페이지를 이미지로 렌더링하는 함수 | |
| def render_pdf_to_images(pdf_path, output_folder, dpi=72, *args, **kwargs): | |
| """PDF 파일의 각 페이지를 이미지로 렌더링하여 저장하는 함수 | |
| Args: | |
| pdf_path (str): PDF 파일 경로 | |
| output_folder (str): 이미지를 저장할 폴더 경로 | |
| dpi (int): 출력 이미지의 해상도 (기본값: 72) | |
| *args: 추가 위치 인자 | |
| **kwargs: 추가 키워드 인자 | |
| """ | |
| # PDF 파일 열기 | |
| pdf_document = fitz.open(pdf_path) | |
| # DPI에 기반한 확대/축소 계수 계산 (PyMuPDF의 기본값은 72 DPI) | |
| zoom = dpi / 72 # 스케일 계수 | |
| matrix = fitz.Matrix(zoom, zoom) | |
| # PDF의 각 페이지를 순회 | |
| for page_number in range(len(pdf_document)): | |
| page = pdf_document[page_number] | |
| # 페이지를 픽스맵(이미지)으로 렌더링 | |
| pixmap = page.get_pixmap(matrix=matrix, alpha=False) | |
| # 렌더링된 이미지 저장 | |
| image_filename = f"page{page_number+1:0>3}.png" | |
| image_path = os.path.join(output_folder, image_filename) | |
| pixmap.save(image_path) | |
| print(f"\tRendered page {page_number+1} at {dpi} DPI as image: {image_path}") | |
| # 이미지 파일들을 ZIP으로 압축하는 함수 | |
| def compress_images_to_zip(input_folder, output_zip): | |
| """이미지 파일들을 ZIP 파일로 압축하는 함수 | |
| Args: | |
| input_folder (str): 압축할 이미지 파일들이 있는 폴더 경로 | |
| output_zip (str): 생성할 ZIP 파일 경로 | |
| """ | |
| # 입력 폴더의 이미지 파일들을 정렬된 리스트로 가져오기 | |
| image_files = sorted( | |
| [f for f in os.listdir(input_folder) if os.path.isfile(os.path.join(input_folder, f))], | |
| key=str.lower # 알파벳 순으로 정렬 (대소문자 구분 없음) | |
| ) | |
| # 압축 레벨 0(저장만)으로 ZIP 파일 생성 | |
| with zipfile.ZipFile(output_zip, 'w', zipfile.ZIP_STORED) as zipf: | |
| for image_file in image_files: | |
| image_path = os.path.join(input_folder, image_file) | |
| # 폴더 구조 없이 파일만 ZIP에 추가 | |
| zipf.write(image_path, arcname=image_file) | |
| print(f"\tAdded to ZIP: {image_file}") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment