ITADN

bs

#83Closedarm3678ice-hue 创建于 2025-10-21
A
arm3678ice-huecommented
import os from pdf2image import convert_from_path from PIL import Image, ImageDraw from fpdf import FPDF # === ตั้งค่าไฟล์ต้นฉบับ === input_pdf = "BASIC BIO 1.pdf" # สร้างชื่อ output อัตโนมัติ เช่น "BASIC BIO 1_cleaned.pdf" base, ext = os.path.splitext(input_pdf) output_pdf = f"{base}_cleaned{ext}" # === แปลง PDF เป็นภาพ === print("🚀 กำลังแปลง PDF เป็นภาพความละเอียดสูง (อาจใช้เวลาสักครู่)...") pages = convert_from_path(input_pdf, dpi=300) cleaned_images = [] for i, page in enumerate(pages): img = page.convert("RGB") draw = ImageDraw.Draw(img) w, h = img.size # ---------- 1️⃣ ลบหัวสไลด์ด้วยแถบสี ---------- top_h = int(h * 0.10) sample_y = top_h + 10 if h > 100 else 50 sample_color = img.getpixel((w // 2, sample_y)) # ปรับความเข้มของสีให้เด่นแต่ยังกลมกลืน darkened = tuple(max(0, int(c * 0.75)) for c in sample_color) draw.rectangle([0, 0, w, top_h], fill=darkened) # ---------- 2️⃣ ตรวจจับและลบโลโก้ BIOLYMPUS ---------- # กำหนดพื้นที่ค้นหามุมขวาบน (20% กว้าง x 12% สูง) logo_area = img.crop((int(w * 0.8), 0, w, int(h * 0.12))) pixels = logo_area.load() # หาค่าเฉลี่ยสีขาวบริเวณนั้น white_pixels = 0 for x in range(logo_area.width): for y in range(logo_area.height): r, g, b = pixels[x, y] if r > 220 and g > 220 and b > 220: # สีเกือบขาว white_pixels += 1 # ถ้ามีสีขาวเยอะ → ถือว่ามีโลโก้อยู่ → ลบทิ้ง if white_pixels > (logo_area.width * logo_area.height * 0.25): draw.rectangle([int(w * 0.75), 0, w, int(h * 0.12)], fill=darkened) # ---------- บันทึกภาพ ---------- temp_path = f"cleaned_page_{i+1}.png" img.save(temp_path, "PNG") cleaned_images.append(temp_path) print(f"✅ หน้า {i+1}/{len(pages)} แก้ไขเรียบร้อย") # ---------- 3️⃣ รวมกลับเป็น PDF ---------- print("📄 กำลังรวมกลับเป็นไฟล์ PDF คุณภาพสูง ...") pdf = FPDF(unit="pt", format=[595.27, 841.89]) # A4 ขนาดมาตรฐาน for img_path in cleaned_images: pdf.add_page() pdf.image(img_path, 0, 0, 595.27, 841.89) pdf.output(output_pdf, "F") # ---------- ลบไฟล์ภาพชั่วคราว ---------- for f in cleaned_images: os.remove(f) print(f"\n🎉 เสร็จสมบูรณ์! ไฟล์ใหม่ถูกสร้างแล้ว: {output_pdf}") [ <!-- Failed to upload "BASIC BIO 1.pdf" --> ](url)
关闭于 2025-10-21 0 条评论