public override void PrintDir(Tiff tif, Stream fd, TiffPrintFlags flags) { CodecWithPredictor sp = tif.m_currentCodec as CodecWithPredictor; Debug.Assert(sp != null); if (tif.fieldSet(CodecWithPredictor.FIELD_PREDICTOR)) { Tiff.fprintf(fd, " Predictor: "); Predictor predictor = sp.GetPredictorValue(); switch (predictor) { case Predictor.NONE: Tiff.fprintf(fd, "none "); break; case Predictor.HORIZONTAL: Tiff.fprintf(fd, "horizontal differencing "); break; case Predictor.FLOATINGPOINT: Tiff.fprintf(fd, "floating point predictor "); break; } Tiff.fprintf(fd, "{0} (0x{1:x})\r\n", predictor, predictor); } TiffTagMethods childMethods = sp.GetChildTagMethods(); if (childMethods != null) childMethods.PrintDir(tif, fd, flags); else base.PrintDir(tif, fd, flags); }
public override bool SetField(Tiff tif, TiffTag tag, FieldValue[] ap) { DeflateCodec sp = tif.m_currentCodec as DeflateCodec; Debug.Assert(sp != null); const string module = "ZIPVSetField"; switch (tag) { case TiffTag.ZIPQUALITY: sp.m_zipquality = ap[0].ToInt(); if ((sp.m_state & DeflateCodec.ZSTATE_INIT_ENCODE) != 0) { if (sp.m_stream.deflateParams(sp.m_zipquality, zlibConst.Z_DEFAULT_STRATEGY) != zlibConst.Z_OK) { Tiff.ErrorExt(tif, tif.m_clientdata, module, "{0}: zlib error: {0}", tif.m_name, sp.m_stream.msg); return false; } } return true; } return base.SetField(tif, tag, ap); }
public override FieldValue[] GetField(Tiff tif, TiffTag tag) { JpegCodec sp = tif.m_currentCodec as JpegCodec; Debug.Assert(sp != null); FieldValue[] result = null; switch (tag) { case TiffTag.JPEGTABLES: result = new FieldValue[2]; result[0].Set(sp.m_jpegtables_length); result[1].Set(sp.m_jpegtables); break; case TiffTag.JPEGQUALITY: result = new FieldValue[1]; result[0].Set(sp.m_jpegquality); break; case TiffTag.JPEGCOLORMODE: result = new FieldValue[1]; result[0].Set(sp.m_jpegcolormode); break; case TiffTag.JPEGTABLESMODE: result = new FieldValue[1]; result[0].Set(sp.m_jpegtablesmode); break; case TiffTag.YCBCRSUBSAMPLING: JPEGFixupTestSubsampling(tif); return base.GetField(tif, tag); case TiffTag.FAXRECVPARAMS: result = new FieldValue[1]; result[0].Set(sp.m_recvparams); break; case TiffTag.FAXSUBADDRESS: result = new FieldValue[1]; result[0].Set(sp.m_subaddress); break; case TiffTag.FAXRECVTIME: result = new FieldValue[1]; result[0].Set(sp.m_recvtime); break; case TiffTag.FAXDCS: result = new FieldValue[1]; result[0].Set(sp.m_faxdcs); break; default: return base.GetField(tif, tag); } return result; }
public override bool SetField(Tiff tif, TiffTag tag, FieldValue[] ap) { CCITTCodec sp = tif.m_currentCodec as CCITTCodec; Debug.Assert(sp != null); switch (tag) { case TiffTag.FAXMODE: sp.m_mode = (FaxMode)ap[0].ToShort(); return true; /* NB: pseudo tag */ case TiffTag.FAXFILLFUNC: sp.fill = ap[0].Value as Tiff.FaxFillFunc; return true; /* NB: pseudo tag */ case TiffTag.GROUP3OPTIONS: /* XXX: avoid reading options if compression mismatches. */ if (tif.m_dir.td_compression == Compression.CCITTFAX3) sp.m_groupoptions = (Group3Opt)ap[0].ToShort(); break; case TiffTag.GROUP4OPTIONS: /* XXX: avoid reading options if compression mismatches. */ if (tif.m_dir.td_compression == Compression.CCITTFAX4) sp.m_groupoptions = (Group3Opt)ap[0].ToShort(); break; case TiffTag.BADFAXLINES: sp.m_badfaxlines = ap[0].ToInt(); break; case TiffTag.CLEANFAXDATA: sp.m_cleanfaxdata = (CleanFaxData)ap[0].ToByte(); break; case TiffTag.CONSECUTIVEBADFAXLINES: sp.m_badfaxrun = ap[0].ToInt(); break; case TiffTag.FAXRECVPARAMS: sp.m_recvparams = ap[0].ToInt(); break; case TiffTag.FAXSUBADDRESS: Tiff.setString(out sp.m_subaddress, ap[0].ToString()); break; case TiffTag.FAXRECVTIME: sp.m_recvtime = ap[0].ToInt(); break; case TiffTag.FAXDCS: Tiff.setString(out sp.m_faxdcs, ap[0].ToString()); break; default: return base.SetField(tif, tag, ap); } TiffFieldInfo fip = tif.FieldWithTag(tag); if (fip != null) tif.setFieldBit(fip.Bit); else return false; tif.m_flags |= TiffFlags.DIRTYDIRECT; return true; }
public override FieldValue[] GetField(Tiff tif, TiffTag tag) { OJpegCodec sp = tif.m_currentCodec as OJpegCodec; Debug.Assert(sp != null); FieldValue[] result = null; switch (tag) { case TiffTag.JPEGIFOFFSET: result = new FieldValue[1]; result[0].Set(sp.m_jpeg_interchange_format); break; case TiffTag.JPEGIFBYTECOUNT: result = new FieldValue[1]; result[0].Set(sp.m_jpeg_interchange_format_length); break; case TiffTag.YCBCRSUBSAMPLING: if (!sp.m_subsamplingcorrect_done) sp.OJPEGSubsamplingCorrect(); result = new FieldValue[2]; result[0].Set(sp.m_subsampling_hor); result[1].Set(sp.m_subsampling_ver); break; case TiffTag.JPEGQTABLES: result = new FieldValue[2]; result[0].Set(sp.m_qtable_offset_count); result[1].Set(sp.m_qtable_offset); break; case TiffTag.JPEGDCTABLES: result = new FieldValue[2]; result[0].Set(sp.m_dctable_offset_count); result[1].Set(sp.m_dctable_offset); break; case TiffTag.JPEGACTABLES: result = new FieldValue[2]; result[0].Set(sp.m_actable_offset_count); result[1].Set(sp.m_actable_offset); break; case TiffTag.JPEGPROC: result = new FieldValue[1]; result[0].Set(sp.m_jpeg_proc); break; case TiffTag.JPEGRESTARTINTERVAL: result = new FieldValue[1]; result[0].Set(sp.m_restart_interval); break; default: return base.GetField(tif, tag); } return result; }
public override void ErrorHandler(Tiff tif, string module, string fmt, params object[] ap) { using (TextWriter stdout = Console.Out) { if (module != null) { stdout.Write("{0}: ", module); } stdout.Write(fmt, ap); stdout.Write(".\n"); } }
void imageContextShowInfo_Click(object sender, EventArgs e) { GlyphImage GI = new GlyphImage(((sender as ToolStripMenuItem).GetCurrentParent() as ContextMenuStrip).SourceControl.Name); using (Tiff input = Tiff.Open(db.DataDirectory + GI.Path, "r")) { int GlyphWidth = input.GetField(TiffTag.IMAGEWIDTH)[0].ToInt(); int GlyphHeight = input.GetField(TiffTag.IMAGELENGTH)[0].ToInt(); int GlyphScanSize = input.ScanlineSize(); MessageBox.Show("Width: " + GlyphWidth + Environment.NewLine + "Height: " + GlyphHeight + Environment.NewLine + "Scansize: " + GlyphScanSize + Environment.NewLine + "Path: " + db.DataDirectory + GI.Path); } }
public static float[] Read(string filePath, List <Point> XYs) { List <float> heights = new List <float>(); using (Tiff tiff = Tiff.Open(filePath, "r")) { foreach (Point XY in XYs) { heights.Add(ReadSingle(tiff, XY.X, XY.Y)); } } return(heights.ToArray()); }
public static float[] Read(string filePath, List <Vector2> UVs) { List <float> heights = new List <float>(); using (Tiff tiff = Tiff.Open(filePath, "r")) { foreach (Vector2 UV in UVs) { heights.Add(ReadSingle(tiff, UV.X, UV.Y)); } } return(heights.ToArray()); }
public Inspect() { Name = "inspect"; Description = "Inspect a TIFF file, parsing and outputting metadata."; HelpOption("-?|-h|--help"); var target = Argument("target", "Target file to inspect"); OnExecute(() => { OutLn(target.Value + ":"); if (!File.Exists(target.Value)) { OutLn("File not found."); return(-1); } else { var fileInfo = new FileInfo(target.Value); OutLn($"{fileInfo.Length} bytes"); var tiff = new Tiff(target.Value); OutLn(tiff.IsBigEndian ? "Big Endian TIFF" : "Little Endian TIFF"); int i = 0; foreach (var ifd in tiff.Images) { OutLn($"IFD{i:N0}:"); foreach (var tag in ifd.Tags) { OutLn($"\t{tag}"); } if (ifd.Exif?.Count > 0) { OutLn("\tEXIF Data:"); foreach (var tag in ifd.Exif) { OutLn($"\t\t{tag}"); } } OutLn("\tImage data:"); foreach (var strip in ifd.Strips) { OutLn($"\t\tStrip {strip.StripNumber}: {strip.ImageData.Length:N0} bytes @ offset {strip.StripOffset}"); } OutLn("End IFD\n"); i++; } return(0); } }); }
/// <summary> /// Retrieves the specifed dictionary object as an object encoded with CCITTFaxDecode filter (TIFF). /// </summary> /// <param name="dictionary">The dictionary to extract the object from.</param> /// <returns>The image retrieve from the dictionary. If not found or an invalid image, then null is returned.</returns> private static Image ImageFromCCITTFaxDecode(PdfDictionary dictionary) { Image image = null; PdfDictionaryImageMetaData imageData = new PdfDictionaryImageMetaData(dictionary); PixelFormat format = GetPixelFormat(imageData.ColorSpace, imageData.BitsPerPixel, true); Bitmap bitmap = new Bitmap(imageData.Width, imageData.Height, format); // Determine if BLACK=1, create proper indexed color palette. CCITTFaxDecodeParameters ccittFaxDecodeParameters = new CCITTFaxDecodeParameters(dictionary.Elements["/DecodeParms"].Get() as PdfDictionary); if (ccittFaxDecodeParameters.BlackIs1) { bitmap.Palette = PdfIndexedColorSpace.CreateColorPalette(Color.Black, Color.White); } else { bitmap.Palette = PdfIndexedColorSpace.CreateColorPalette(Color.White, Color.Black); } if (ccittFaxDecodeParameters.K == 0 || ccittFaxDecodeParameters.K > 0) { imageData.Compression = Compression.CCITTFAX3; } else if (ccittFaxDecodeParameters.K < 0) { imageData.Compression = Compression.CCITTFAX4; } using (MemoryStream stream = new MemoryStream(GetTiffImageBufferFromCCITTFaxDecode(imageData, dictionary.Stream.Value))) { using (Tiff tiff = Tiff.ClientOpen("<INLINE>", "r", stream, new TiffStream())) { if (tiff == null) { return(null); } int stride = tiff.ScanlineSize(); byte[] buffer = new byte[stride]; for (int i = 0; i < imageData.Height; i++) { tiff.ReadScanline(buffer, i); Rectangle imgRect = new Rectangle(0, i, imageData.Width, 1); BitmapData imgData = bitmap.LockBits(imgRect, ImageLockMode.WriteOnly, PixelFormat.Format1bppIndexed); Marshal.Copy(buffer, 0, imgData.Scan0, buffer.Length); bitmap.UnlockBits(imgData); } } } return(bitmap); }
private void createDataArray(int xSize, int ySize, string data) { var resolution = 72; var bitPerSample = 16; var samplePerPixel = 1; Regex regex = new Regex("[^,\\r\\n]+,[^,\\r\\n]+"); MatchCollection mc = regex.Matches(data); using (Tiff output = Tiff.Open(this.saveFilename, "w")) { if (output == null) { return; } ushort[] image = new ushort[xSize * ySize]; int index = 0; foreach (Match m in mc) { string[] unit = m.Value.Split(','); if (float.Parse(unit[1]) < 0) { image[index] = 0; } else { image[index] = (ushort)(float.Parse(unit[1]) * 100 / this.scale); } index++; } output.SetField(TiffTag.IMAGEWIDTH, xSize); output.SetField(TiffTag.IMAGELENGTH, ySize); output.SetField(TiffTag.SAMPLESPERPIXEL, samplePerPixel); output.SetField(TiffTag.BITSPERSAMPLE, bitPerSample); output.SetField(TiffTag.ORIENTATION, BitMiracle.LibTiff.Classic.Orientation.TOPLEFT); output.SetField(TiffTag.XRESOLUTION, resolution); output.SetField(TiffTag.YRESOLUTION, resolution); output.SetField(TiffTag.PLANARCONFIG, PlanarConfig.CONTIG); output.SetField(TiffTag.PHOTOMETRIC, Photometric.MINISBLACK); output.SetField(TiffTag.COMPRESSION, Compression.NONE); output.SetField(TiffTag.FILLORDER, FillOrder.MSB2LSB); byte[] byteBuffer = new byte[image.Length * sizeof(ushort)]; Buffer.BlockCopy(image, 0, byteBuffer, 0, byteBuffer.Length); output.WriteEncodedStrip(0, byteBuffer, byteBuffer.Length); output.WriteDirectory(); } }
/* public static IEnumerable<(Image image, int? frameIndex, ImageMetadata metadata)> Open(string fileName, Stream stream, bool ownStream, int startingFrame, int frameCount) * { * return new Loader(fileName, stream, ownStream, startingFrame, frameCount); * * Tiff.SetErrorHandler(Libtiff.TiffErrorHandler); * * object sync = new object(); * * // h in mode means we will not read first directory by default * using (Tiff tiff = Tiff.ClientOpen("in-memory", "rh", stream, new TiffStream())) * { * int numberOfFrames = (int)tiff.NumberOfDirectories(); * int lastFrame = Math.Min(numberOfFrames, startingFrame + (frameCount > 0 ? frameCount : numberOfFrames)) - 1; * * if (!tiff.SetDirectory((short)startingFrame)) * { * yield break; * } * * bool cont = true; * while (cont) * { * // need locking for parallel linq * (Image image, ImageMetadata metadata) frame; * int? frameIndex = numberOfFrames == 1 ? null : (int?)startingFrame; * lock (sync) * { * frame = ExtractFrame(); * * cont = ++startingFrame < lastFrame; * if (cont) * { * tiff.ReadDirectory(); * } * } * * yield return (frame.image, frameIndex, frame.metadata); * } * } * }*/ public static void Save(Stream stream, Image image, ImageMetadata metadata, TIFFCompression compression) { using (MemoryStream ms = new MemoryStream()) { Tiff.SetErrorHandler(Libtiff.TiffErrorHandler); using (Tiff tiff = Tiff.ClientOpen("in-memory", "w", ms, new TiffStream())) { Libtiff.Save(tiff, image, metadata, compression); stream.Write(ms.GetBuffer(), 0, (int)ms.Length); } } }
/// <summary> /// Decode a hunk of pixels. /// </summary> private bool DumpModeDecode(byte[] buffer, int offset, int count, short plane) { if (m_tif.m_rawcc < count) { Tiff.ErrorExt(m_tif, m_tif.m_clientdata, m_tif.m_name, "DumpModeDecode: Not enough data for scanline {0}", m_tif.m_row); return(false); } Buffer.BlockCopy(m_tif.m_rawdata, m_tif.m_rawcp, buffer, offset, count); m_tif.m_rawcp += count; m_tif.m_rawcc -= count; return(true); }
public static void Main() { File.Copy(@"Sample Data\16bit.tif", @"Sample Data\ToBeAppended.tif", true); using (Tiff image = Tiff.Open(@"Sample Data\ToBeAppended.tif", "a")) { int newPageNumber = image.NumberOfDirectories() + 1; const int width = 100; const int height = 100; image.SetField(TiffTag.IMAGEWIDTH, width); image.SetField(TiffTag.IMAGELENGTH, height); image.SetField(TiffTag.BITSPERSAMPLE, 8); image.SetField(TiffTag.SAMPLESPERPIXEL, 3); image.SetField(TiffTag.ROWSPERSTRIP, height); image.SetField(TiffTag.COMPRESSION, Compression.LZW); image.SetField(TiffTag.PHOTOMETRIC, Photometric.RGB); image.SetField(TiffTag.FILLORDER, FillOrder.MSB2LSB); image.SetField(TiffTag.PLANARCONFIG, PlanarConfig.CONTIG); byte[] buffer = null; using (Bitmap bmp = new Bitmap(width, height, PixelFormat.Format24bppRgb)) { using (Graphics g = Graphics.FromImage(bmp)) { g.FillRectangle(Brushes.White, g.VisibleClipBounds); string s = newPageNumber.ToString(); Font f = SystemFonts.DefaultFont; SizeF size = g.MeasureString(s, f); PointF loc = new PointF(Math.Max((bmp.Width - size.Width) / 2, 0), Math.Max((bmp.Height - size.Height) / 2, 0)); g.DrawString(s, f, Brushes.Black, loc); buffer = getImageRasterBytes(bmp, PixelFormat.Format24bppRgb); } } int stride = buffer.Length / height; convertRGBSamples(buffer, width, height); for (int i = 0, offset = 0; i < height; i++) { image.WriteScanline(buffer, offset, i, 0); offset += stride; } } Process.Start(@"Sample Data\ToBeAppended.tif"); }
public static MemoryStream CreateGeoTiff(Tiff sourceTiff, string name, double north, double west, int width, int height, short[] data) { var tempFile = CreateGeoTiffFile(sourceTiff, name, north, west, width, height, data); var tiffStream = new MemoryStream(); using (var fileStream = tempFile.OpenRead()) { fileStream.CopyTo(tiffStream); } tempFile.Delete(); return(tiffStream); }
private static void CopyTags(Tiff sourceTiff, Tiff targetTiff) { TiffTag[] tagsToIgnore = { TiffTag.STRIPBYTECOUNTS, TiffTag.STRIPOFFSETS, TiffTag.TILEBYTECOUNTS, TiffTag.TILEOFFSETS, TiffTag.DOCUMENTNAME, TiffTag.IMAGEWIDTH, TiffTag.IMAGELENGTH, TiffTag.GEOTIFF_MODELTIEPOINTTAG, TiffTag.GEOTIFF_MODELPIXELSCALETAG }; var tagsToCopy = Enum.GetValues(typeof(TiffTag)) .OfType <TiffTag>() .Where(tag => sourceTiff.GetField(tag) != null) .Except(tagsToIgnore) .ToArray(); foreach (var tag in tagsToCopy) { targetTiff.SetField(tag, sourceTiff.GetField(tag).Select(t => t.Value).ToArray()); } }
public TIF(string fileName) : base(fileName) { using (Tiff tiff = Tiff.Open(fileName, "r")) { if (tiff != null) { pageCount = tiff.NumberOfDirectories(); } else { throw new Exception("Could not open TIF file."); } } }
private static string writeTiffWithCustomTags(byte[] buffer) { string outputFileName = "output.tif"; using (Tiff image = Tiff.Open(outputFileName, "w")) { // set up some basic tags before adding data image.SetField(TiffTag.IMAGEWIDTH, 25 * 8); image.SetField(TiffTag.IMAGELENGTH, 144); image.SetField(TiffTag.BITSPERSAMPLE, 1); image.SetField(TiffTag.SAMPLESPERPIXEL, 1); image.SetField(TiffTag.ROWSPERSTRIP, 144); image.SetField(TiffTag.COMPRESSION, Compression.CCITTFAX4); image.SetField(TiffTag.PHOTOMETRIC, Photometric.MINISWHITE); image.SetField(TiffTag.FILLORDER, FillOrder.MSB2LSB); image.SetField(TiffTag.PLANARCONFIG, PlanarConfig.CONTIG); image.SetField(TiffTag.XRESOLUTION, 150.0); image.SetField(TiffTag.YRESOLUTION, 150.0); image.SetField(TiffTag.RESOLUTIONUNIT, ResUnit.INCH); // set custom tags string value = "Tag contents"; image.SetField(TIFFTAG_ASCIITAG, value); short[] shorts = { 263, 264 }; image.SetField(TIFFTAG_SHORTTAG, 2, shorts); int[] longs = { 117, 118 }; image.SetField(TIFFTAG_LONGTAG, 2, longs); float[] rationals = { 0.333333f, 0.444444f }; image.SetField(TIFFTAG_RATIONALTAG, 2, rationals); float[] floats = { 0.666666f, 0.777777f }; image.SetField(TIFFTAG_FLOATTAG, 2, floats); double[] doubles = { 0.1234567, 0.7654321 }; image.SetField(TIFFTAG_DOUBLETAG, 2, doubles); byte[] bytes = { 89, 90 }; image.SetField(TIFFTAG_BYTETAG, 2, bytes); // Write the information to the file image.WriteEncodedStrip(0, buffer, 25 * 144); } return(outputFileName); }
public static void Main() { using (Tiff tif = Tiff.Open(@"Sample data\dscf0013.tif", "r")) { // Find the width and height of the image FieldValue[] value = tif.GetField(TiffTag.IMAGEWIDTH); int width = value[0].ToInt(); value = tif.GetField(TiffTag.IMAGELENGTH); int height = value[0].ToInt(); // Read the image into the memory buffer int[] raster = new int[height * width]; if (!tif.ReadRGBAImage(width, height, raster)) { System.Windows.Forms.MessageBox.Show("Could not read image"); return; } using (Bitmap bmp = new Bitmap(width, height, PixelFormat.Format32bppRgb)) { Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height); BitmapData bmpdata = bmp.LockBits(rect, ImageLockMode.ReadWrite, PixelFormat.Format32bppRgb); byte[] bits = new byte[bmpdata.Stride * bmpdata.Height]; for (int y = 0; y < bmp.Height; y++) { int rasterOffset = y * bmp.Width; int bitsOffset = (bmp.Height - y - 1) * bmpdata.Stride; for (int x = 0; x < bmp.Width; x++) { int rgba = raster[rasterOffset++]; bits[bitsOffset++] = (byte)((rgba >> 16) & 0xff); bits[bitsOffset++] = (byte)((rgba >> 8) & 0xff); bits[bitsOffset++] = (byte)(rgba & 0xff); bits[bitsOffset++] = (byte)((rgba >> 24) & 0xff); } } System.Runtime.InteropServices.Marshal.Copy(bits, 0, bmpdata.Scan0, bits.Length); bmp.UnlockBits(bmpdata); bmp.Save("TiffTo32BitBitmap.bmp"); System.Diagnostics.Process.Start("TiffTo32BitBitmap.bmp"); } } }
public static short[] GetElevationMap(Tiff tiff) { int stripCount = tiff.NumberOfStrips(); int stripSize = tiff.StripSize(); var elevationMap = new short[stripCount * stripSize]; byte[] buffer = new byte[stripSize]; for (int stripIndex = 0; stripIndex < stripCount; stripIndex++) { tiff.ReadEncodedStrip(stripIndex, buffer, 0, -1); Buffer.BlockCopy(buffer, 0, elevationMap, stripIndex * stripSize, stripSize); } return(elevationMap); }
public void CanWriteStream() { string hash1, hash2; using (var stream = new MemoryStream()) { var tiff = new Tiff(SamplesList.LAB); tiff.Save(stream); stream.Seek(0, SeekOrigin.Begin); hash1 = Convert.ToBase64String(System.Security.Cryptography.MD5.Create().ComputeHash(stream)); } hash2 = CheckRewrite(SamplesList.LAB); Assert.Equal(hash1, hash2); }
public void TestStripOffsetsArePositive(string name) { string fn = Path.Combine(TestCase.Folder, name); using (Tiff tiff = Tiff.Open(fn, "r")) { FieldValue[] fieldValues = tiff.GetField(TiffTag.STRIPOFFSETS); long[] offsets = fieldValues[0].TolongArray(); foreach (long offset in offsets) { Assert.GreaterOrEqual(offset, 0); } } }
/// <summary> /// Fills input buffer /// </summary> /// <returns> /// <c>true</c> if operation succeed; otherwise, <c>false</c> /// </returns> public override bool fill_input_buffer() { Tiff tif = m_sp.GetTiff(); byte[] mem = null; uint len = 0; if (!m_sp.OJPEGWriteStream(out mem, out len)) { Tiff.ErrorExt(tif, tif.m_clientdata, "LibJpeg", "Premature end of JPEG data"); } initInternalBuffer(mem, (int)len); return(true); }
public override FieldValue[] GetField(Tiff tif, TiffTag tag) { DeflateCodec sp = tif.m_currentCodec as DeflateCodec; Debug.Assert(sp != null); switch (tag) { case TiffTag.ZIPQUALITY: FieldValue[] result = new FieldValue[1]; result[0].Set(sp.m_zipquality); return result; } return base.GetField(tif, tag); }
private static void TagExtender(Tiff tif) { TiffFieldInfo[] tiffFieldInfo = { new TiffFieldInfo(TIFFTAG_CellTool_METADATA, -1, -1, TiffType.ASCII, FieldBit.Custom, true, false, "CellTool_Metadata"), }; tif.MergeFieldInfo(tiffFieldInfo, tiffFieldInfo.Length); if (m_parentExtender != null) { m_parentExtender(tif); } }
public void TestReadMinMaxSampleValues(string name) { string fn = Path.Combine(TestCase.Folder, name); using (Tiff tiff = Tiff.Open(fn, "r")) { FieldValue[] fieldValues = tiff.GetField(TiffTag.MINSAMPLEVALUE); uint min = fieldValues[0].ToUInt(); Assert.AreEqual(0, min); fieldValues = tiff.GetField(TiffTag.MAXSAMPLEVALUE); uint max = (uint)fieldValues[0].ToInt(); Assert.AreEqual(65535, max); } }
public oMatrix _ImportRawData14bitUncompressed(string filename) { int width, height, bitsPerSample; int filelength; int datalength; int start_addr; int pixelcount; ushort[,] output; using (Tiff input = Tiff.Open(@filename, "r")) { width = input.GetField(TiffTag.IMAGEWIDTH)[0].ToInt(); height = input.GetField(TiffTag.IMAGELENGTH)[0].ToInt(); //bitsPerSample = input.GetField(TiffTag.BITSPERSAMPLE)[0].ToInt(); bitsPerSample = 14; } output = new ushort[width, height]; pixelcount = width * height; datalength = (int)(width * height * bitsPerSample / 8f); byte[] inputByte; using (BinaryReader reader = new BinaryReader(File.Open(filename, FileMode.Open))) { filelength = (int)(new System.IO.FileInfo(filename).Length); start_addr = filelength - datalength; reader.ReadBytes(start_addr); inputByte = reader.ReadBytes(datalength); } int temp; for (int i = 0; i < datalength; i = i + 7) { //tempbuffer = reader.ReadBytes(7); /*buff.Add((ushort)((tempbuffer[0] * 64) + (tempbuffer[1] >> 2))); * buff.Add((ushort)(((((byte)(tempbuffer[1] << 6)) >> 6) * 4096) + (tempbuffer[2] * 16) + (tempbuffer[3] >> 4))); * buff.Add((ushort)(((((byte)(tempbuffer[3] << 4)) >> 4) * 1024) + (tempbuffer[4] * 4) + (tempbuffer[5] >> 6))); * buff.Add((ushort)(((((byte)(tempbuffer[5] << 2)) >> 2) * 256) + (tempbuffer[6])));*/ temp = (i / 7) << 2; output[(temp + 0) % width, (temp + 0) / width] = (ushort)((inputByte[i + 0] << 6) + (inputByte[i + 1] >> 2)); output[(temp + 1) % width, (temp + 1) / width] = (ushort)((((byte)(inputByte[i + 1] << 6)) << 6) + (inputByte[i + 2] << 4) + (inputByte[i + 3] >> 4)); output[(temp + 2) % width, (temp + 2) / width] = (ushort)((((byte)(inputByte[i + 3] << 4)) << 6) + (inputByte[i + 4] << 2) + (inputByte[i + 5] >> 6)); output[(temp + 3) % width, (temp + 3) / width] = (ushort)((((byte)(inputByte[i + 5] << 2)) << 6) + (inputByte[i + 6])); } return(new oMatrix(output)); }
private bool ZIPDecode(byte[] buffer, int offset, int count, short plane) { const string module = "ZIPDecode"; Debug.Assert(m_state == ZSTATE_INIT_DECODE); m_stream.next_out = buffer; m_stream.next_out_index = offset; m_stream.avail_out = count; do { int state = m_stream.inflate(zlibConst.Z_PARTIAL_FLUSH); if (state == zlibConst.Z_STREAM_END) { break; } if (state == zlibConst.Z_DATA_ERROR) { Tiff.ErrorExt(m_tif, m_tif.m_clientdata, module, "{0}: Decoding error at scanline {1}, {2}", m_tif.m_name, m_tif.m_row, m_stream.msg); if (m_stream.inflateSync() != zlibConst.Z_OK) { return(false); } continue; } if (state != zlibConst.Z_OK) { Tiff.ErrorExt(m_tif, m_tif.m_clientdata, module, "{0}: zlib error: {1}", m_tif.m_name, m_stream.msg); return(false); } }while (m_stream.avail_out > 0); if (m_stream.avail_out != 0) { Tiff.ErrorExt(m_tif, m_tif.m_clientdata, module, "{0}: Not enough data at scanline {1} (short {2} bytes)", m_tif.m_name, m_tif.m_row, m_stream.avail_out); return(false); } return(true); }
public static void WriteToDisk(ushort[][] data, String fileName, int imageWidth, int imageHeight, int samplesPerPixel = 1, Compression compression = Compression.NONE, int bitsPerSample = 16) { if (data == null) { throw new Exception("no data provided"); } using (Tiff imagesData = Tiff.Open(fileName, "w")) { for (uint page = 0; page < data.Length; page++) { imagesData.SetField(TiffTag.IMAGEWIDTH, imageWidth.ToString(CultureInfo.InvariantCulture)); imagesData.SetField(TiffTag.IMAGELENGTH, imageHeight.ToString(CultureInfo.InvariantCulture)); imagesData.SetField(TiffTag.COMPRESSION, compression); imagesData.SetField(TiffTag.BITSPERSAMPLE, bitsPerSample.ToString(CultureInfo.InvariantCulture)); // imageData.SetField(TiffTag.SAMPLESPERPIXEL, samplesPerPixel); imagesData.SetField(TiffTag.XRESOLUTION, 1); imagesData.SetField(TiffTag.YRESOLUTION, 1); imagesData.SetField(TiffTag.DATETIME, DateTime.Now); // imageData.SetField(TiffTag.ROWSPERSTRIP, imageHeight.ToString(CultureInfo.InvariantCulture)); imagesData.SetField(TiffTag.PLANARCONFIG, PlanarConfig.CONTIG); imagesData.SetField(TiffTag.PHOTOMETRIC, Photometric.MINISBLACK); imagesData.SetField(TiffTag.FILLORDER, FillOrder.MSB2LSB); imagesData.SetField(TiffTag.ORIENTATION, Orientation.TOPLEFT); imagesData.SetField(TiffTag.RESOLUTIONUNIT, ResUnit.CENTIMETER); imagesData.SetField(TiffTag.ARTIST, "ProjectStorm"); imagesData.SetField(TiffTag.IMAGEDESCRIPTION, "Test data constructed by openCL kernel of project storm"); // specify that it's a page within the multipage file imagesData.SetField(TiffTag.SUBFILETYPE, FileType.PAGE); // specify the page number imagesData.SetField(TiffTag.PAGENUMBER, page, data.Length); for (int i = 0; i < imageHeight; i++) { Byte[] buffer = new byte[data[page].Length * sizeof(ushort)]; Buffer.BlockCopy(data, i * imageWidth, buffer, 0, buffer.Length); imagesData.WriteScanline(buffer, i); } imagesData.WriteDirectory(); } imagesData.FlushData(); } }
public static IEnumerable <WriteableBitmap> ConvertToWriteableBitmaps(this Tiff tiff) { if (tiff == null) { throw new ArgumentNullException("tiff", "tiff is null."); } short dirs = tiff.NumberOfDirectories(); for (int i = 0; i < dirs; i++) { if (tiff.SetDirectory((short)i)) { int tileCount = tiff.NumberOfTiles(); int stripCount = tiff.NumberOfStrips(); var frameWidthField = tiff.GetField(TiffTag.IMAGEWIDTH); var frameHeightField = tiff.GetField(TiffTag.IMAGELENGTH); var compressionField = tiff.GetField(TiffTag.COMPRESSION); var xResolutionField = tiff.GetField(TiffTag.XRESOLUTION); var yResolutionField = tiff.GetField(TiffTag.YRESOLUTION); var samplesPerPixelField = tiff.GetField(TiffTag.SAMPLESPERPIXEL); int frameWidth = frameWidthField != null && frameWidthField.Length > 0 ? frameWidthField[0].ToInt() : 0; int frameHeight = frameHeightField != null && frameHeightField.Length > 0 ? frameHeightField[0].ToInt() : 0; var compression = compressionField != null && compressionField.Length > 0 ? (Compression)compressionField[0].Value : Compression.NONE; var xResolution = xResolutionField != null && xResolutionField.Length > 0 ? new double?(xResolutionField[0].ToDouble()) : null; var yResolution = yResolutionField != null && yResolutionField.Length > 0 ? new double?(yResolutionField[0].ToDouble()) : null; var samplesPerPixel = samplesPerPixelField != null && samplesPerPixelField.Length > 0 ? samplesPerPixelField[0].ToString() : String.Empty; if (xResolution != null && yResolution == null) { yResolution = xResolution; } var buffer = new int[frameWidth * frameHeight]; tiff.ReadRGBAImage(frameWidth, frameHeight, buffer); var bmp = new WriteableBitmap(frameWidth, frameHeight); for (int y = 0; y < frameHeight; y++) { var ytif = y * frameWidth; var ybmp = (frameHeight - y - 1) * frameWidth; for (int x = 0; x < frameWidth; x++) { var currentValue = buffer[ytif + x]; // Shift the Tiff's RGBA format to the Silverlight WriteableBitmap's ARGB format bmp.Pixels[ybmp + x] = Tiff.GetB(currentValue) | Tiff.GetG(currentValue) << 8 | Tiff.GetR(currentValue) << 16 | Tiff.GetA(currentValue) << 24; } } yield return(bmp); } } }
public static int simcnt; // Counter for simulation public string WriteImage(byte[] arr, int row, int col) { simcnt++; string opname = "ans" + simcnt.ToString() + ".tif"; //string file = opname + filecounter.ToString() + ".tif"; // Open the TIFF file using (Tiff image = Tiff.Open(opname, "w")) { if (image == null) { MessageBox.Show("Could not open " + opname + " for writing"); return(null); } image.SetField(TiffTag.IMAGEWIDTH, col); image.SetField(TiffTag.IMAGELENGTH, row); // Need some attention 1 for bilevel,grayscale and patellte colour images // 3 for RGB images image.SetField(TiffTag.SAMPLESPERPIXEL, 1); image.SetField(TiffTag.BITSPERSAMPLE, 8); image.SetField(TiffTag.ROWSPERSTRIP, row); image.SetField(TiffTag.COMPRESSION, Compression.NONE); image.SetField(TiffTag.PHOTOMETRIC, Photometric.MINISWHITE); image.SetField(TiffTag.FILLORDER, FillOrder.MSB2LSB); image.SetField(TiffTag.PLANARCONFIG, PlanarConfig.CONTIG); image.SetField(TiffTag.XRESOLUTION, 3000); image.SetField(TiffTag.YRESOLUTION, 3000); image.SetField(TiffTag.RESOLUTIONUNIT, ResUnit.CENTIMETER); int c = 0; for (int i = 0; i < row; i++) { byte[] buf = new byte[col]; for (int j = 0; j < col; j++) { buf[j] = arr[c + j]; } image.WriteScanline(buf, i); c += col; } image.WriteDirectory(); image.Close(); } return(opname); }
private static double GetAltNoCache(geotiffdata geotiffdata, int x, int y) { byte[] scanline; lock (cachescanlines) scanline = cachescanlines.Get(geotiffdata.FileName + x.ToString()) as byte[]; if (scanline == null) { //Task.Run(() => { lock (geotiffdata) if (geotiffdata.Tiff == null) { geotiffdata.Tiff = Tiff.Open(geotiffdata.FileName, "r"); } lock (geotiffdata.Tiff) { lock (cachescanlines) scanline = cachescanlines.Get(geotiffdata.FileName + x.ToString()) as byte[]; if (scanline == null) { if (geotiffdata.Tiff.GetField(TiffTag.TILEWIDTH) != null && geotiffdata.Tiff.GetField(TiffTag.TILEWIDTH).Length >= 1) { //log.Info("read tile scanline " + x); //return short.MinValue; ExtractScanLineFromTile(geotiffdata, x); lock (cachescanlines) scanline = cachescanlines.Get(geotiffdata.FileName + x.ToString()) as byte[]; } else { //log.Info("read scanline " + x); scanline = new byte[geotiffdata.Tiff.ScanlineSize()]; geotiffdata.Tiff.ReadScanline(scanline, x); AddToCache(geotiffdata, x, scanline); } } } } //); //return short.MinValue; } return(ProcessScanLine(geotiffdata, y, scanline)); }
public void ReadExifTags() { string path = System.IO.Path.Combine(TestCase.Folder, "dscf0013.tif"); using (Tiff image = Tiff.Open(path, "r")) { FieldValue[] exifIfd = image.GetField(TiffTag.EXIFIFD); Assert.IsNotNull(exifIfd); Assert.That(exifIfd.Length, Is.EqualTo(1)); int exifIFDOffset = exifIfd[0].ToInt(); Assert.That(exifIFDOffset, Is.EqualTo(640)); bool readSuccessful = image.ReadEXIFDirectory(exifIFDOffset); Assert.That(readSuccessful); FieldValue[] fnumber = image.GetField(TiffTag.EXIF_FNUMBER); Assert.IsNotNull(fnumber); Assert.That(fnumber.Length, Is.EqualTo(1)); Assert.AreEqual(3.4, fnumber[0].ToDouble(), 0.001); FieldValue[] exposureProgram = image.GetField(TiffTag.EXIF_EXPOSUREPROGRAM); Assert.IsNotNull(exposureProgram); Assert.That(exposureProgram.Length, Is.EqualTo(1)); Assert.That(exposureProgram[0].ToString(), Is.EqualTo("2")); FieldValue[] dateTimeOriginal = image.GetField(TiffTag.EXIF_DATETIMEORIGINAL); Assert.IsNotNull(dateTimeOriginal); Assert.That(dateTimeOriginal.Length, Is.EqualTo(1)); //The format is "YYYY:MM:DD HH:MM:SS", see DateTimeOriginal tag description Assert.That(dateTimeOriginal[0].ToString(), Is.EqualTo("2004:11:10 00:00:31")); FieldValue[] exifVersion = image.GetField(TiffTag.EXIF_EXIFVERSION); Assert.IsNotNull(exifVersion); Assert.That(exifVersion.Length, Is.EqualTo(1)); Assert.That(exifVersion[0].ToString(), Is.EqualTo("0210")); FieldValue[] fileSource = image.GetField(TiffTag.EXIF_FILESOURCE); Assert.IsNotNull(fileSource); Assert.That(fileSource.Length, Is.EqualTo(1)); Assert.That(fileSource[0].ToByte(), Is.EqualTo(3)); FieldValue[] sceneType = image.GetField(TiffTag.EXIF_SCENETYPE); Assert.IsNotNull(sceneType); Assert.That(sceneType.Length, Is.EqualTo(1)); Assert.That(sceneType[0].ToByte(), Is.EqualTo(1)); } }
public static void Main() { int[] rotateAngles = new int[] { 90, 180, 270 }; for (int angleIndex = 0; angleIndex < rotateAngles.Length; angleIndex++) { string outputFileName = string.Format("Rotated-{0}-degrees.tif", rotateAngles[angleIndex]); using (Tiff input = Tiff.Open(@"Sample Data\flag_t24.tif", "r")) { using (Tiff output = Tiff.Open(outputFileName, "w")) { for (short page = 0; page < input.NumberOfDirectories(); page++) { input.SetDirectory(page); output.SetDirectory(page); int width = input.GetField(TiffTag.IMAGEWIDTH)[0].ToInt(); int height = input.GetField(TiffTag.IMAGELENGTH)[0].ToInt(); int samplesPerPixel = input.GetField(TiffTag.SAMPLESPERPIXEL)[0].ToInt(); int bitsPerSample = input.GetField(TiffTag.BITSPERSAMPLE)[0].ToInt(); int photo = input.GetField(TiffTag.PHOTOMETRIC)[0].ToInt(); int[] raster = new int[width * height]; input.ReadRGBAImageOriented(width, height, raster, Orientation.TOPLEFT); raster = rotate(raster, rotateAngles[angleIndex], ref width, ref height); output.SetField(TiffTag.IMAGEWIDTH, width); output.SetField(TiffTag.IMAGELENGTH, height); output.SetField(TiffTag.SAMPLESPERPIXEL, 3); output.SetField(TiffTag.BITSPERSAMPLE, 8); output.SetField(TiffTag.ROWSPERSTRIP, height); output.SetField(TiffTag.PHOTOMETRIC, Photometric.RGB); output.SetField(TiffTag.PLANARCONFIG, PlanarConfig.CONTIG); output.SetField(TiffTag.COMPRESSION, Compression.DEFLATE); byte[] strip = rasterToRgbBuffer(raster); output.WriteEncodedStrip(0, strip, strip.Length); output.WriteDirectory(); } } } Process.Start(outputFileName); } }
public static void Main() { byte[] inputBytes = File.ReadAllBytes(@"Sample Data\multipage.tif"); TiffStreamForBytes byteStream = new TiffStreamForBytes(inputBytes); using (Tiff input = Tiff.ClientOpen("bytes", "r", null, byteStream)) { if (input == null) { MessageBox.Show("Could not open incoming image"); return; } if (input.IsTiled()) { MessageBox.Show("Could not process tiled image"); return; } using (MemoryStream ms = new MemoryStream()) { using (Tiff output = Tiff.ClientOpen("InMemory", "w", ms, new TiffStream())) { int numberOfDirectories = input.NumberOfDirectories(); for (short i = 0; i < numberOfDirectories; ++i) { input.SetDirectory(i); copyTags(input, output); copyStrips(input, output); output.WriteDirectory(); } } // retrieve bytes from memory stream and write them in a file byte[] bytes = ms.ToArray(); File.WriteAllBytes("SavedBytes.tif", bytes); } } using (Tiff result = Tiff.Open("SavedBytes.tif", "rc")) { MessageBox.Show("Number of strips in result file: " + result.NumberOfStrips()); } Process.Start("SavedBytes.tif"); }
public override FieldValue[] GetField(Tiff tif, TiffTag tag) { CCITTCodec sp = tif.m_currentCodec as CCITTCodec; Debug.Assert(sp != null); FieldValue[] result = new FieldValue[1]; switch (tag) { case TiffTag.FAXMODE: result[0].Set(sp.m_mode); break; case TiffTag.FAXFILLFUNC: result[0].Set(sp.fill); break; case TiffTag.GROUP3OPTIONS: case TiffTag.GROUP4OPTIONS: result[0].Set(sp.m_groupoptions); break; case TiffTag.BADFAXLINES: result[0].Set(sp.m_badfaxlines); break; case TiffTag.CLEANFAXDATA: result[0].Set(sp.m_cleanfaxdata); break; case TiffTag.CONSECUTIVEBADFAXLINES: result[0].Set(sp.m_badfaxrun); break; case TiffTag.FAXRECVPARAMS: result[0].Set(sp.m_recvparams); break; case TiffTag.FAXSUBADDRESS: result[0].Set(sp.m_subaddress); break; case TiffTag.FAXRECVTIME: result[0].Set(sp.m_recvtime); break; case TiffTag.FAXDCS: result[0].Set(sp.m_faxdcs); break; default: return base.GetField(tif, tag); } return result; }
public override FieldValue[] GetField(Tiff tif, TiffTag tag) { CodecWithPredictor sp = tif.m_currentCodec as CodecWithPredictor; Debug.Assert(sp != null); switch (tag) { case TiffTag.PREDICTOR: FieldValue[] result = new FieldValue[1]; result[0].Set(sp.GetPredictorValue()); return result; } TiffTagMethods childMethods = sp.GetChildTagMethods(); if (childMethods != null) return childMethods.GetField(tif, tag); return base.GetField(tif, tag); }
public override bool SetField(Tiff tif, TiffTag tag, FieldValue[] ap) { CodecWithPredictor sp = tif.m_currentCodec as CodecWithPredictor; Debug.Assert(sp != null); switch (tag) { case TiffTag.PREDICTOR: sp.SetPredictorValue((Predictor)ap[0].ToByte()); tif.setFieldBit(CodecWithPredictor.FIELD_PREDICTOR); tif.m_flags |= TiffFlags.DIRTYDIRECT; return true; } TiffTagMethods childMethods = sp.GetChildTagMethods(); if (childMethods != null) return childMethods.SetField(tif, tag, ap); return base.SetField(tif, tag, ap); }
public override void PrintDir(Tiff tif, Stream fd, TiffPrintFlags flags) { OJpegCodec sp = tif.m_currentCodec as OJpegCodec; Debug.Assert(sp != null); if (tif.fieldSet(OJpegCodec.FIELD_OJPEG_JPEGINTERCHANGEFORMAT)) Tiff.fprintf(fd, " JpegInterchangeFormat: {0}\n", sp.m_jpeg_interchange_format); if (tif.fieldSet(OJpegCodec.FIELD_OJPEG_JPEGINTERCHANGEFORMATLENGTH)) Tiff.fprintf(fd, " JpegInterchangeFormatLength: {0}\n", sp.m_jpeg_interchange_format_length); if (tif.fieldSet(OJpegCodec.FIELD_OJPEG_JPEGQTABLES)) { Tiff.fprintf(fd, " JpegQTables:"); for (byte m = 0; m < sp.m_qtable_offset_count; m++) Tiff.fprintf(fd, " {0}", sp.m_qtable_offset[m]); Tiff.fprintf(fd, "\n"); } if (tif.fieldSet(OJpegCodec.FIELD_OJPEG_JPEGDCTABLES)) { Tiff.fprintf(fd, " JpegDcTables:"); for (byte m = 0; m < sp.m_dctable_offset_count; m++) Tiff.fprintf(fd, " {0}", sp.m_dctable_offset[m]); Tiff.fprintf(fd, "\n"); } if (tif.fieldSet(OJpegCodec.FIELD_OJPEG_JPEGACTABLES)) { Tiff.fprintf(fd, " JpegAcTables:"); for (byte m = 0; m < sp.m_actable_offset_count; m++) Tiff.fprintf(fd, " {0}", sp.m_actable_offset[m]); Tiff.fprintf(fd, "\n"); } if (tif.fieldSet(OJpegCodec.FIELD_OJPEG_JPEGPROC)) Tiff.fprintf(fd, " JpegProc: {0}\n", sp.m_jpeg_proc); if (tif.fieldSet(OJpegCodec.FIELD_OJPEG_JPEGRESTARTINTERVAL)) Tiff.fprintf(fd, " JpegRestartInterval: {0}\n", sp.m_restart_interval); }
public JpegStdDestination(Tiff tif) { m_tif = tif; }
public override void PrintDir(Tiff tif, Stream fd, TiffPrintFlags flags) { JpegCodec sp = tif.m_currentCodec as JpegCodec; Debug.Assert(sp != null); if (tif.fieldSet(JpegCodec.FIELD_JPEGTABLES)) Tiff.fprintf(fd, " JPEG Tables: ({0} bytes)\n", sp.m_jpegtables_length); if (tif.fieldSet(JpegCodec.FIELD_RECVPARAMS)) Tiff.fprintf(fd, " Fax Receive Parameters: {0,8:x}\n", sp.m_recvparams); if (tif.fieldSet(JpegCodec.FIELD_SUBADDRESS)) Tiff.fprintf(fd, " Fax SubAddress: {0}\n", sp.m_subaddress); if (tif.fieldSet(JpegCodec.FIELD_RECVTIME)) Tiff.fprintf(fd, " Fax Receive Time: {0} secs\n", sp.m_recvtime); if (tif.fieldSet(JpegCodec.FIELD_FAXDCS)) Tiff.fprintf(fd, " Fax DCS: {0}\n", sp.m_faxdcs); }
public override bool SetField(Tiff tif, TiffTag tag, FieldValue[] ap) { JpegCodec sp = tif.m_currentCodec as JpegCodec; Debug.Assert(sp != null); switch (tag) { case TiffTag.JPEGTABLES: int v32 = ap[0].ToInt(); if (v32 == 0) { // XXX return false; } sp.m_jpegtables = new byte [v32]; Buffer.BlockCopy(ap[1].ToByteArray(), 0, sp.m_jpegtables, 0, v32); sp.m_jpegtables_length = v32; tif.setFieldBit(JpegCodec.FIELD_JPEGTABLES); break; case TiffTag.JPEGQUALITY: sp.m_jpegquality = ap[0].ToInt(); return true; // pseudo tag case TiffTag.JPEGCOLORMODE: sp.m_jpegcolormode = (JpegColorMode)ap[0].ToShort(); sp.JPEGResetUpsampled(); return true; // pseudo tag case TiffTag.PHOTOMETRIC: bool ret_value = base.SetField(tif, tag, ap); sp.JPEGResetUpsampled(); return ret_value; case TiffTag.JPEGTABLESMODE: sp.m_jpegtablesmode = (JpegTablesMode)ap[0].ToShort(); return true; // pseudo tag case TiffTag.YCBCRSUBSAMPLING: // mark the fact that we have a real ycbcrsubsampling! sp.m_ycbcrsampling_fetched = true; // should we be recomputing upsampling info here? return base.SetField(tif, tag, ap); case TiffTag.FAXRECVPARAMS: sp.m_recvparams = ap[0].ToInt(); break; case TiffTag.FAXSUBADDRESS: Tiff.setString(out sp.m_subaddress, ap[0].ToString()); break; case TiffTag.FAXRECVTIME: sp.m_recvtime = ap[0].ToInt(); break; case TiffTag.FAXDCS: Tiff.setString(out sp.m_faxdcs, ap[0].ToString()); break; default: return base.SetField(tif, tag, ap); } TiffFieldInfo fip = tif.FieldWithTag(tag); if (fip != null) tif.setFieldBit(fip.Bit); else return false; tif.m_flags |= TiffFlags.DIRTYDIRECT; return true; }
/* * Some JPEG-in-TIFF produces do not emit the YCBCRSUBSAMPLING values in * the TIFF tags, but still use non-default (2,2) values within the jpeg * data stream itself. In order for TIFF applications to work properly * - for instance to get the strip buffer size right - it is imperative * that the subsampling be available before we start reading the image * data normally. This function will attempt to load the first strip in * order to get the sampling values from the jpeg data stream. Various * hacks are various places are done to ensure this function gets called * before the td_ycbcrsubsampling values are used from the directory structure, * including calling TIFFGetField() for the YCBCRSUBSAMPLING field from * TIFFStripSize(), and the printing code in tif_print.c. * * Note that JPEGPreDeocode() will produce a fairly loud warning when the * discovered sampling does not match the default sampling (2,2) or whatever * was actually in the tiff tags. * * Problems: * o This code will cause one whole strip/tile of compressed data to be * loaded just to get the tags right, even if the imagery is never read. * It would be more efficient to just load a bit of the header, and * initialize things from that. * * See the bug in bugzilla for details: * * http://bugzilla.remotesensing.org/show_bug.cgi?id=168 * * Frank Warmerdam, July 2002 */ private static void JPEGFixupTestSubsampling(Tiff tif) { if (Tiff.CHECK_JPEG_YCBCR_SUBSAMPLING) { JpegCodec sp = tif.m_currentCodec as JpegCodec; Debug.Assert(sp != null); sp.InitializeLibJPEG(false, false); /* * Some JPEG-in-TIFF files don't provide the ycbcrsampling tags, * and use a sampling schema other than the default 2,2. To handle * this we actually have to scan the header of a strip or tile of * jpeg data to get the sampling. */ if (!sp.m_common.IsDecompressor || sp.m_ycbcrsampling_fetched || tif.m_dir.td_photometric != Photometric.YCBCR) { return; } sp.m_ycbcrsampling_fetched = true; if (tif.IsTiled()) { if (!tif.fillTile(0)) return; } else { if (!tif.fillStrip(0)) return; } tif.SetField(TiffTag.YCBCRSUBSAMPLING, sp.m_h_sampling, sp.m_v_sampling); // We want to clear the loaded strip so the application has time // to set JPEGCOLORMODE or other behavior modifiers. This essentially // undoes the JPEGPreDecode triggers by FileStrip(). tif.m_curstrip = -1; } }
public override void PrintDir(Tiff tif, Stream fd, TiffPrintFlags flags) { CCITTCodec sp = tif.m_currentCodec as CCITTCodec; Debug.Assert(sp != null); if (tif.fieldSet(CCITTCodec.FIELD_OPTIONS)) { string sep = " "; if (tif.m_dir.td_compression == Compression.CCITTFAX4) { Tiff.fprintf(fd, " Group 4 Options:"); if ((sp.m_groupoptions & Group3Opt.UNCOMPRESSED) != 0) Tiff.fprintf(fd, "{0}uncompressed data", sep); } else { Tiff.fprintf(fd, " Group 3 Options:"); if ((sp.m_groupoptions & Group3Opt.ENCODING2D) != 0) { Tiff.fprintf(fd, "{0}2-d encoding", sep); sep = "+"; } if ((sp.m_groupoptions & Group3Opt.FILLBITS) != 0) { Tiff.fprintf(fd, "{0}EOL padding", sep); sep = "+"; } if ((sp.m_groupoptions & Group3Opt.UNCOMPRESSED) != 0) Tiff.fprintf(fd, "{0}uncompressed data", sep); } Tiff.fprintf(fd, " ({0} = 0x{1:x})\n", sp.m_groupoptions, sp.m_groupoptions); } if (tif.fieldSet(CCITTCodec.FIELD_CLEANFAXDATA)) { Tiff.fprintf(fd, " Fax Data:"); switch (sp.m_cleanfaxdata) { case CleanFaxData.CLEAN: Tiff.fprintf(fd, " clean"); break; case CleanFaxData.REGENERATED: Tiff.fprintf(fd, " receiver regenerated"); break; case CleanFaxData.UNCLEAN: Tiff.fprintf(fd, " uncorrected errors"); break; } Tiff.fprintf(fd, " ({0} = 0x{1:x})\n", sp.m_cleanfaxdata, sp.m_cleanfaxdata); } if (tif.fieldSet(CCITTCodec.FIELD_BADFAXLINES)) Tiff.fprintf(fd, " Bad Fax Lines: {0}\n", sp.m_badfaxlines); if (tif.fieldSet(CCITTCodec.FIELD_BADFAXRUN)) Tiff.fprintf(fd, " Consecutive Bad Fax Lines: {0}\n", sp.m_badfaxrun); if (tif.fieldSet(CCITTCodec.FIELD_RECVPARAMS)) Tiff.fprintf(fd, " Fax Receive Parameters: {0,8:x}\n", sp.m_recvparams); if (tif.fieldSet(CCITTCodec.FIELD_SUBADDRESS)) Tiff.fprintf(fd, " Fax SubAddress: {0}\n", sp.m_subaddress); if (tif.fieldSet(CCITTCodec.FIELD_RECVTIME)) Tiff.fprintf(fd, " Fax Receive Time: {0} secs\n", sp.m_recvtime); if (tif.fieldSet(CCITTCodec.FIELD_FAXDCS)) Tiff.fprintf(fd, " Fax DCS: {0}\n", sp.m_faxdcs); }
public override bool SetField(Tiff tif, TiffTag tag, FieldValue[] ap) { const string module = "OJPEGVSetField"; OJpegCodec sp = tif.m_currentCodec as OJpegCodec; Debug.Assert(sp != null); uint ma; uint[] mb; uint n; switch (tag) { case TiffTag.JPEGIFOFFSET: sp.m_jpeg_interchange_format = ap[0].ToUInt(); break; case TiffTag.JPEGIFBYTECOUNT: sp.m_jpeg_interchange_format_length = ap[0].ToUInt(); break; case TiffTag.YCBCRSUBSAMPLING: sp.m_subsampling_tag = true; sp.m_subsampling_hor = ap[0].ToByte(); sp.m_subsampling_ver = ap[1].ToByte(); tif.m_dir.td_ycbcrsubsampling[0] = sp.m_subsampling_hor; tif.m_dir.td_ycbcrsubsampling[1] = sp.m_subsampling_ver; break; case TiffTag.JPEGQTABLES: ma = ap[0].ToUInt(); if (ma != 0) { if (ma > 3) { Tiff.ErrorExt(tif, tif.m_clientdata, module, "JpegQTables tag has incorrect count"); return false; } sp.m_qtable_offset_count = (byte)ma; mb = ap[1].ToUIntArray(); for (n = 0; n < ma; n++) sp.m_qtable_offset[n] = mb[n]; } break; case TiffTag.JPEGDCTABLES: ma = ap[0].ToUInt(); if (ma != 0) { if (ma > 3) { Tiff.ErrorExt(tif, tif.m_clientdata, module, "JpegDcTables tag has incorrect count"); return false; } sp.m_dctable_offset_count = (byte)ma; mb = ap[1].ToUIntArray(); for (n = 0; n < ma; n++) sp.m_dctable_offset[n] = mb[n]; } break; case TiffTag.JPEGACTABLES: ma = ap[0].ToUInt(); if (ma != 0) { if (ma > 3) { Tiff.ErrorExt(tif, tif.m_clientdata, module, "JpegAcTables tag has incorrect count"); return false; } sp.m_actable_offset_count = (byte)ma; mb = ap[1].ToUIntArray(); for (n = 0; n < ma; n++) sp.m_actable_offset[n] = mb[n]; } break; case TiffTag.JPEGPROC: sp.m_jpeg_proc = ap[0].ToByte(); break; case TiffTag.JPEGRESTARTINTERVAL: sp.m_restart_interval = ap[0].ToUShort(); break; default: return base.SetField(tif, tag, ap); } TiffFieldInfo fip = tif.FieldWithTag(tag); if (fip != null) tif.setFieldBit(fip.Bit); else return false; tif.m_flags |= TiffFlags.DIRTYDIRECT; return true; }
private int m_offset; // current position in m_buffer public CCITTCodec(Tiff tif, Compression scheme, string name) : base(tif, scheme, name) { m_tagMethods = new CCITTCodecTagMethods(); }
public CodecWithPredictor(Tiff tif, Compression scheme, string name) : base(tif, scheme, name) { m_tagMethods = new CodecWithPredictorTagMethods(); }
/// <summary> /// Initializes a new instance of the <see cref="TiffCodec"/> class. /// </summary> /// <param name="tif">An instance of <see cref="Tiff"/> class.</param> /// <param name="scheme">The compression scheme for the codec.</param> /// <param name="name">The name of the codec.</param> public TiffCodec(Tiff tif, Compression scheme, string name) { m_scheme = scheme; m_tif = tif; m_name = name; }
private hash_t[] m_enc_hashtab; /* kept separate for small machines */ public LZWCodec(Tiff tif, Compression scheme, string name) : base(tif, scheme, name) { }
public PackBitsCodec(Tiff tif, Compression scheme, string name) : base(tif, scheme, name) { }