} // 'ARGB' public override ImageMetaData ReadMetaData(IBinaryStream file) { var header = file.ReadHeader(0x19); if (!header.AsciiEqual("ARGBSaveData1\0") || header[0x10] != 3) { return(null); } const uint image_offset = 0x19; uint image_size = header.ToUInt32(0x11); uint mask_size = header.ToUInt32(0x15); using (var jpeg = OpenStreamRegion(file, image_offset, image_size)) { var info = Jpeg.ReadMetaData(jpeg); if (null == info) { return(null); } return(new ArgbMetaData { Width = info.Width, Height = info.Height, BPP = 32, ImageOffset = image_offset, ImageLength = image_size, MaskLength = mask_size, }); } }
public static void GeneratePODForm(string templateFormsPath, string podFilePath, string receivedBy, string receivingTime, string signature) { PdfReader reader = new PdfReader(templateFormsPath); //select three pages from the original document reader.SelectPages("1-3"); //create PdfStamper object to write to get the pages from reader PdfStamper stamper = new PdfStamper(reader, new FileStream(podFilePath, FileMode.Create)); Rectangle pagesize = reader.GetPageSize(1); // PdfContentByte from stamper to add content to the pages over the original content PdfContentByte pbover = stamper.GetOverContent(1); PdfContentByte pbunder = stamper.GetUnderContent(1); //add content to the page using ColumnText ColumnText.ShowTextAligned(pbover, Element.ALIGN_LEFT, new Phrase(receivedBy), pagesize.Left + 320, pagesize.Bottom + 90, 0); ColumnText.ShowTextAligned(pbover, Element.ALIGN_LEFT, new Phrase(receivingTime), pagesize.Left + 400, pagesize.Bottom + 60, 0); // PdfContentByte from stamper to add content to the pages under the original content //add image from a file iTextSharp.text.Image img = new Jpeg(imageToByteArray(System.Drawing.Image.FromFile(signature))); //add the image under the original content img.SetAbsolutePosition(pagesize.Left + 380, pagesize.Bottom + 10); pbunder.AddImage(img); //pbunder.AddImage(img, img.Width / 2, 0, 0, img.Height / 2, 0, 0); //close the stamper stamper.Close(); }
private void PopulateFileResourceDataAsImage() { var fileResourceDataAsMemoryStream = new MemoryStream(FileResourceData.Data); _photo = new Jpeg(new System.Drawing.Bitmap(fileResourceDataAsMemoryStream)); _hasCheckedPhoto = true; }
public static BitmapSource ApplyDiscreteCosineTransform(BitmapSource bitmap, object parameter) { var dctParameters = (DctParameters)parameter; var encoded = DctAlgorithm.ApplyDct(bitmap, dctParameters); Jpeg.Save(encoded, dctParameters); return(null); }
public void Throws_StreamTooSmall_When_Stream_Empty() { // empty memory stream using (MemoryStream stream = new MemoryStream()) { Assert.Throws <Exceptions.StreamTooSmallException>(() => Jpeg.GetDimensions(stream)); } }
private bool ExistAnyDateTimeExifTag(ref Jpeg VtJpeg) { bool ExifDateTime = VtJpeg.ExistPropertyItem(PropertyTagId.DateTime); bool ExifDateTimeDigitized = VtJpeg.ExistPropertyItem(PropertyTagId.DateTimeDigitized); bool ExifDateTimeOriginal = VtJpeg.ExistPropertyItem(PropertyTagId.DateTimeOriginal); return(ExifDateTime | ExifDateTimeDigitized | ExifDateTimeOriginal); }
public override ImageMetaData ReadMetaData(IBinaryStream file) { if ((file.Signature & 0xFFFFFF) != 0xFDFF00) { return(null); } using (var jpeg = OpenAsJpeg(file)) return(Jpeg.ReadMetaData(jpeg)); }
public void Should_Read_From_SOF0() { using (Stream fileStream = File.OpenRead(@"testimages\SOF0_1280x853.jpg")) { Dimensions dimensions = Jpeg.GetDimensions(fileStream); Assert.Equal(1280, dimensions.Width); Assert.Equal(853, dimensions.Height); } }
public void Should_Read_From_SOF2() { using (Stream fileStream = File.OpenRead(@"testimages\SOF2_800x600.jpg")) { Dimensions dimensions = Jpeg.GetDimensions(fileStream); Assert.Equal(800, dimensions.Width); Assert.Equal(600, dimensions.Height); } }
public void Throws_BadSegmentSize_When_Stream_Ends() { byte[] headerBuffer = new byte[4]; // the stream is empty so it should throw when trying to get next bytes using (MemoryStream jpegStream = new MemoryStream(new byte[0])) { Assert.Throws <Exceptions.BadSegmentSizeException>(() => Jpeg.FindNextSegment(jpegStream, headerBuffer)); } }
public void Should_Read_From_Image_With_Bad_Segment_Size() { // this image has a bad segment size that must be recovered from, it also has LOADS of metadata using (Stream fileStream = File.OpenRead(@"testimages\Bad_Segment_Size_4596x3418.jpg")) { Dimensions dimensions = Jpeg.GetDimensions(fileStream); Assert.Equal(4596, dimensions.Width); Assert.Equal(3418, dimensions.Height); } }
public override ImageMetaData ReadMetaData(IBinaryStream stream) { var header = stream.ReadHeader(2); if (header[0] != 0 || header[1] != 0x93) { return(null); } using (var jpg = OpenEncrypted(stream)) return(Jpeg.ReadMetaData(jpg)); }
public void Should_Read_From_SOF0_With_CMYK() { // this image has I higher number of components than normal because of photometric interpretation CMYK using (Stream fileStream = File.OpenRead(@"testimages\CMYK_SOF0_5100x3300.jpg")) { Dimensions dimensions = Jpeg.GetDimensions(fileStream); Assert.Equal(5100, dimensions.Width); Assert.Equal(3300, dimensions.Height); } }
private string GetExifString(ref Jpeg VtJpeg, string Key) { PropertyTagId PTagId = GetPIdFromStr(Key); if (VtJpeg.ExistPropertyItem(PTagId)) { return(VtJpeg.GetPropertyItemAsString(PTagId)); } else { return(""); } }
public void Save_Jpeg(long quality) { var filename = "lena.png"; using (var resizer = new ImageResizer(GetSource(filename))) { resizer.ResizeMode = ImageResizeMode.HighQuality; resizer.Width = 256; var dest = SavePath(resizer, "jpeg", ".jpg"); resizer.Save(dest, Jpeg.Format, Jpeg.Quality(quality)); Assert.That(Io.Exists(dest), Is.True); } }
public static BitmapSource DecodeDct(DctParameters dctParameters) { var encoded = Jpeg.Load(dctParameters); var encodedMatrices = SplitToBlocksInt(encoded, 8); var dequantizedMatrices = DequantizeMatrices(encodedMatrices, dctParameters); var dct = GetDctMatrix(); var transposedDct = dct.Transpose(); var inversedDct = ApplyDct(dequantizedMatrices, transposedDct, dct); var flattened = FlattenByte(inversedDct); var undecimated = Undecimate(flattened, dctParameters.DecimationType); var inRgb = ToRgbBytes(undecimated); return(BitmapSource.Create(undecimated.GetLength(0), undecimated.GetLength(1), 96.0, 96.0, PixelFormats.Bgr32, null, inRgb, inRgb.Length / undecimated.GetLength(0))); }
//EquipMake //EquipModel private string GetEquip(ref Jpeg VtJpeg) { string Result = ""; string EquipMake = GetExifString(ref VtJpeg, "EquipMake"); string EquipModel = GetExifString(ref VtJpeg, "EquipModel"); // sectu to, pokud existuji oba retezce, oddelim je mezerou Result = EquipMake; if (!string.IsNullOrEmpty(EquipMake) && !string.IsNullOrEmpty(EquipModel)) { Result += " "; } Result += EquipModel; return(Result); }
public override ImageMetaData ReadMetaData(IBinaryStream file) { int type = file.ReadByte(); if (type != 3) { return(null); } uint width = file.ReadUInt16(); uint height = file.ReadUInt16(); if (0 == width || width > 0x8000 || 0 == height || height > 0x8000) { return(null); } using (var jpeg = OpenJpegStream(file)) return(Jpeg.ReadMetaData(jpeg)); }
public static void ReadItem(ZipFile file, ZipEntry itemEntry, Database destinationDb) { Stream itemStream = file.GetInputStream(itemEntry); try { XElement xmlDoc = XElement.Load(itemStream); string templateName = xmlDoc.Attribute("template")?.Value; switch (templateName) { case "blog author": Author author = new Author(xmlDoc); destinationDb.Authors.Add(author); break; case "blog category": case "blog tag": Taxonomy taxonomy = new Taxonomy(xmlDoc); destinationDb.TaxonomyItems.Add(taxonomy); break; case "blog post": BlogPost blogPost = new BlogPost(xmlDoc); destinationDb.BlogPosts.Add(blogPost); break; case "image": Image image = new Image(xmlDoc, itemEntry.Name); destinationDb.Images.Add(image); break; case "jpeg": Jpeg jpeg = new Jpeg(xmlDoc, itemEntry.Name); destinationDb.Images.Add(jpeg); break; } } catch (Exception e) { Console.WriteLine($"Error loading {itemEntry.Name}..."); Console.WriteLine(e); } }
public void Throws_StreamTooSmallException_When_Stream_Too_Small() { /* * This test make sure that it is performing checked reads. * It should throw when it tries to read but the stream is empty */ // this has the file marker but no oihers so it should throw when trying to read the next header byte[] shortImage = new byte[] { 0xff, Markers.FileMarker }; using (MemoryStream stream = new MemoryStream(shortImage)) { Assert.Throws <Exceptions.StreamTooSmallException>(() => Jpeg.GetDimensions(stream)); } }
public void Throws_InvalidJpeg_When_FileMarker_Missing() { byte[] missingHeader = new byte[10]; using (MemoryStream stream = new MemoryStream(missingHeader)) { // all bytes are 0 to start with Assert.Throws <Exceptions.InvalidJpegException>(() => Jpeg.GetDimensions(stream)); } // set the first byte to be valid to make sure it is checking second byte as well missingHeader[0] = 0xff; using (MemoryStream stream = new MemoryStream(missingHeader)) { // all 0 bytes to start with Assert.Throws <Exceptions.InvalidJpegException>(() => Jpeg.GetDimensions(stream)); } }
private DateTime GetPreferedDateTime(ref Jpeg VtJpeg, ArrayList PreferExifDate) { DateTime Result = DateTime.MinValue; //foreach (string Item in LBExifDates.Items) //{ // PropertyTagId PTagId = GetPIdFromStr(Item); // if (VtJpeg.ExistPropertyItem(PTagId)) // return VtJpeg.GetPropertyItemAsDateTime(PTagId); //} foreach (string Item in PreferExifDate) { PropertyTagId PTagId = GetPIdFromStr(Item); if (VtJpeg.ExistPropertyItem(PTagId)) { return(VtJpeg.GetPropertyItemAsDateTime(PTagId)); } } return(Result); }
private void pdfToolStripMenuItem_Click(object sender, EventArgs e) { try { SaveFileDialog sfd = new SaveFileDialog(); sfd.Title = "Bulmaca Pdf Kayıt"; sfd.Filter = "Pdf Dosyası (*.pdf) | *.pdf"; string sfdname = sfd.FileName; if (sfd.ShowDialog() == DialogResult.OK) { kelimeEkleText.Focus(); soldanSagaSorular.BorderStyle = BorderStyle.None; yukaridanAsagiyaSorular.BorderStyle = BorderStyle.None; var doc = new iTextSharp.text.Document(); MemoryStream ms = new MemoryStream(); Bitmap img2 = new Bitmap(A4.Width, A4.Height); A4.DrawToBitmap(img2, new System.Drawing.Rectangle(0, 0, A4.Width, A4.Height)); iTextSharp.text.pdf.PdfWriter.GetInstance(doc, new FileStream(sfd.FileName, FileMode.Create)); doc.Open(); iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(img2, System.Drawing.Imaging.ImageFormat.Png); var jpeg = new Jpeg(img); jpeg.ScaleToFit(doc.PageSize.Width - (doc.LeftMargin + doc.RightMargin), doc.PageSize.Height - (doc.BottomMargin + doc.TopMargin)); jpeg.SetAbsolutePosition(doc.BottomMargin, doc.TopMargin); doc.Add(jpeg); doc.Close(); soldanSagaSorular.BorderStyle = BorderStyle.FixedSingle; yukaridanAsagiyaSorular.BorderStyle = BorderStyle.FixedSingle; } } catch { } }
public void Should_Read_Stream_Until_Marker_Found() { const int TestSize = 10; for (int i = 0; i < TestSize; i++) { // this represents the stream of an image byte[] imageBuffer = new byte[TestSize + 3]; // number the bytes so we can test they where copied of the stream for (byte j = 0; j < imageBuffer.Length; j++) { imageBuffer[j] = j; } // the method should find this marker imageBuffer[i] = Jpeg.SectionStartMarker; byte[] headerBuffer = imageBuffer.Take(4).ToArray(); using (MemoryStream jpegStream = new MemoryStream(imageBuffer, headerBuffer.Length, imageBuffer.Length - headerBuffer.Length)) { Jpeg.FindNextSegment(jpegStream, headerBuffer); // method should have made the marker the first byte in the array Assert.Equal(Jpeg.SectionStartMarker, headerBuffer[0]); // it should of filled the headerBuffer with bytes from the stream Assert.Equal(i, jpegStream.Position); for (int j = 1; j < headerBuffer.Length; j++) { // make sure the bytes should the stream are in the headerBuffer Assert.Equal(i + j, headerBuffer[j]); } } } }
private void capiturar_screenshot(object sender, EventArgs e) { if (this.driver != null) { try { //ScreenshotImageFormat format; //JPG if (rb_formato_jpg.Checked == true) { //format = ScreenshotImageFormat.Jpeg; String filePathName = path + "\\" + "Screenshot_Capture_" + DateTime.Now.ToString("yyyy_MM_dd_hh_mm_ss") + ".jpeg"; //((ITakesScreenshot)driver).GetScreenshot().SaveAsFile(filePathName, format); var bytesArray = driver.TakeScreenshot(new VerticalCombineDecorator(new ScreenshotMaker().RemoveScrollBarsWhileShooting())); MemoryStream ms = new MemoryStream(bytesArray, 0, bytesArray.Length); System.Drawing.Image image = System.Drawing.Image.FromStream(ms, true); image.Save(filePathName, System.Drawing.Imaging.ImageFormat.Jpeg); bytesArray = null; image.Dispose(); //PNG } else if (rb_formato_png.Checked == true) { //format = ScreenshotImageFormat.Png; String filePathName = path + "\\" + "Screenshot_Capture_" + DateTime.Now.ToString("yyyy_MM_dd_hh_mm_ss") + ".png"; //((ITakesScreenshot)driver).GetScreenshot().SaveAsFile(filePathName, format) var bytesArray = driver.TakeScreenshot(new VerticalCombineDecorator(new ScreenshotMaker().RemoveScrollBarsWhileShooting())); MemoryStream ms = new MemoryStream(bytesArray, 0, bytesArray.Length); System.Drawing.Image image = System.Drawing.Image.FromStream(ms, true); image.Save(filePathName, System.Drawing.Imaging.ImageFormat.Png); bytesArray = null; image.Dispose(); //PDF } else if (rb_formato_pdf.Checked == true) { //format = ScreenshotImageFormat.Jpeg; String filePath = path; String fileName = "Screenshot_Capture_" + DateTime.Now.ToString("yyyy_MM_dd_hh_mm_ss"); String filePathName = filePath + "\\" + fileName; //((ITakesScreenshot)driver).GetScreenshot().SaveAsFile(filePathName+ ".jpeg", format); var bytesArray = driver.TakeScreenshot(new VerticalCombineDecorator(new ScreenshotMaker().RemoveScrollBarsWhileShooting())); MemoryStream ms = new MemoryStream(bytesArray, 0, bytesArray.Length); System.Drawing.Image image = System.Drawing.Image.FromStream(ms, true); image.Save(filePathName + ".jpeg", System.Drawing.Imaging.ImageFormat.Jpeg); bytesArray = null; image.Dispose(); //criando pdf Document doc = new Document(); try { iTextSharp.text.pdf.PdfWriter.GetInstance(doc, new FileStream(filePathName + ".pdf", FileMode.Create)); doc.Open(); iTextSharp.text.Image jpg = iTextSharp.text.Image.GetInstance(filePathName + ".jpeg"); jpg.Border = iTextSharp.text.Rectangle.BOX; var jpeg = new Jpeg(jpg); jpeg.ScaleToFit(doc.PageSize.Width - (doc.LeftMargin + doc.RightMargin), doc.PageSize.Height - (doc.BottomMargin + doc.TopMargin)); doc.Add(jpeg); } catch (Exception ex) { Console.WriteLine(ex); MessageBox.Show("Tivemos algum problema ao salvar em PDF", "Mensagem"); } finally { doc.Close(); File.Delete(filePathName + ".jpeg"); } } System.Diagnostics.Process.Start("Explorer", path); /* * var result = MessageBox.Show("Imagem salva com sucesso, " + * "deseja abrir diretorio onde a screenshot esta salva ?", * "Mensagem", * MessageBoxButtons.YesNo, * MessageBoxIcon.Question); * if (result == DialogResult.Yes) { * System.Diagnostics.Process.Start("Explorer", path); * } */ } catch (Exception ex) { Console.WriteLine(ex); MessageBox.Show("Tivemos algum problema ao salvar a screenshot, " + "provavelmente o navegar foi fechado ou a sua primeira aba, " + "onde seria realizada a screenshot.", "Mensagem"); if (this.driver != null) { this.driver.Quit(); } } } else { MessageBox.Show("Abra o navegar através do nosso aplicativo " + "antes de tentar capiturar a screenshot.", "Mensagem"); } }
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); }
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); }
public override ImageData Read(IBinaryStream stream, ImageMetaData info) { using (var input = OpenEncrypted(stream)) return(Jpeg.Read(input, info)); }
public override ImageMetaData ReadMetaData(IBinaryStream stream) { using (var input = OpenEncrypted(stream, true)) return(Jpeg.ReadMetaData(input)); }
public IActionResult ExportToPdf(string returnUrl, int id) { var fanfic = Mapper.Map <FanficViewModel>(FanficRepository.GetById(id)); var topics = Mapper.Map <List <TopicViewModel> >(TopicRepository.GetTopicsByFanficId(id)); try { pdfDoc = new Document(PageSize.LETTER, 40f, 40f, 60f, 60f); BaseFont baseFont = BaseFont.CreateFont(@"wwwroot/font/arial.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); string path = @"wwwroot/pdf/tester1.pdf"; file = new FileStream(path, FileMode.Create); wri = PdfWriter.GetInstance(pdfDoc, file); pdfDoc.Open(); var spacer = new Paragraph("\n"); FileStream fileLogo = new FileStream(@"wwwroot/images/icons/logoPDF.png", FileMode.Open); var logo = Image.GetInstance(fileLogo); logo.SetAbsolutePosition(pdfDoc.Left, pdfDoc.Top); pdfDoc.Add(logo); fileLogo.Close(); var helvetica = new Font(baseFont, 20); var helveticaBase = helvetica.GetCalculatedBaseFont(false); wri.DirectContent.BeginText(); wri.DirectContent.SetFontAndSize(helveticaBase, 20f); wri.DirectContent.ShowTextAligned(Element.ALIGN_CENTER, fanfic.Name, 305, 705, 0); wri.DirectContent.EndText(); pdfDoc.Add(spacer); pdfDoc.Add(spacer); Paragraph info = new Paragraph("Author: " + fanfic.ApplicationUser.UserName + "\n" + "Rating: " + fanfic.AverageRating + "\n" + "Date: " + fanfic.CreateDate.ToShortDateString(), new Font(baseFont, 11, 2)); pdfDoc.Add(info); pdfDoc.Add(spacer); var avatarFanfic = fanfic.ImgUrl; avatarFanfic = avatarFanfic.Substring(0, 47) + "t_FanficPDF" + avatarFanfic.Substring(58, 22) + "jpg"; Uri uri = new Uri(avatarFanfic); Jpeg img = new Jpeg(uri); pdfDoc.Add(img); pdfDoc.Add(spacer); Paragraph descLabel = new Paragraph("Description: ", new Font(baseFont, 16)); pdfDoc.Add(descLabel); pdfDoc.Add(spacer); string arialuniTff = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "ARIALUNI.TTF"); FontFactory.Register(arialuniTff); StyleSheet ST = new StyleSheet(); ST.LoadTagStyle(HtmlTags.BODY, HtmlTags.FACE, "Arial Unicode MS"); ST.LoadTagStyle(HtmlTags.BODY, HtmlTags.ENCODING, BaseFont.IDENTITY_H); using (var htmlWorker = new HTMLWorker(pdfDoc)) { using (var sr = new StringReader(fanfic.Description)) { htmlWorker.SetStyleSheet(ST); htmlWorker.Parse(sr); } } pdfDoc.Add(spacer); Chapter content = new Chapter(new Paragraph("Content: ", new Font(baseFont, 16)), 0); pdfDoc.Add(content); foreach (var item in topics) { pdfDoc.Add(spacer); Paragraph chapter = new Paragraph("Chapter " + item.Number + ". " + item.Name, new Font(baseFont, 12)); pdfDoc.Add(chapter); } foreach (var item in topics) { Chapter chapter = new Chapter(new Paragraph(item.Name, new Font(baseFont, 18)), item.Number); pdfDoc.Add(chapter); pdfDoc.Add(spacer); Paragraph infoTopic = new Paragraph("Rating: " + item.AverageRating, new Font(baseFont, 11)); pdfDoc.Add(infoTopic); pdfDoc.Add(spacer); if (item.ImgUrl != " ") { var avatarTopic = item.ImgUrl; avatarTopic = avatarTopic.Substring(0, 47) + "t_FanficPDF" + avatarTopic.Substring(58, 22) + "jpg"; Uri uriTopic = new Uri(avatarTopic); Jpeg imgTopic = new Jpeg(uriTopic); pdfDoc.Add(imgTopic); pdfDoc.Add(spacer); } using (var htmlWorker = new HTMLWorker(pdfDoc)) { using (var sr = new StringReader(item.Text)) { htmlWorker.SetStyleSheet(ST); htmlWorker.Parse(sr); } } } pdfDoc.Close(); wri.Close(); WebClient User = new WebClient(); Byte[] FileBuffer = User.DownloadData(@"wwwroot/pdf/tester1.pdf"); if (FileBuffer != null) { Response.ContentType = "application/pdf"; Response.Headers.Add("content-length", FileBuffer.Length.ToString()); Response.Body.Write(FileBuffer, 0, FileBuffer.Length); } } catch (Exception ex) { pdfDoc.Close(); wri.Close(); } finally { System.IO.File.Delete(@"wwwroot/pdf/tester1.pdf"); } return(RedirectPermanent(returnUrl)); }
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("The compression " + compression + " is not supported."); } 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("The photometric " + photometric + " is not supported."); 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("Planar images are not supported."); if (dir.IsTagPresent(TIFFConstants.TIFFTAG_EXTRASAMPLES)) throw new ArgumentException("Extra samples are not supported."); 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("Bits per sample " + bitsPerSample + " is not supported."); } 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) { TIFFField predictorField = dir.GetField(TIFFConstants.TIFFTAG_PREDICTOR); if (predictorField != null) { predictor = predictorField.GetAsInt(0); if (predictor != 1 && predictor != 2) { throw new Exception("Illegal value for Predictor in TIFF file."); } if (predictor == 2 && bitsPerSample != 8) { throw new Exception(bitsPerSample + "-bit samples are not supported for Horizontal differencing Predictor."); } } lzwDecoder = new TIFFLZWDecoder(w, predictor, samplePerPixel); } int rowsLeft = h; MemoryStream stream = null; ZOutputStream 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 ZOutputStream(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."); } int jpegOffset = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_JPEGIFOFFSET); int jpegLength = 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 = 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."); 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); 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, Image.CCITTG4, photometric == TIFFConstants.PHOTOMETRIC_MINISBLACK ? Image.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 { TIFFField fd = dir.GetField(TIFFConstants.TIFFTAG_ICCPROFILE); ICC_Profile icc_prof = ICC_Profile.GetInstance(fd.GetAsBytes()); if (samplePerPixel == 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); } 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; return img; }