PDFsharp & MigraDoc Foundation https://forum.pdfsharp.net/ |
|
Compressing images in PDF https://forum.pdfsharp.net/viewtopic.php?f=2&t=1913 |
Page 1 of 1 |
Author: | SaschaS [ Fri Feb 17, 2012 12:02 pm ] |
Post subject: | Compressing images in PDF |
Hi, Iam trying to save .pdf with multiple pages and compressed images as described here: http://forum.pdfsharp.net/viewtopic.php?f=2&t=1825&p=5206&hilit=compress#p5206 In order to use compressed images in my document, I saved the images as compressed .jpeg to a stream. Code: EncoderParameter epQuality = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)30); ImageCodecInfo[] iciCodecs = ImageCodecInfo.GetImageEncoders(); EncoderParameters epParameters = new EncoderParameters(1); epParameters.Param[0] = epQuality; img.Save(stream, iciCodecs.Single((i) => i.MimeType == "image/jpeg"), epParameters); Then I create the XImages from that stream... Code: var xImg = XImage.FromGdiPlusImage(System.Drawing.Image.FromStream(stream); Unfortunately it does not work this way...Am I doing something wrong? Here is my complete source: Code: public void AddImage(System.Drawing.Bitmap img, string path)
{ try { // Compress image first using (var stream = new MemoryStream()) { EncoderParameter epQuality = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)30); ImageCodecInfo[] iciCodecs = ImageCodecInfo.GetImageEncoders(); EncoderParameters epParameters = new EncoderParameters(1); epParameters.Param[0] = epQuality; img.Save(stream, iciCodecs.Single((i) => i.MimeType == "image/jpeg"), epParameters); using (var xImg = XImage.FromGdiPlusImage(System.Drawing.Image.FromStream(stream))) { var page = _document.AddPage(); page.Width = XUnit.FromCentimeter(21).Point; page.Height = XUnit.FromCentimeter(29.7).Point; var rect = new XRect( PixelToPoints(0, img.HorizontalResolution), PixelToPoints(0, img.HorizontalResolution), PixelToPoints(img.Width, img.HorizontalResolution), PixelToPoints(img.Height, img.HorizontalResolution)); using (var gfx = XGraphics.FromPdfPage(page, XGraphicsUnit.Point)) { gfx.DrawImage(XImage.FromGdiPlusImage(img), rect); } } } } catch (System.Exception ex) { } } |
Author: | Thomas Hoevel [ Tue Feb 21, 2012 9:34 am ] |
Post subject: | Re: Compressing images in PDF |
Hi! Your code might work with the GDI+ build, but not with the WPF build. Which build do you use? Save to a temporary file to make it work with the WPF build (PDFsharp copies the original bytes into the PDF file - WPF won't give us the original bytes, so this works for files only, not streams; all other formats are converted to "PDF images", so these will work fine from streams). |
Page 1 of 1 | All times are UTC |
Powered by phpBB® Forum Software © phpBB Group https://www.phpbb.com/ |