Preventing Large File Size JPEG-PDF Roundtrip Conversion

Abstract: Prevent JPEG-PDF roundtrip file size inflation by using pdfimages to extract raw binary streams without re-encoding.

Created: 2026-10-09 by
Converting a JPEG to PDF and back often doubles the file size because standard tools re-encode the image data instead of preserving the original stream. This happens when the conversion process applies compression algorithms like DCTDecode or JBIG2Decode, which alter pixel data and increase overhead. To prevent this size inflation, you must use extraction methods that bypass re-encoding and retrieve the raw binary stream directly from the PDF container.

Understanding Why Size Increases

When you convert a JPEG image into a PDF document using common office suites or command-line tools, the software does not simply wrap the existing file. Instead, it parses the image data and embeds it into the PDF structure. During this embedding phase, many converters apply their own compression settings. Even if the input is already compressed JPEG data, the tool might treat it as a new image asset and apply lossy compression again, leading to generational loss and increased file size due to metadata overhead. Furthermore, some PDF generators flatten transparency or change color spaces (e.g., from RGB to CMYK for print) which can significantly alter the byte count. If you then extract the image back out, you are getting this newly encoded version, not the original file. The goal is to find a method where the image inside the PDF is stored as a direct reference to the original bytes without any intermediate processing.

Using Poppler Utilities for Direct Extraction

The most reliable way to extract images without re-encoding is using the Poppler suite, specifically the pdfimages tool. This utility is designed to dump images from PDF files in their native format. However, the behavior depends heavily on how the image was originally embedded. If the PDF contains the JPEG as an uncompressed stream or with minimal filtering, pdfimages can recover the exact bytes. To use it, open your terminal and run the following command:
pdfimages -j input.pdf output_prefix
The -j flag tells the tool to output JPEG images. If the source image was a JPEG, the output will be a .jpg file. Crucially, compare the file size of the extracted file with the original. If they match exactly, the PDF preserved the stream. If the size differs, the PDF had already modified the image during creation. For non-JPEG images stored in the PDF, such as PNGs, you should omit the -j flag to get the raw format:
pdfimages -list input.pdf
This command lists all images in the PDF along with their type and dimensions. It helps you diagnose whether the image is stored as a JPEG, PNG, or other format. If the list shows "JPEG" but the size changed, the issue lies in the initial conversion step, not the extraction.

Alternative Tools for Different Formats

While Poppler is excellent for standard cases, other tools offer different approaches. ImageMagick’s convert command can extract pages, but it almost always re-rasterizes the content. This means it reads the visual pixels and writes a new image file, guaranteeing a change in file size and quality. Therefore, ImageMagick is unsuitable for preserving exact file sizes in round-trip scenarios. Another option is mutool from the MuPDF project. It provides powerful extraction capabilities:
mutool draw -o output.png page_number input.pdf
Like ImageMagick, mutool draw renders the page, which leads to re-encoding. However, mutool clean can sometimes optimize or repair PDF structures without altering image streams, making it useful for cleaning up poorly generated PDFs before extraction.

Preventing Issues at the Source

The best prevention strategy is to ensure the PDF creation step preserves the original image stream. When creating PDFs from images, avoid using high-level office applications that aggressively compress assets. Instead, use tools that allow you to embed images as raw objects. In Linux, you can use img2pdf, a specialized tool that wraps JPEGs into PDFs without re-encoding them. It takes multiple JPEG files and creates a single PDF where each image is stored exactly as it is.
img2pdf image.jpg -o output.pdf
This tool is widely regarded as the gold standard for this task because it guarantees zero-generation loss. The resulting PDF will have a slightly larger size than the JPEG alone due to PDF structural overhead (headers, cross-reference tables), but the image data itself remains identical. When you later extract it with pdfimages -j, you will get the original file back. For Windows and macOS users, similar dedicated utilities exist. On macOS, the built-in sips command or third-party tools like pdfcpu can help manage PDF contents more precisely than default preview apps. On Windows, command-line wrappers for ImageMagick can be configured to disable compression, but this requires careful parameter tuning.

Verifying Integrity

After extraction, always verify the integrity of the recovered file. Use checksums to ensure the bits are identical.
md5sum original.jpg extracted.jpg
If the hashes match, the round-trip was perfect. If they differ, the PDF generation step introduced changes. In such cases, consider switching to img2pdf or configuring your current tool to use "no compression" or "raw" embedding options if available.

Handling Scanned Documents

Scanned documents present a unique challenge. They are often stored as multi-page TIFFs or large JPEGs within the PDF. Extracting these requires handling multi-image objects. pdfimages handles this by naming outputs with indices, such as output_001.jpg, output_002.jpg, etc. If you need to merge them back, ensure the order matches the original sequence. For OCR-heavy PDFs, the image layer might be separate from the text layer. In these cases, extraction yields the visual image, which may still suffer from compression artifacts if the scanner driver applied heavy compression before creating the PDF. Using high-quality scanning profiles that output uncompressed or lightly compressed TIFs before PDF creation is the most effective long-term solution.

Frequently Asked Questions

Why does my PDF file size increase even if I don't add text?

The increase comes from PDF structural overhead, including headers, object streams, and cross-reference tables. Additionally, if the converter re-encodes the image, the new compression algorithm may be less efficient than the original JPEG.

Can I force a PDF generator to not compress images?

Yes, many command-line tools like Ghostscript or img2pdf allow flags to disable compression. For example, img2pdf inherently avoids recompression by design. Check your specific tool's documentation for "embed raw" or "no compression" options.

Is pdfimages safe for sensitive documents?

Yes, pdfimages only extracts image streams; it does not execute code or access metadata beyond what is necessary for identification. However, always review the extracted content for hidden layers or watermarks if security is a concern.

What if the PDF uses JBIG2 compression?

If the PDF uses JBIG2, pdfimages may output a .j2k or raw stream depending on the version. You may need additional tools to decode JBIG2 back to JPEG or PNG. This format is common in fax-based scans and often results in smaller PDFs but complex extraction.

Does converting PDF to JPEG affect text readability?

This question is irrelevant to file size preservation, but note that extracting the image removes all selectable text. If you need both, keep the PDF intact. Use OCR tools if you need searchable text from the extracted image.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More