iTextSharp jbig2 encoder - c#

string imgfile = #"C:\users\me\desktop\test.jpg";
Bitmap bmp = new Bitmap(imgfile);
Bitmap bw = ConvertTo1Bpp(bmp); //make b+w
Document doc =
new Document(new iTextSharp.text.Rectangle(bmp.Width, bmp.Height));
PdfWriter.GetInstance(doc,
new System.IO.FileStream(
#"C:\users\me\desktop\test.pdf",
System.IO.FileMode.Create,
System.IO.FileAccess.ReadWrite));
iTextSharp.text.ImgJBIG2 i =
((iTextSharp.text.ImgJBIG2)iTextSharp.text.ImgJBIG2.GetInstance(
bmp, System.Drawing.Imaging.ImageFormat.Bmp));
doc.Open();
doc.Add(i);
doc.Close();
I cant find any good documentation for this with iTextSharp. What I am trying to do is take a Jpeg file and convert it into a pdf embedded as a black and white JBig2 image. The error I get is an InvalidCastException between "iTextSharp.text.ImageRaw" and "iTextSharp.text.ImageJBig2"... is there an alternative to what I have above?
EDIT
ImgJBig2 just represents an image already encoded in JBig2 I believe now. What I am looking for is something that will take a Bitmap and encode it into a BW JBig2 Bitmap that I can put into a Pdf.

As far as I can tell there's not a lot of options for encoding JBig2 and no native free ones.
Windows Imaging SDK ($2500+)
JBIG2 Compression Codec SDK for .NET ($1,800)
jbig2enc (free but c code only)
The last creates a CLI program that you might be able to P/Invoke into or at worst script against so I think that's your best option if you don't want to pay. Does JBIG2 offer such greater compression over other formats?

Related

Save .jpg image in grayscale using C# [duplicate]

We have a system that provides images in 8-bit grayscale either tiff or jpg formats. However, the component we have to process the images expects image to be in 8-bit jpg format.
When I use .Net to save the tiff images as jpg it convets it to 24-bit image.
Is there a way, hopefully simple and fast, to convert 8-bit grayscale tiff images to equivalent jpg?
I tried and tried just to conclude that I'm sorry: .Net library's Bitmap class DOES NOT save JPEG as 8bpp even when explicitly stated and data is in grayscale.
(note: although stated in some places, JPEG format DOES support 8bpp).
At Convert an image to grayscale you may find code snipet to convert to grayscale any Image.
Using that code, I was able to save a 8bpp grayscale Image instance with '.jpeg' extension, but stating ImageFormat.Gif... that's a cheat...
My findings show as solution an entirely different approach.
The FreeImage library offers powerful APIs, including the feature needed to solve your problem.
It's home page is at http://freeimage.sourceforge.net/faq.html
But, I could not easily compile it in my Win2008 + VS 2010 machine.
One ought to sweat a lot to make it run on modern environments.
Some hints on how to accomplish that are found at http://www.sambeauvois.be/blog/2010/05/freeimage-and-x64-projects-yes-you-can/
Good luck!
Image img = Image.FromFile(filePathOriginal);
Bitmap bmp = ConvertTo8bpp(img);
EncoderParameters parameters = new EncoderParameters();
parameters.Param[0] = new EncoderParameter(Encoder.ColorDepth, 8);
bmp.Save(filePathNew, jpgCodec, parameters);
bmp.Dispose();
img.Dispose();
...
private static Bitmap ConvertTo8bpp(Image img) {
var bmp = new Bitmap(img.Width, img.Height, System.Drawing.Imaging.PixelFormat.Format8bppIndexed);
using (var gr = Graphics.FromImage(bmp))
{
gr.DrawImage(img, new Rectangle(0, 0, img.Width, img.Height));
}
return bmp;
}

Set image resolution

I have array of image bytes and I would like to set resolution. Original image can be JPEG, PNG, BMP. Output - PNG. I am using ImageMagic to convert image and do some manipulations.
using (var image = this.Convert(originalImage, height, width))
using (var stream = new MemoryStream())
{
image.Quality = 90;
image.Write(stream, MagickFormat.Png);
return stream.GetBuffer();
}
I tryed to modify image.GetExifProfile, but has no success (at least for PNG images).
I can't use any comandline tool (like ImageMagic or ExifTool) here.
There are 3 exiff tags I need to modify
XResolution
YResolution
ResolutionUnit
I can successfully achieve this with bitmap, but it also resource overhead (need to create MemoryStream ...).
I have found some Pdf specification, but it will consume time to make it all work.
Does any can point me to right direction?
Thanks.

Export Illustrator Vector Image From PDF Using C#

