PdfPig: Transparency is lost when extracting images from PDFs

I am trying to pull out all of the images from a PDF that I have. It is a Pathfinder Adventure Module that I purchased awhile ago. Everything works great, but the only things is that the images lose their transparency when I try and save them, and then the images look awful with a black blocky background.

#pragma warning disable CA1416
using System.Drawing.Imaging;
using System.Drawing;
using UglyToad.PdfPig;

var filePath = args[0];
var destinationFolder = args[1];

using var file = File.Open(filePath, FileMode.Open);
using var pdf = PdfDocument.Open(file);

var encoders = ImageCodecInfo.GetImageDecoders();
var pngEncoder = encoders.First(enc => enc.FormatID == ImageFormat.Png.Guid);

Console.WriteLine("Exporting images...");
foreach (var page in pdf.GetPages())
{
	var images = page.GetImages().ToArray();
	for (int i = 0; i < images.Length; i++)
	{
		images[i].TryGetPng(out var pngBytes);
		using var stream = new MemoryStream(pngBytes ?? images[i].RawBytes.ToArray());
		using var image = Image.FromStream(stream, false, false);
		image.Save($"{destinationFolder}/{page.Number}-{i}.png", pngEncoder, null);
	}
}

Console.WriteLine($"Extracted images from {filePath}");
#pragma warning restore CA1416

About this issue

  • Original URL
  • State: closed
  • Created 3 years ago
  • Comments: 17 (1 by maintainers)

Most upvoted comments

@tcm151 okay great news! Happy to know it now works.

As for the performance, it’s somewhat expected that it takes a bit longer since it’s now processing the workload (whereas before, it was skipping it). However, a 3-4x increase does seem a bit excessive. I plan to review image performance later this year, but for now, the main priority is ensuring that the new feature functions as intended.

I’m closing the issue but feel free to reopen if need be

@racsus I did not have time to work on transparency lately, I was focusing on having all filters implemented (see https://github.com/BobLd/UglyToad.PdfPig.Filters.Jbig2.PdfboxJbig2, https://github.com/BobLd/UglyToad.PdfPig.Filters.Jpx.OpenJpegDotNet, https://github.com/BobLd/UglyToad.PdfPig.Filters.Dct.JpegLibrary)

Now having these implemented, I’ll try to find some time shortly to work on getting masks data