/** * Generate an object that contains an CMS Compressed Data */ public CmsCompressedData Generate( CmsProcessable content, string compressionOid) { AlgorithmIdentifier comAlgId; Asn1OctetString comOcts; try { MemoryStream bOut = new MemoryStream(); ZDeflaterOutputStream zOut = new ZDeflaterOutputStream(bOut); content.Write(zOut); zOut.Close(); comAlgId = new AlgorithmIdentifier( new DerObjectIdentifier(compressionOid), null); comOcts = new BerOctetString(bOut.ToArray()); } catch (IOException e) { throw new CmsException("exception encoding data.", e); } ContentInfo comContent = new ContentInfo(CmsObjectIdentifiers.Data, comOcts); ContentInfo contentInfo = new ContentInfo( CmsObjectIdentifiers.CompressedData, new CompressedData(comAlgId, comContent)); return(new CmsCompressedData(contentInfo)); }
static Image ProcessExtraSamples(ZDeflaterOutputStream zip, ZDeflaterOutputStream mzip, byte[] outBuf, int samplePerPixel, int bitsPerSample, int width, int height) { if (bitsPerSample == 8) { byte[] mask = new byte[width * height]; int mptr = 0; int optr = 0; int total = width * height * samplePerPixel; for (int k = 0; k < total; k += samplePerPixel) { for (int s = 0; s < samplePerPixel - 1; ++s) { outBuf[optr++] = outBuf[k + s]; } mask[mptr++] = outBuf[k + samplePerPixel - 1]; } zip.Write(outBuf, 0, optr); mzip.Write(mask, 0, mptr); } else { throw new ArgumentException(MessageLocalization.GetComposedMessage("extra.samples.are.not.supported")); } return(null); }
internal CmsCompressedOutputStream( ZDeflaterOutputStream outStream, BerSequenceGenerator sGen, BerSequenceGenerator cGen, BerSequenceGenerator eiGen) { _out = outStream; _sGen = sGen; _cGen = cGen; _eiGen = eiGen; }
public static void FlateEncode(Stream rawData, Stream result) { ZDeflaterOutputStream stream = new ZDeflaterOutputStream(result); byte[] buffer = new byte[0x400]; int count = 0; while ((count = rawData.Read(buffer, 0, buffer.Length)) > 0) { stream.Write(buffer, 0, count); } stream.Finish(); }
/// <summary> /// Encodes the inner. /// </summary> /// <param name="rawData">The raw data.</param> /// <param name="result">The result.</param> /// <param name="options">The options.</param> protected override void EncodeInner(Stream rawData, Stream result, Dictionary <PdfName, PdfObjectBase> options) { ZDeflaterOutputStream stream = new ZDeflaterOutputStream(result); byte[] buffer = new byte[0x400]; int count = 0; while ((count = rawData.Read(buffer, 0, buffer.Length)) > 0) { stream.Write(buffer, 0, count); } stream.Finish(); }
public void WriteData(byte[] data, int stride) { MemoryStream stream = new MemoryStream(); ZDeflaterOutputStream zip = new ZDeflaterOutputStream(stream, 5); for (int k = 0; k < data.Length; k += stride) { zip.WriteByte(0); zip.Write(data, k, stride); } zip.Finish(); WriteChunk(IDAT, stream.ToArray()); }
virtual public void WriteIccProfile(byte[] data) { MemoryStream stream = new MemoryStream(); stream.WriteByte((byte)'I'); stream.WriteByte((byte)'C'); stream.WriteByte((byte)'C'); stream.WriteByte(0); stream.WriteByte(0); ZDeflaterOutputStream zip = new ZDeflaterOutputStream(stream, 5); zip.Write(data, 0, data.Length); zip.Close(); WriteChunk(iCCP, stream.ToArray()); }
/**Sets the data associated with the stream * @param data raw data, decrypted and uncompressed. */ public void SetData(byte[] data) { Remove(PdfName.FILTER); this.offset = -1; if (Document.Compress) { MemoryStream stream = new MemoryStream(); ZDeflaterOutputStream zip = new ZDeflaterOutputStream(stream); zip.Write(data, 0, data.Length); zip.Close(); bytes = stream.ToArray(); Put(PdfName.FILTER, PdfName.FLATEDECODE); } else { bytes = data; } Length = bytes.Length; }
/// <summary> /// Creates a new PDF stream object that will replace a stream /// in a existing PDF file. /// @since 2.1.3 (replacing the existing constructor without param compressionLevel) /// </summary> /// <param name="reader">the reader that holds the existing PDF</param> /// <param name="conts">the new content</param> /// <param name="compressionLevel">the compression level for the content</param> public PrStream(PdfReader reader, byte[] conts, int compressionLevel) { this.reader = reader; offset = -1; if (Document.Compress) { MemoryStream stream = new MemoryStream(); ZDeflaterOutputStream zip = new ZDeflaterOutputStream(stream, compressionLevel); zip.Write(conts, 0, conts.Length); zip.Close(); Bytes = stream.ToArray(); Put(PdfName.Filter, PdfName.Flatedecode); } else { Bytes = conts; } Length = Bytes.Length; }
/** * Creates a new PDF stream object that will replace a stream * in a existing PDF file. * @param reader the reader that holds the existing PDF * @param conts the new content * @param compressionLevel the compression level for the content * @since 2.1.3 (replacing the existing constructor without param compressionLevel) */ public PRStream(PdfReader reader, byte[] conts, int compressionLevel) { this.reader = reader; this.offset = -1; if (Document.Compress) { MemoryStream stream = new MemoryStream(); ZDeflaterOutputStream zip = new ZDeflaterOutputStream(stream, compressionLevel); zip.Write(conts, 0, conts.Length); zip.Close(); bytes = stream.ToArray(); Put(PdfName.FILTER, PdfName.FLATEDECODE); } else { bytes = conts; } Length = bytes.Length; }
/// <summary> /// Sets the data associated with the stream, either compressed or /// uncompressed. Note that the data will never be compressed if /// Document.compress is set to false. /// @since iText 2.1.3 /// </summary> /// <param name="data">raw data, decrypted and uncompressed.</param> /// <param name="compress">true if you want the stream to be compresssed.</param> /// <param name="compressionLevel">a value between -1 and 9 (ignored if compress == false)</param> public void SetData(byte[] data, bool compress, int compressionLevel) { Remove(PdfName.Filter); offset = -1; if (Document.Compress && compress) { MemoryStream stream = new MemoryStream(); ZDeflaterOutputStream zip = new ZDeflaterOutputStream(stream, compressionLevel); zip.Write(data, 0, data.Length); zip.Close(); Bytes = stream.ToArray(); CompressionLevel = compressionLevel; Put(PdfName.Filter, PdfName.Flatedecode); } else { Bytes = data; } Length = Bytes.Length; }
virtual public void WriteData(byte[] data, int stride) { MemoryStream stream = new MemoryStream(); ZDeflaterOutputStream zip = new ZDeflaterOutputStream(stream, 5); int k; for (k = 0; k < data.Length - stride; k += stride) { zip.WriteByte(0); zip.Write(data, k, stride); } int remaining = data.Length - k; if (remaining > 0) { zip.WriteByte(0); zip.Write(data, k, remaining); } zip.Close(); WriteChunk(IDAT, stream.ToArray()); }
protected static Image GetTiffImageColor(TIFFDirectory dir, RandomAccessFileOrArray s) { int predictor = 1; TIFFLZWDecoder lzwDecoder = null; int compression = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_COMPRESSION); switch (compression) { case TIFFConstants.COMPRESSION_NONE: case TIFFConstants.COMPRESSION_LZW: case TIFFConstants.COMPRESSION_PACKBITS: case TIFFConstants.COMPRESSION_DEFLATE: case TIFFConstants.COMPRESSION_ADOBE_DEFLATE: case TIFFConstants.COMPRESSION_OJPEG: case TIFFConstants.COMPRESSION_JPEG: break; default: throw new ArgumentException(MessageLocalization.GetComposedMessage("the.compression.1.is.not.supported", compression)); } int photometric = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_PHOTOMETRIC); switch (photometric) { case TIFFConstants.PHOTOMETRIC_MINISWHITE: case TIFFConstants.PHOTOMETRIC_MINISBLACK: case TIFFConstants.PHOTOMETRIC_RGB: case TIFFConstants.PHOTOMETRIC_SEPARATED: case TIFFConstants.PHOTOMETRIC_PALETTE: break; default: if (compression != TIFFConstants.COMPRESSION_OJPEG && compression != TIFFConstants.COMPRESSION_JPEG) { throw new ArgumentException(MessageLocalization.GetComposedMessage("the.photometric.1.is.not.supported", photometric)); } break; } float rotation = 0; if (dir.IsTagPresent(TIFFConstants.TIFFTAG_ORIENTATION)) { int rot = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_ORIENTATION); if (rot == TIFFConstants.ORIENTATION_BOTRIGHT || rot == TIFFConstants.ORIENTATION_BOTLEFT) { rotation = (float)Math.PI; } else if (rot == TIFFConstants.ORIENTATION_LEFTTOP || rot == TIFFConstants.ORIENTATION_LEFTBOT) { rotation = (float)(Math.PI / 2.0); } else if (rot == TIFFConstants.ORIENTATION_RIGHTTOP || rot == TIFFConstants.ORIENTATION_RIGHTBOT) { rotation = -(float)(Math.PI / 2.0); } } if (dir.IsTagPresent(TIFFConstants.TIFFTAG_PLANARCONFIG) && dir.GetFieldAsLong(TIFFConstants.TIFFTAG_PLANARCONFIG) == TIFFConstants.PLANARCONFIG_SEPARATE) { throw new ArgumentException(MessageLocalization.GetComposedMessage("planar.images.are.not.supported")); } int extraSamples = 0; if (dir.IsTagPresent(TIFFConstants.TIFFTAG_EXTRASAMPLES)) { extraSamples = 1; } int samplePerPixel = 1; if (dir.IsTagPresent(TIFFConstants.TIFFTAG_SAMPLESPERPIXEL)) // 1,3,4 { samplePerPixel = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_SAMPLESPERPIXEL); } int bitsPerSample = 1; if (dir.IsTagPresent(TIFFConstants.TIFFTAG_BITSPERSAMPLE)) { bitsPerSample = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_BITSPERSAMPLE); } switch (bitsPerSample) { case 1: case 2: case 4: case 8: break; default: throw new ArgumentException(MessageLocalization.GetComposedMessage("bits.per.sample.1.is.not.supported", bitsPerSample)); } Image img = null; int h = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_IMAGELENGTH); int w = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_IMAGEWIDTH); int dpiX = 0; int dpiY = 0; int resolutionUnit = TIFFConstants.RESUNIT_INCH; if (dir.IsTagPresent(TIFFConstants.TIFFTAG_RESOLUTIONUNIT)) { resolutionUnit = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_RESOLUTIONUNIT); } dpiX = GetDpi(dir.GetField(TIFFConstants.TIFFTAG_XRESOLUTION), resolutionUnit); dpiY = GetDpi(dir.GetField(TIFFConstants.TIFFTAG_YRESOLUTION), resolutionUnit); int fillOrder = 1; bool reverse = false; TIFFField fillOrderField = dir.GetField(TIFFConstants.TIFFTAG_FILLORDER); if (fillOrderField != null) { fillOrder = fillOrderField.GetAsInt(0); } reverse = (fillOrder == TIFFConstants.FILLORDER_LSB2MSB); int rowsStrip = h; if (dir.IsTagPresent(TIFFConstants.TIFFTAG_ROWSPERSTRIP)) //another hack for broken tiffs { rowsStrip = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_ROWSPERSTRIP); } if (rowsStrip <= 0 || rowsStrip > h) { rowsStrip = h; } long[] offset = GetArrayLongShort(dir, TIFFConstants.TIFFTAG_STRIPOFFSETS); long[] size = GetArrayLongShort(dir, TIFFConstants.TIFFTAG_STRIPBYTECOUNTS); if ((size == null || (size.Length == 1 && (size[0] == 0 || size[0] + offset[0] > s.Length))) && h == rowsStrip) // some TIFF producers are really lousy, so... { size = new long[] { s.Length - (int)offset[0] }; } if (compression == TIFFConstants.COMPRESSION_LZW || compression == TIFFConstants.COMPRESSION_DEFLATE || compression == TIFFConstants.COMPRESSION_ADOBE_DEFLATE) { TIFFField predictorField = dir.GetField(TIFFConstants.TIFFTAG_PREDICTOR); if (predictorField != null) { predictor = predictorField.GetAsInt(0); if (predictor != 1 && predictor != 2) { throw new Exception(MessageLocalization.GetComposedMessage("illegal.value.for.predictor.in.tiff.file")); } if (predictor == 2 && bitsPerSample != 8) { throw new Exception(MessageLocalization.GetComposedMessage("1.bit.samples.are.not.supported.for.horizontal.differencing.predictor", bitsPerSample)); } } } if (compression == TIFFConstants.COMPRESSION_LZW) { lzwDecoder = new TIFFLZWDecoder(w, predictor, samplePerPixel); } int rowsLeft = h; MemoryStream stream = null; MemoryStream mstream = null; ZDeflaterOutputStream zip = null; ZDeflaterOutputStream mzip = null; if (extraSamples > 0) { mstream = new MemoryStream(); mzip = new ZDeflaterOutputStream(mstream); } CCITTG4Encoder g4 = null; if (bitsPerSample == 1 && samplePerPixel == 1 && photometric != TIFFConstants.PHOTOMETRIC_PALETTE) { g4 = new CCITTG4Encoder(w); } else { stream = new MemoryStream(); if (compression != TIFFConstants.COMPRESSION_OJPEG && compression != TIFFConstants.COMPRESSION_JPEG) { zip = new ZDeflaterOutputStream(stream); } } if (compression == TIFFConstants.COMPRESSION_OJPEG) { // Assume that the TIFFTAG_JPEGIFBYTECOUNT tag is optional, since it's obsolete and // is often missing if ((!dir.IsTagPresent(TIFFConstants.TIFFTAG_JPEGIFOFFSET))) { throw new IOException(MessageLocalization.GetComposedMessage("missing.tag.s.for.ojpeg.compression")); } int jpegOffset = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_JPEGIFOFFSET); int jpegLength = (int)s.Length - jpegOffset; if (dir.IsTagPresent(TIFFConstants.TIFFTAG_JPEGIFBYTECOUNT)) { jpegLength = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_JPEGIFBYTECOUNT) + (int)size[0]; } byte[] jpeg = new byte[Math.Min(jpegLength, s.Length - jpegOffset)]; int posFilePointer = (int)s.FilePointer; posFilePointer += jpegOffset; s.Seek(posFilePointer); s.ReadFully(jpeg); // if quantization and/or Huffman tables are stored separately in the tiff, // we need to add them to the jpeg data TIFFField jpegtables = dir.GetField(TIFFConstants.TIFFTAG_JPEGTABLES); if (jpegtables != null) { byte[] temp = jpegtables.GetAsBytes(); int tableoffset = 0; int tablelength = temp.Length; // remove FFD8 from start if (temp[0] == (byte)0xFF && temp[1] == (byte)0xD8) { tableoffset = 2; tablelength -= 2; } // remove FFD9 from end if (temp[temp.Length - 2] == (byte)0xFF && temp[temp.Length - 1] == (byte)0xD9) { tablelength -= 2; } byte[] tables = new byte[tablelength]; Array.Copy(temp, tableoffset, tables, 0, tablelength); // TODO insert after JFIF header, instead of at the start byte[] jpegwithtables = new byte[jpeg.Length + tables.Length]; Array.Copy(jpeg, 0, jpegwithtables, 0, 2); Array.Copy(tables, 0, jpegwithtables, 2, tables.Length); Array.Copy(jpeg, 2, jpegwithtables, tables.Length + 2, jpeg.Length - 2); jpeg = jpegwithtables; } img = new Jpeg(jpeg); } else if (compression == TIFFConstants.COMPRESSION_JPEG) { if (size.Length > 1) { throw new IOException(MessageLocalization.GetComposedMessage("compression.jpeg.is.only.supported.with.a.single.strip.this.image.has.1.strips", size.Length)); } byte[] jpeg = new byte[(int)size[0]]; s.Seek(offset[0]); s.ReadFully(jpeg); img = new Jpeg(jpeg); } else { for (int k = 0; k < offset.Length; ++k) { byte[] im = new byte[(int)size[k]]; s.Seek(offset[k]); s.ReadFully(im); int height = Math.Min(rowsStrip, rowsLeft); byte[] outBuf = null; if (compression != TIFFConstants.COMPRESSION_NONE) { outBuf = new byte[(w * bitsPerSample * samplePerPixel + 7) / 8 * height]; } if (reverse) { TIFFFaxDecoder.ReverseBits(im); } switch (compression) { case TIFFConstants.COMPRESSION_DEFLATE: case TIFFConstants.COMPRESSION_ADOBE_DEFLATE: Inflate(im, outBuf); ApplyPredictor(outBuf, predictor, w, height, samplePerPixel); break; case TIFFConstants.COMPRESSION_NONE: outBuf = im; break; case TIFFConstants.COMPRESSION_PACKBITS: DecodePackbits(im, outBuf); break; case TIFFConstants.COMPRESSION_LZW: lzwDecoder.Decode(im, outBuf, height); break; } if (bitsPerSample == 1 && samplePerPixel == 1 && photometric != TIFFConstants.PHOTOMETRIC_PALETTE) { g4.Fax4Encode(outBuf, height); } else { if (extraSamples > 0) { ProcessExtraSamples(zip, mzip, outBuf, samplePerPixel, bitsPerSample, w, height); } else { zip.Write(outBuf, 0, outBuf.Length); } } rowsLeft -= rowsStrip; } if (bitsPerSample == 1 && samplePerPixel == 1 && photometric != TIFFConstants.PHOTOMETRIC_PALETTE) { img = Image.GetInstance(w, h, false, Image.CCITTG4, photometric == TIFFConstants.PHOTOMETRIC_MINISBLACK ? Image.CCITT_BLACKIS1 : 0, g4.Close()); } else { zip.Close(); img = new ImgRaw(w, h, samplePerPixel - extraSamples, bitsPerSample, stream.ToArray()); img.Deflated = true; } } img.SetDpi(dpiX, dpiY); if (compression != TIFFConstants.COMPRESSION_OJPEG && compression != TIFFConstants.COMPRESSION_JPEG) { if (dir.IsTagPresent(TIFFConstants.TIFFTAG_ICCPROFILE)) { try { TIFFField fd = dir.GetField(TIFFConstants.TIFFTAG_ICCPROFILE); ICC_Profile icc_prof = ICC_Profile.GetInstance(fd.GetAsBytes()); if (samplePerPixel - extraSamples == icc_prof.NumComponents) { img.TagICC = icc_prof; } } catch { //empty } } if (dir.IsTagPresent(TIFFConstants.TIFFTAG_COLORMAP)) { TIFFField fd = dir.GetField(TIFFConstants.TIFFTAG_COLORMAP); char[] rgb = fd.GetAsChars(); byte[] palette = new byte[rgb.Length]; int gColor = rgb.Length / 3; int bColor = gColor * 2; for (int k = 0; k < gColor; ++k) { palette[k * 3] = (byte)(rgb[k] >> 8); palette[k * 3 + 1] = (byte)(rgb[k + gColor] >> 8); palette[k * 3 + 2] = (byte)(rgb[k + bColor] >> 8); } // Colormap components are supposed to go from 0 to 655535 but, // as usually, some tiff producers just put values from 0 to 255. // Let's check for these broken tiffs. bool colormapBroken = true; for (int k = 0; k < palette.Length; ++k) { if (palette[k] != 0) { colormapBroken = false; break; } } if (colormapBroken) { for (int k = 0; k < gColor; ++k) { palette[k * 3] = (byte)rgb[k]; palette[k * 3 + 1] = (byte)rgb[k + gColor]; palette[k * 3 + 2] = (byte)rgb[k + bColor]; } } PdfArray indexed = new PdfArray(); indexed.Add(PdfName.INDEXED); indexed.Add(PdfName.DEVICERGB); indexed.Add(new PdfNumber(gColor - 1)); indexed.Add(new PdfString(palette)); PdfDictionary additional = new PdfDictionary(); additional.Put(PdfName.COLORSPACE, indexed); img.Additional = additional; } img.OriginalType = Image.ORIGINAL_TIFF; } if (photometric == TIFFConstants.PHOTOMETRIC_MINISWHITE) { img.Inverted = true; } if (rotation != 0) { img.InitialRotation = rotation; } if (extraSamples > 0) { mzip.Close(); Image mimg = Image.GetInstance(w, h, 1, bitsPerSample, mstream.ToArray()); mimg.MakeMask(); mimg.Deflated = true; img.ImageMask = mimg; } return(img); }
/** * @see com.lowagie.text.pdf.PdfDictionary#toPdf(com.lowagie.text.pdf.PdfWriter, java.io.OutputStream) */ public override void ToPdf(PdfWriter writer, Stream os) { if (inputStream != null && compressed) { Put(PdfName.FILTER, PdfName.FLATEDECODE); } PdfEncryption crypto = null; if (writer != null) { crypto = writer.Encryption; } if (crypto != null) { PdfObject filter = Get(PdfName.FILTER); if (filter != null) { if (PdfName.CRYPT.Equals(filter)) { crypto = null; } else if (filter.IsArray()) { PdfArray a = (PdfArray)filter; if (!a.IsEmpty() && PdfName.CRYPT.Equals(a[0])) { crypto = null; } } } } if (crypto != null && crypto.IsEmbeddedFilesOnly()) { PdfArray filter = new PdfArray(); PdfArray decodeparms = new PdfArray(); PdfDictionary crypt = new PdfDictionary(); crypt.Put(PdfName.NAME, PdfName.STDCF); filter.Add(PdfName.CRYPT); decodeparms.Add(crypt); if (compressed) { filter.Add(PdfName.FLATEDECODE); decodeparms.Add(new PdfNull()); } Put(PdfName.FILTER, filter); Put(PdfName.DECODEPARMS, decodeparms); } PdfObject nn = Get(PdfName.LENGTH); if (crypto != null && nn != null && nn.IsNumber()) { int sz = ((PdfNumber)nn).IntValue; Put(PdfName.LENGTH, new PdfNumber(crypto.CalculateStreamSize(sz))); SuperToPdf(writer, os); Put(PdfName.LENGTH, nn); } else { SuperToPdf(writer, os); } os.Write(STARTSTREAM, 0, STARTSTREAM.Length); if (inputStream != null) { rawLength = 0; ZDeflaterOutputStream def = null; OutputStreamCounter osc = new OutputStreamCounter(os); OutputStreamEncryption ose = null; Stream fout = osc; if (crypto != null) { fout = ose = crypto.GetEncryptionStream(fout); } if (compressed) { fout = def = new ZDeflaterOutputStream(fout, compressionLevel); } byte[] buf = new byte[4192]; while (true) { int n = inputStream.Read(buf, 0, buf.Length); if (n <= 0) { break; } fout.Write(buf, 0, n); rawLength += n; } if (def != null) { def.Finish(); } if (ose != null) { ose.Finish(); } inputStreamLength = (int)osc.Counter; } else { if (crypto == null) { if (streamBytes != null) { streamBytes.WriteTo(os); } else { os.Write(bytes, 0, bytes.Length); } } else { byte[] b; if (streamBytes != null) { b = crypto.EncryptByteArray(streamBytes.ToArray()); } else { b = crypto.EncryptByteArray(bytes); } os.Write(b, 0, b.Length); } } os.Write(ENDSTREAM, 0, ENDSTREAM.Length); }
public override void ToPdf(PdfWriter writer, Stream os) { if (inputStream != null && compressed) { Put(PdfName.FILTER, PdfName.FLATEDECODE); } PdfEncryption crypto = null; if (writer != null) { crypto = writer.Encryption; } if (crypto != null) { PdfObject filter = Get(PdfName.FILTER); if (filter != null) { if (PdfName.CRYPT.Equals(filter)) { crypto = null; } else if (filter.IsArray()) { PdfArray a = ((PdfArray)filter); if (a.Size > 0 && PdfName.CRYPT.Equals(a[0])) { crypto = null; } } } } PdfObject nn = Get(PdfName.LENGTH); if (crypto != null && nn != null && nn.IsNumber()) { int sz = ((PdfNumber)nn).IntValue; Put(PdfName.LENGTH, new PdfNumber(crypto.CalculateStreamSize(sz))); SuperToPdf(writer, os); Put(PdfName.LENGTH, nn); } else { SuperToPdf(writer, os); } PdfWriter.CheckPdfIsoConformance(writer, PdfIsoKeys.PDFISOKEY_STREAM, this); os.Write(STARTSTREAM, 0, STARTSTREAM.Length); if (inputStream != null) { rawLength = 0; ZDeflaterOutputStream def = null; OutputStreamCounter osc = new OutputStreamCounter(os); OutputStreamEncryption ose = null; Stream fout = osc; if (crypto != null && !crypto.IsEmbeddedFilesOnly()) { fout = ose = crypto.GetEncryptionStream(fout); } if (compressed) { fout = def = new ZDeflaterOutputStream(fout, compressionLevel); } byte[] buf = new byte[4192]; while (true) { int n = inputStream.Read(buf, 0, buf.Length); if (n <= 0) { break; } fout.Write(buf, 0, n); rawLength += n; } if (def != null) { def.Finish(); } if (ose != null) { ose.Finish(); } inputStreamLength = (int)osc.Counter; } else { if (crypto != null && !crypto.IsEmbeddedFilesOnly()) { byte[] b; if (streamBytes != null) { b = crypto.EncryptByteArray(streamBytes.ToArray()); } else { b = crypto.EncryptByteArray(bytes); } os.Write(b, 0, b.Length); } else { if (streamBytes != null) { streamBytes.WriteTo(os); } else { os.Write(bytes, 0, bytes.Length); } } } os.Write(ENDSTREAM, 0, ENDSTREAM.Length); }
/** * Compresses the stream. * @param compressionLevel the compression level (0 = best speed, 9 = best compression, -1 is default) * @since 2.1.3 */ virtual public void FlateCompress(int compressionLevel) { if (!Document.Compress) { return; } // check if the flateCompress-method has already been used if (compressed) { return; } this.compressionLevel = compressionLevel; if (inputStream != null) { compressed = true; return; } // check if a filter already exists PdfObject filter = PdfReader.GetPdfObject(Get(PdfName.FILTER)); if (filter != null) { if (filter.IsName()) { if (PdfName.FLATEDECODE.Equals(filter)) { return; } } else if (filter.IsArray()) { if (((PdfArray)filter).Contains(PdfName.FLATEDECODE)) { return; } } else { throw new PdfException(MessageLocalization.GetComposedMessage("stream.could.not.be.compressed.filter.is.not.a.name.or.array")); } } // compress MemoryStream stream = new MemoryStream(); ZDeflaterOutputStream zip = new ZDeflaterOutputStream(stream, compressionLevel); if (streamBytes != null) { streamBytes.WriteTo(zip); } else { zip.Write(bytes, 0, bytes.Length); } //zip.Close(); zip.Finish(); // update the object streamBytes = stream; bytes = null; Put(PdfName.LENGTH, new PdfNumber(streamBytes.Length)); if (filter == null) { Put(PdfName.FILTER, PdfName.FLATEDECODE); } else { PdfArray filters = new PdfArray(filter); filters.Add(0, PdfName.FLATEDECODE); Put(PdfName.FILTER, filters); } compressed = true; }
// constructor /** * Constructs a <CODE>PdfContents</CODE>-object, containing text and general graphics. * * @param under the direct content that is under all others * @param content the graphics in a page * @param text the text in a page * @param secondContent the direct content that is over all others * @throws BadPdfFormatException on error */ internal PdfContents(PdfContentByte under, PdfContentByte content, PdfContentByte text, PdfContentByte secondContent, Rectangle page) : base() { Stream ostr = null; streamBytes = new MemoryStream(); if (Document.Compress) { compressed = true; ostr = new ZDeflaterOutputStream(streamBytes, text.PdfWriter.CompressionLevel); } else { ostr = streamBytes; } int rotation = page.Rotation; byte[] tmp; switch (rotation) { case 90: ostr.Write(ROTATE90, 0, ROTATE90.Length); tmp = DocWriter.GetISOBytes(ByteBuffer.FormatDouble(page.Top)); ostr.Write(tmp, 0, tmp.Length); ostr.WriteByte((byte)' '); ostr.WriteByte((byte)'0'); ostr.Write(ROTATEFINAL, 0, ROTATEFINAL.Length); break; case 180: ostr.Write(ROTATE180, 0, ROTATE180.Length); tmp = DocWriter.GetISOBytes(ByteBuffer.FormatDouble(page.Right)); ostr.Write(tmp, 0, tmp.Length); ostr.WriteByte((byte)' '); tmp = DocWriter.GetISOBytes(ByteBuffer.FormatDouble(page.Top)); ostr.Write(tmp, 0, tmp.Length); ostr.Write(ROTATEFINAL, 0, ROTATEFINAL.Length); break; case 270: ostr.Write(ROTATE270, 0, ROTATE270.Length); ostr.WriteByte((byte)'0'); ostr.WriteByte((byte)' '); tmp = DocWriter.GetISOBytes(ByteBuffer.FormatDouble(page.Right)); ostr.Write(tmp, 0, tmp.Length); ostr.Write(ROTATEFINAL, 0, ROTATEFINAL.Length); break; } if (under.Size > 0) { ostr.Write(SAVESTATE, 0, SAVESTATE.Length); under.InternalBuffer.WriteTo(ostr); ostr.Write(RESTORESTATE, 0, RESTORESTATE.Length); } if (content.Size > 0) { ostr.Write(SAVESTATE, 0, SAVESTATE.Length); content.InternalBuffer.WriteTo(ostr); ostr.Write(RESTORESTATE, 0, RESTORESTATE.Length); } if (text != null) { ostr.Write(SAVESTATE, 0, SAVESTATE.Length); text.InternalBuffer.WriteTo(ostr); ostr.Write(RESTORESTATE, 0, RESTORESTATE.Length); } if (secondContent.Size > 0) { secondContent.InternalBuffer.WriteTo(ostr); } if (ostr is ZDeflaterOutputStream) { ((ZDeflaterOutputStream)ostr).Finish(); } Put(PdfName.LENGTH, new PdfNumber(streamBytes.Length)); if (compressed) { Put(PdfName.FILTER, PdfName.FLATEDECODE); } }
/// <summary> /// methods /// </summary> /// <summary> /// Compresses the stream. /// @since 2.1.3 /// </summary> /// <param name="compressionLevel">the compression level (0 = best speed, 9 = best compression, -1 is default)</param> public void FlateCompress(int compressionLevel) { if (!Document.Compress) { return; } // check if the flateCompress-method has allready been if (Compressed) { return; } CompressionLevel = compressionLevel; if (InputStream != null) { Compressed = true; return; } // check if a filter allready exists PdfObject filter = PdfReader.GetPdfObject(Get(PdfName.Filter)); if (filter != null) { if (filter.IsName()) { if (PdfName.Flatedecode.Equals(filter)) { return; } } else if (filter.IsArray()) { if (((PdfArray)filter).Contains(PdfName.Flatedecode)) { return; } } else { throw new PdfException("Stream could not be compressed: filter is not a name or array."); } } // compress MemoryStream stream = new MemoryStream(); ZDeflaterOutputStream zip = new ZDeflaterOutputStream(stream, compressionLevel); if (StreamBytes != null) { StreamBytes.WriteTo(zip); } else { zip.Write(Bytes, 0, Bytes.Length); } //zip.Close(); zip.Finish(); // update the object StreamBytes = stream; Bytes = null; Put(PdfName.LENGTH, new PdfNumber(StreamBytes.Length)); if (filter == null) { Put(PdfName.Filter, PdfName.Flatedecode); } else { PdfArray filters = new PdfArray(filter); filters.Add(PdfName.Flatedecode); Put(PdfName.Filter, filters); } Compressed = true; }
/// <summary> /// Constructs a PdfContents -object, containing text and general graphics. /// @throws BadPdfFormatException on error /// </summary> /// <param name="under">the direct content that is under all others</param> /// <param name="content">the graphics in a page</param> /// <param name="text">the text in a page</param> /// <param name="secondContent">the direct content that is over all others</param> /// <param name="page"></param> internal PdfContents(PdfContentByte under, PdfContentByte content, PdfContentByte text, PdfContentByte secondContent, Rectangle page) { Stream ostr = null; StreamBytes = new MemoryStream(); if (Document.Compress) { Compressed = true; ostr = new ZDeflaterOutputStream(StreamBytes, text.PdfWriter.CompressionLevel); } else { ostr = StreamBytes; } int rotation = page.Rotation; byte[] tmp; switch (rotation) { case 90: ostr.Write(Rotate90, 0, Rotate90.Length); tmp = DocWriter.GetIsoBytes(ByteBuffer.FormatDouble(page.Top)); ostr.Write(tmp, 0, tmp.Length); ostr.WriteByte((byte)' '); ostr.WriteByte((byte)'0'); ostr.Write(Rotatefinal, 0, Rotatefinal.Length); break; case 180: ostr.Write(Rotate180, 0, Rotate180.Length); tmp = DocWriter.GetIsoBytes(ByteBuffer.FormatDouble(page.Right)); ostr.Write(tmp, 0, tmp.Length); ostr.WriteByte((byte)' '); tmp = DocWriter.GetIsoBytes(ByteBuffer.FormatDouble(page.Top)); ostr.Write(tmp, 0, tmp.Length); ostr.Write(Rotatefinal, 0, Rotatefinal.Length); break; case 270: ostr.Write(Rotate270, 0, Rotate270.Length); ostr.WriteByte((byte)'0'); ostr.WriteByte((byte)' '); tmp = DocWriter.GetIsoBytes(ByteBuffer.FormatDouble(page.Right)); ostr.Write(tmp, 0, tmp.Length); ostr.Write(Rotatefinal, 0, Rotatefinal.Length); break; } if (under.Size > 0) { ostr.Write(Savestate, 0, Savestate.Length); under.InternalBuffer.WriteTo(ostr); ostr.Write(Restorestate, 0, Restorestate.Length); } if (content.Size > 0) { ostr.Write(Savestate, 0, Savestate.Length); content.InternalBuffer.WriteTo(ostr); ostr.Write(Restorestate, 0, Restorestate.Length); } if (text != null) { ostr.Write(Savestate, 0, Savestate.Length); text.InternalBuffer.WriteTo(ostr); ostr.Write(Restorestate, 0, Restorestate.Length); } if (secondContent.Size > 0) { secondContent.InternalBuffer.WriteTo(ostr); } if (ostr is ZDeflaterOutputStream) { ((ZDeflaterOutputStream)ostr).Finish(); } Put(PdfName.LENGTH, new PdfNumber(StreamBytes.Length)); if (Compressed) { Put(PdfName.Filter, PdfName.Flatedecode); } }
public override void ToPdf(PdfWriter writer, Stream os) { if (inputStream != null && compressed) { Put(PdfName.FILTER, PdfName.FLATEDECODE); } SuperToPdf(writer, os); os.Write(STARTSTREAM, 0, STARTSTREAM.Length); PdfEncryption crypto = null; if (writer != null) { crypto = writer.Encryption; } if (crypto != null) { crypto.PrepareKey(); } if (inputStream != null) { rawLength = 0; ZDeflaterOutputStream def = null; OutputStreamCounter osc = new OutputStreamCounter(os); Stream fout = osc; if (crypto != null) { fout = new PdfEncryptionStream(fout, crypto); } if (compressed) { fout = def = new ZDeflaterOutputStream(fout); } byte[] buf = new byte[0x10000]; while (true) { int n = inputStream.Read(buf, 0, buf.Length); if (n <= 0) { break; } fout.Write(buf, 0, n); rawLength += n; } if (def != null) { def.Finish(); } inputStreamLength = osc.Counter; } else { if (crypto == null) { if (streamBytes != null) { streamBytes.WriteTo(os); } else { os.Write(bytes, 0, bytes.Length); } } else { byte[] b; if (streamBytes != null) { b = streamBytes.ToArray(); crypto.EncryptRC4(b); } else { b = new byte[bytes.Length]; crypto.EncryptRC4(bytes, b); } os.Write(b, 0, b.Length); } } os.Write(ENDSTREAM, 0, ENDSTREAM.Length); }
// methods /** * Compresses the stream. * * @throws PdfException if a filter is allready defined */ public void FlateCompress() { if (!Document.Compress) { return; } // check if the flateCompress-method has allready been if (compressed) { return; } if (inputStream != null) { compressed = true; return; } // check if a filter allready exists PdfObject filter = Get(PdfName.FILTER); if (filter != null) { if (filter.IsName() && ((PdfName)filter).CompareTo(PdfName.FLATEDECODE) == 0) { return; } else if (filter.IsArray() && ((PdfArray)filter).Contains(PdfName.FLATEDECODE)) { return; } else { throw new PdfException("Stream could not be compressed: filter is not a name or array."); } } // compress MemoryStream stream = new MemoryStream(); ZDeflaterOutputStream zip = new ZDeflaterOutputStream(stream); if (streamBytes != null) { streamBytes.WriteTo(zip); } else { zip.Write(bytes, 0, bytes.Length); } //zip.Close(); zip.Finish(); // update the object streamBytes = stream; bytes = null; Put(PdfName.LENGTH, new PdfNumber(streamBytes.Length)); if (filter == null) { Put(PdfName.FILTER, PdfName.FLATEDECODE); } else { PdfArray filters = new PdfArray(filter); filters.Add(PdfName.FLATEDECODE); Put(PdfName.FILTER, filters); } compressed = true; }
public override void ToPdf(PdfWriter writer, Stream os) { if (InputStream != null && Compressed) { Put(PdfName.Filter, PdfName.Flatedecode); } PdfEncryption crypto = null; if (writer != null) { crypto = writer.Encryption; } if (crypto != null) { PdfObject filter = Get(PdfName.Filter); if (filter != null) { if (PdfName.Crypt.Equals(filter)) { crypto = null; } else if (filter.IsArray()) { PdfArray a = ((PdfArray)filter); if (a.Size > 0 && PdfName.Crypt.Equals(a[0])) { crypto = null; } } } } PdfObject nn = Get(PdfName.LENGTH); if (crypto != null && nn != null && nn.IsNumber()) { int sz = ((PdfNumber)nn).IntValue; Put(PdfName.LENGTH, new PdfNumber(crypto.CalculateStreamSize(sz))); SuperToPdf(writer, os); Put(PdfName.LENGTH, nn); } else { SuperToPdf(writer, os); } os.Write(Startstream, 0, Startstream.Length); if (InputStream != null) { rawLength = 0; ZDeflaterOutputStream def = null; OutputStreamCounter osc = new OutputStreamCounter(os); OutputStreamEncryption ose = null; Stream fout = osc; if (crypto != null && !crypto.IsEmbeddedFilesOnly()) { fout = ose = crypto.GetEncryptionStream(fout); } if (Compressed) { fout = def = new ZDeflaterOutputStream(fout, CompressionLevel); } byte[] buf = new byte[4192]; while (true) { int n = InputStream.Read(buf, 0, buf.Length); if (n <= 0) { break; } fout.Write(buf, 0, n); rawLength += n; } if (def != null) { def.Finish(); } if (ose != null) { ose.Finish(); } InputStreamLength = osc.Counter; } else { if (crypto != null && !crypto.IsEmbeddedFilesOnly()) { byte[] b; if (StreamBytes != null) { b = crypto.EncryptByteArray(StreamBytes.ToArray()); } else { b = crypto.EncryptByteArray(Bytes); } os.Write(b, 0, b.Length); } else { if (StreamBytes != null) { StreamBytes.WriteTo(os); } else { os.Write(Bytes, 0, Bytes.Length); } } } os.Write(Endstream, 0, Endstream.Length); }
protected static Image GetTiffImageColor(TiffDirectory dir, RandomAccessFileOrArray s) { var predictor = 1; TifflzwDecoder lzwDecoder = null; var compression = (int)dir.GetFieldAsLong(TiffConstants.TIFFTAG_COMPRESSION); switch (compression) { case TiffConstants.COMPRESSION_NONE: case TiffConstants.COMPRESSION_LZW: case TiffConstants.COMPRESSION_PACKBITS: case TiffConstants.COMPRESSION_DEFLATE: case TiffConstants.COMPRESSION_ADOBE_DEFLATE: case TiffConstants.COMPRESSION_OJPEG: case TiffConstants.COMPRESSION_JPEG: break; default: throw new InvalidOperationException("The compression " + compression + " is not supported."); } var photometric = (int)dir.GetFieldAsLong(TiffConstants.TIFFTAG_PHOTOMETRIC); switch (photometric) { case TiffConstants.PHOTOMETRIC_MINISWHITE: case TiffConstants.PHOTOMETRIC_MINISBLACK: case TiffConstants.PHOTOMETRIC_RGB: case TiffConstants.PHOTOMETRIC_SEPARATED: case TiffConstants.PHOTOMETRIC_PALETTE: break; default: if (compression != TiffConstants.COMPRESSION_OJPEG && compression != TiffConstants.COMPRESSION_JPEG) { throw new InvalidOperationException("The photometric " + photometric + " is not supported."); } break; } float rotation = 0; if (dir.IsTagPresent(TiffConstants.TIFFTAG_ORIENTATION)) { var rot = (int)dir.GetFieldAsLong(TiffConstants.TIFFTAG_ORIENTATION); if (rot == TiffConstants.ORIENTATION_BOTRIGHT || rot == TiffConstants.ORIENTATION_BOTLEFT) { rotation = (float)Math.PI; } else if (rot == TiffConstants.ORIENTATION_LEFTTOP || rot == TiffConstants.ORIENTATION_LEFTBOT) { rotation = (float)(Math.PI / 2.0); } else if (rot == TiffConstants.ORIENTATION_RIGHTTOP || rot == TiffConstants.ORIENTATION_RIGHTBOT) { rotation = -(float)(Math.PI / 2.0); } } if (dir.IsTagPresent(TiffConstants.TIFFTAG_PLANARCONFIG) && dir.GetFieldAsLong(TiffConstants.TIFFTAG_PLANARCONFIG) == TiffConstants.PLANARCONFIG_SEPARATE) { throw new InvalidOperationException("Planar images are not supported."); } if (dir.IsTagPresent(TiffConstants.TIFFTAG_EXTRASAMPLES)) { throw new InvalidOperationException("Extra samples are not supported."); } var samplePerPixel = 1; if (dir.IsTagPresent(TiffConstants.TIFFTAG_SAMPLESPERPIXEL)) // 1,3,4 { samplePerPixel = (int)dir.GetFieldAsLong(TiffConstants.TIFFTAG_SAMPLESPERPIXEL); } var bitsPerSample = 1; if (dir.IsTagPresent(TiffConstants.TIFFTAG_BITSPERSAMPLE)) { bitsPerSample = (int)dir.GetFieldAsLong(TiffConstants.TIFFTAG_BITSPERSAMPLE); } switch (bitsPerSample) { case 1: case 2: case 4: case 8: break; default: throw new InvalidOperationException("Bits per sample " + bitsPerSample + " is not supported."); } Image img = null; var h = (int)dir.GetFieldAsLong(TiffConstants.TIFFTAG_IMAGELENGTH); var w = (int)dir.GetFieldAsLong(TiffConstants.TIFFTAG_IMAGEWIDTH); var dpiX = 0; var dpiY = 0; var resolutionUnit = TiffConstants.RESUNIT_INCH; if (dir.IsTagPresent(TiffConstants.TIFFTAG_RESOLUTIONUNIT)) { resolutionUnit = (int)dir.GetFieldAsLong(TiffConstants.TIFFTAG_RESOLUTIONUNIT); } dpiX = getDpi(dir.GetField(TiffConstants.TIFFTAG_XRESOLUTION), resolutionUnit); dpiY = getDpi(dir.GetField(TiffConstants.TIFFTAG_YRESOLUTION), resolutionUnit); var fillOrder = 1; var reverse = false; var fillOrderField = dir.GetField(TiffConstants.TIFFTAG_FILLORDER); if (fillOrderField != null) { fillOrder = fillOrderField.GetAsInt(0); } reverse = (fillOrder == TiffConstants.FILLORDER_LSB2MSB); var rowsStrip = h; if (dir.IsTagPresent(TiffConstants.TIFFTAG_ROWSPERSTRIP)) //another hack for broken tiffs { rowsStrip = (int)dir.GetFieldAsLong(TiffConstants.TIFFTAG_ROWSPERSTRIP); } if (rowsStrip <= 0 || rowsStrip > h) { rowsStrip = h; } var offset = getArrayLongShort(dir, TiffConstants.TIFFTAG_STRIPOFFSETS); var size = getArrayLongShort(dir, TiffConstants.TIFFTAG_STRIPBYTECOUNTS); if ((size == null || (size.Length == 1 && (size[0] == 0 || size[0] + offset[0] > s.Length))) && h == rowsStrip) { // some TIFF producers are really lousy, so... size = new long[] { s.Length - (int)offset[0] }; } if (compression == TiffConstants.COMPRESSION_LZW) { var predictorField = dir.GetField(TiffConstants.TIFFTAG_PREDICTOR); if (predictorField != null) { predictor = predictorField.GetAsInt(0); if (predictor != 1 && predictor != 2) { throw new InvalidOperationException("Illegal value for Predictor in TIFF file."); } if (predictor == 2 && bitsPerSample != 8) { throw new InvalidOperationException(bitsPerSample + "-bit samples are not supported for Horizontal differencing Predictor."); } } lzwDecoder = new TifflzwDecoder(w, predictor, samplePerPixel); } var rowsLeft = h; MemoryStream stream = null; ZDeflaterOutputStream zip = null; Ccittg4Encoder g4 = null; if (bitsPerSample == 1 && samplePerPixel == 1) { g4 = new Ccittg4Encoder(w); } else { stream = new MemoryStream(); if (compression != TiffConstants.COMPRESSION_OJPEG && compression != TiffConstants.COMPRESSION_JPEG) { zip = new ZDeflaterOutputStream(stream); } } if (compression == TiffConstants.COMPRESSION_OJPEG) { // Assume that the TIFFTAG_JPEGIFBYTECOUNT tag is optional, since it's obsolete and // is often missing if ((!dir.IsTagPresent(TiffConstants.TIFFTAG_JPEGIFOFFSET))) { throw new IOException("Missing tag(s) for OJPEG compression."); } var jpegOffset = (int)dir.GetFieldAsLong(TiffConstants.TIFFTAG_JPEGIFOFFSET); var jpegLength = s.Length - jpegOffset; if (dir.IsTagPresent(TiffConstants.TIFFTAG_JPEGIFBYTECOUNT)) { jpegLength = (int)dir.GetFieldAsLong(TiffConstants.TIFFTAG_JPEGIFBYTECOUNT) + (int)size[0]; } var jpeg = new byte[Math.Min(jpegLength, s.Length - jpegOffset)]; var posFilePointer = s.FilePointer; posFilePointer += jpegOffset; s.Seek(posFilePointer); s.ReadFully(jpeg); img = new Jpeg(jpeg); } else if (compression == TiffConstants.COMPRESSION_JPEG) { if (size.Length > 1) { throw new IOException("Compression JPEG is only supported with a single strip. This image has " + size.Length + " strips."); } var jpeg = new byte[(int)size[0]]; s.Seek(offset[0]); s.ReadFully(jpeg); img = new Jpeg(jpeg); } else { for (var k = 0; k < offset.Length; ++k) { var im = new byte[(int)size[k]]; s.Seek(offset[k]); s.ReadFully(im); var height = Math.Min(rowsStrip, rowsLeft); byte[] outBuf = null; if (compression != TiffConstants.COMPRESSION_NONE) { outBuf = new byte[(w * bitsPerSample * samplePerPixel + 7) / 8 * height]; } if (reverse) { TiffFaxDecoder.ReverseBits(im); } switch (compression) { case TiffConstants.COMPRESSION_DEFLATE: case TiffConstants.COMPRESSION_ADOBE_DEFLATE: Inflate(im, outBuf); break; case TiffConstants.COMPRESSION_NONE: outBuf = im; break; case TiffConstants.COMPRESSION_PACKBITS: DecodePackbits(im, outBuf); break; case TiffConstants.COMPRESSION_LZW: lzwDecoder.Decode(im, outBuf, height); break; } if (bitsPerSample == 1 && samplePerPixel == 1) { g4.Fax4Encode(outBuf, height); } else { zip.Write(outBuf, 0, outBuf.Length); } rowsLeft -= rowsStrip; } if (bitsPerSample == 1 && samplePerPixel == 1) { img = Image.GetInstance(w, h, false, Element.CCITTG4, photometric == TiffConstants.PHOTOMETRIC_MINISBLACK ? Element.CCITT_BLACKIS1 : 0, g4.Close()); } else { zip.Close(); img = Image.GetInstance(w, h, samplePerPixel, bitsPerSample, stream.ToArray()); img.Deflated = true; } } img.SetDpi(dpiX, dpiY); if (compression != TiffConstants.COMPRESSION_OJPEG && compression != TiffConstants.COMPRESSION_JPEG) { if (dir.IsTagPresent(TiffConstants.TIFFTAG_ICCPROFILE)) { try { var fd = dir.GetField(TiffConstants.TIFFTAG_ICCPROFILE); var iccProf = IccProfile.GetInstance(fd.GetAsBytes()); if (samplePerPixel == iccProf.NumComponents) { img.TagIcc = iccProf; } } catch { //empty } } if (dir.IsTagPresent(TiffConstants.TIFFTAG_COLORMAP)) { var fd = dir.GetField(TiffConstants.TIFFTAG_COLORMAP); var rgb = fd.GetAsChars(); var palette = new byte[rgb.Length]; var gColor = rgb.Length / 3; var bColor = gColor * 2; for (var k = 0; k < gColor; ++k) { palette[k * 3] = (byte)(rgb[k] >> 8); palette[k * 3 + 1] = (byte)(rgb[k + gColor] >> 8); palette[k * 3 + 2] = (byte)(rgb[k + bColor] >> 8); } var indexed = new PdfArray(); indexed.Add(PdfName.Indexed); indexed.Add(PdfName.Devicergb); indexed.Add(new PdfNumber(gColor - 1)); indexed.Add(new PdfString(palette)); var additional = new PdfDictionary(); additional.Put(PdfName.Colorspace, indexed); img.Additional = additional; } img.OriginalType = Image.ORIGINAL_TIFF; } if (photometric == TiffConstants.PHOTOMETRIC_MINISWHITE) { img.Inverted = true; } if (rotation.ApproxNotEqual(0)) { img.InitialRotation = rotation; } return(img); }