I have a pdf that contains a vector image. I asked the client about it, and they said that they created the image in Illustrator and saved it as a pdf. Is there a way I can extract that image and convert it into a png? I've tried code from the following:
Extract image from PDF using itextsharp
http://www.vbforums.com/showthread.php?530736-2005-Extract-Images-from-a-PDF-file-using-iTextSharp
and a couple of other links that I can't find, but they all don't seem to work. My theory is that they are extracting embedded images like jpegs, bmps, pngs, etc., but what I am faced with is a direct export from illustrator.
Should I be using an illustrator sdk or is there a way for me to do it using itextsharp? Also, I need to convert it to a standard image format, like png, and send the stream to a calling app, so I'll need to be able to grab stream.
You will not be able to do this with iText, since it cannot render or rasterize vector graphics in PDF files.
Option 1:
If a GPL license works for you, you could rasterize your PDF file with Imagemagick+GNU Ghostscript, but AFAIK you will have to write the output into a file in this case.
Command line sample:
convert -density 300 -depth 8 c:\temp\mydoc.pdf c:\temp\myrasterimage.png
There is also a .net wrapper in Codeplex that might work for you: ImageMagick.NET
Option A:
If a commercial library is an option for you, you could try with Amyuni PDF Creator .Net. You can either use the method IacDocument.ExportToJpg, which requires writing into a file, or you can use the method IacDocument.DrawCurrentPage, which can be useful for writing the output into a memory stream.
Sample code for exporting one page using IacDocument.DrawCurrentPage into a memory stream:
const int twipsPerInch = 1440;
const int MM_ISOTROPIC = 7;
private static MemoryStream RasterizePDF(string filePath, int pageIndex, int targetDPI)
{
Amyuni.PDFCreator.IacDocument doc = new Amyuni.PDFCreator.IacDocument();
doc.SetLicenseKey("Evaluation", "07EFC00...77C23E29");
FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
doc.Open(fs, "");
//Get the width and height of the target page
Amyuni.PDFCreator.IacPageFormat format = doc.GetPage(pageIndex).GetPageFormat();
doc.CurrentPageNumber = pageIndex;
//Create Image
Bitmap img = new Bitmap((int)(format.Width * targetDPI / twipsPerInch), (int)(format.Length * targetDPI / twipsPerInch), PixelFormat.Format32bppArgb);
Graphics g = Graphics.FromImage(img);
//set image object background to white
g.Clear(Color.White);
//Get a device context for the grahics object
IntPtr hdc = g.GetHdc();
SetMapMode(hdc, MM_ISOTROPIC);
// set scaling factor
SetWindowExtEx(hdc, twipsPerInch, twipsPerInch, 0);
SetViewportExtEx(hdc, targetDPI, targetDPI, 0);
//draw the contents of the PDF document on to the graphic context
doc.DrawCurrentPage(hdc, false);
//clean up
g.ReleaseHdc(hdc);
g.Dispose();
// Save the bitmap as png into the resulting stream
MemoryStream resultStrm = new MemoryStream();
img.Save(resultStrm, ImageFormat.Png);
//Prepare the stream to be read later on
resultStrm.Position = 0;
}
[System.Runtime.InteropServices.DllImportAttribute("gdi32.dll")]
private static extern int SetMapMode(IntPtr hdc, int MapMode);
[System.Runtime.InteropServices.DllImportAttribute("gdi32.dll")]
private static extern int SetWindowExtEx(IntPtr hdc, int nXExtent, int nYExtent, int not_used);
[System.Runtime.InteropServices.DllImportAttribute("gdi32.dll")]
private static extern int SetViewportExtEx(IntPtr hdc, int nXExtent, int nYExtent, int not_used);
Disclaimer: I currently work as a developer of the library
Modern versions of AI uses PDF as an export format. It's an enhanced form of PDF containing important metadata for Illustrator but ultimately it is PDF.
Yes most PDF packages are aimed at extracting bitmaps as these come in atomic lumps. If your embedded image is vector then it's been dropped in in a format which most will not understand.
Illustrator may have used its own metadata to delimit the image. If this is the case then it will be difficult to extract. However it may have used a PDF analog like the Form XObject. If I was designing Illustrator I would probably do both.
So it probably is possible to extract though perhaps a little tricky. More is impossible to say without being able to see the document.
If you would like to mail your illustrator file to us at ABCpdf we will certainly see what we can suggest. :-)

Convert bitmap from 16bpp to 8bpp in C#

