2025-05-08 19:27:05 +10:00

49 lines
1.6 KiB
Python

# pdf-segmented: Generate PDFs using separate compression for foreground and background
# Copyright (C) 2025 Lee Yingtong Li
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
from . import CompressedLayer
from ..util import assert_has_jbig2
from PIL import Image
from dataclasses import dataclass
import os
import subprocess
import tempfile
@dataclass
class JBIG2Layer(CompressedLayer):
data: bytes
def jbig2_compress_layer(layer: Image, tempdir: str) -> JBIG2Layer:
assert_has_jbig2('JBIG2 compression requires jbig2enc')
# Save image to PNG temporarily
_, png_file = tempfile.mkstemp(suffix='.png', dir=tempdir)
try:
layer.save(png_file, format='png')
# Compress using JBIG2
# Passing "-s" uses lossly JBIG2 encoding, so we do not pass this option
jbig2_proc = subprocess.run(['jbig2', '-p', '-v', png_file], cwd=tempdir, check=True, capture_output=True)
jbig2_data = jbig2_proc.stdout
finally:
# Clean up
os.unlink(png_file)
return JBIG2Layer(data=jbig2_data)