I have a Bitmap with 16bpp. I want to convert that image in my ASP.NET side in a 8bpp image.
I tried a lot of options which I found in the internet but nothing works for me.
I also tried that way: C# Converting 32bpp image to 8bpp
But if I want to save the file, I get the following error:
Exception Details: System.Runtime.InteropServices.ExternalException: A generic error occurred in GDI+.
Line 278: System.Drawing.Image img2 = Convert(bm_resize);//byteArrayToImage(gray);
Line 279:
Line 280: img2.Save(helper+"grey2.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
Line 281: }
Line 282:
Is there any correct way for my problem?
Full Code:
System.Drawing.Image img2 = Convert(bm_resize);
img2.Save(path+"test.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
public static System.Drawing.Image Convert(Bitmap oldbmp)
{
using (MemoryStream ms = new MemoryStream())
{
oldbmp.Save(ms, ImageFormat.Gif);
ms.Position = 0;
return System.Drawing.Image.FromStream(ms);
}
}
The problem is caused by disposing the memory stream before the image is saved.
I believe GDI+ requires the memory stream to persist while you are still working with an Image created from the memory stream.
See the Microsoft Support article.
I use a little helper function to create 1 bpp monochrome bitmaps in .NET. Check out this link, it also works great for 8 bpp
http://www.wischik.com/lu/programmer/1bpp.html
hope this could help!
AForge.Net has a good collection of free (under Lesser GPL License) routines for such changes and a lot more. Conversion of 16bpp to 8bpp is as simple as this.

iTextsharp - PDF file size after inserting image

I'm currently converting some legacy code to create PDF files using iTextSharp. We're creating a largish PDF file that contains a number of images, which I'm inserting like so:
Document doc = new Document(PageSize.A4, 50, 50, 25, 25);
PdfWriter writer = PdfWriter.GetInstance(doc, myStream);
writer.SetFullCompression();
doc.Open();
Image frontCover = iTextSharp.text.Image.GetInstance(#"C:\MyImage.png");
//Scale down from a 96 dpi image to standard itextsharp 72 dpi
frontCover.ScalePercent(75f);
frontCover.SetAbsolutePosition(0, 0);
doc.Add(frontCover);
doc.Close();
Inserting an image (20.8 KB png file) seems to increase the PDF file size by nearly 100 KB.
Is there a way of compressing the image before entry (bearing in mind that this needs to be of reasonable print quality), or of further compressing the entire PDF? Am I even performing any compression in the above example?
The answer appears to have been that you need to set an appropriate version of the PDF spec to target and then set the compression as follows:
PdfWriter writer = PdfWriter.GetInstance(doc, ms);
PdfContentByte contentPlacer;
writer.SetPdfVersion(PdfWriter.PDF_VERSION_1_5);
writer.CompressionLevel = PdfStream.BEST_COMPRESSION;
This has brought my file size down considerably. I also found that PNG's were giving me the best results as regards to final size of document.
I did some experiments this morning. My test image was 800x600 with a file size of 100.69K when saved as a PNG. I inserted this into a PDF (using iTextSharp and the usual GetInstance() method) and the file size increased from 301.71K to 402.63K. I then re-saved my test image as a raw bitmap with file size of 1,440,054. I inserted this into the PDF and the file size went DOWN to 389.81K. Interesting!
I did some research on the web for a possible explanation, and, based on what I found, it looks like iTextSharp does not compress images, but rather it compresses everything with some generic compression. So in other words, the BMP is not actually converted to another file type, it's just compressed very much like you would by ZIPping it. Whatever they're doing, it must be good, for it compressed better than the image with PNG compression. I assume iTextSharp woudld try to compress the PNG but would compress at 0% since it already is compressed. (This is inconsistent with the original author's observations, though... Paddy said his PDF size increased much more than the size of the PNG... not sure what to make of that. I can only go on my own experiments).
Conclusions:
1) I don't need to add some fancy library to my project to convert my (eventual dynamically-created) image to PNG; it actually does better to leave it totally uncompressed and let iTextSharp do all the compression work.
2) I also read stuff on the web about iTextSharp saving images at a certain DPI. I did NOT see this problem... I used ScalePercent() method to scale the bitmap to 1% and the file size was the same and there was no "loss" in the bitmap pixels in the bitmap... this confirms that iTextSharp is doing a simple, nice, generic lossless compression.
It seems that PDF requires the png to be transcoded to something else, jpeg, most probably.
see here: http://forums.adobe.com/message/2952201
The only thing I can think of is to convert png to smallest jpeg first, including scaling down 75%, then importing that file without scaling.
use:
var image = iTextSharp.text.Image.GetInstance(srcImage, ImageFormat.Jpeg);
image.ScaleToFit(document.PageSize.Width, document.PageSize.Height);
//image.ScalePercent(75f);
image.SetAbsolutePosition(0, 0);
document.Add(image);
document.NewPage();

Categories

Resources