public void EncoderOptions_SetPhotometricInterpretationAndCompression_Works( TiffPhotometricInterpretation?photometricInterpretation, TiffCompression compression, TiffBitsPerPixel expectedBitsPerPixel, TiffCompression expectedCompression) { // arrange var tiffEncoder = new TiffEncoder { PhotometricInterpretation = photometricInterpretation, Compression = compression }; using Image input = new Image <Rgb24>(10, 10); using var memStream = new MemoryStream(); // act input.Save(memStream, tiffEncoder); // assert memStream.Position = 0; using var output = Image.Load <Rgba32>(memStream); TiffFrameMetadata rootFrameMetaData = output.Frames.RootFrame.Metadata.GetTiffMetadata(); Assert.Equal(expectedBitsPerPixel, rootFrameMetaData.BitsPerPixel); Assert.Equal(expectedCompression, rootFrameMetaData.Compression); }
protected static void TestTiffEncoderCore <TPixel>( TestImageProvider <TPixel> provider, TiffBitsPerPixel?bitsPerPixel, TiffPhotometricInterpretation photometricInterpretation, TiffCompression compression = TiffCompression.None, TiffPredictor predictor = TiffPredictor.None, bool useExactComparer = true, float compareTolerance = 0.001f, IImageDecoder imageDecoder = null) where TPixel : unmanaged, IPixel <TPixel> { using Image <TPixel> image = provider.GetImage(); var encoder = new TiffEncoder { PhotometricInterpretation = photometricInterpretation, BitsPerPixel = bitsPerPixel, Compression = compression, HorizontalPredictor = predictor }; // Does DebugSave & load reference CompareToReferenceInput(): image.VerifyEncoder( provider, "tiff", bitsPerPixel, encoder, useExactComparer ? ImageComparer.Exact : ImageComparer.Tolerant(compareTolerance), referenceDecoder: imageDecoder ?? ReferenceDecoder); }
private EncoderValue GetEncoderValue(TiffCompression compression, Bitmap bitmap) { switch (compression) { case TiffCompression.None: return(EncoderValue.CompressionNone); case TiffCompression.Ccitt4: return(EncoderValue.CompressionCCITT4); case TiffCompression.Lzw: return(EncoderValue.CompressionLZW); default: if (bitmap.PixelFormat == PixelFormat.Format1bppIndexed && bitmap.Palette.Entries.Length == 2 && bitmap.Palette.Entries[0].ToArgb() == Color.Black.ToArgb() && bitmap.Palette.Entries[1].ToArgb() == Color.White.ToArgb()) { return(EncoderValue.CompressionCCITT4); } else { return(EncoderValue.CompressionLZW); } } }
public void DecompressStreamAsync_ThrowsException_WithUnsupportedCompression(TiffCompression compression) { var stream = new StreamBuilder(ByteOrder.LittleEndian).ToStream(); var e = Assert.Throws <NotSupportedException>(() => { TiffDecompressor.DecompressStreamAsync(stream, compression, 100, 100); }); Assert.Equal($"The compression format '{compression}' is not supported.", e.Message); }
public static TiffBaseCompressor Create( TiffCompression method, Stream output, MemoryAllocator allocator, int width, int bitsPerPixel, DeflateCompressionLevel compressionLevel, TiffPredictor predictor) { switch (method) { // The following compression types are not implemented in the encoder and will default to no compression instead. case TiffCompression.ItuTRecT43: case TiffCompression.ItuTRecT82: case TiffCompression.OldJpeg: case TiffCompression.OldDeflate: case TiffCompression.None: DebugGuard.IsTrue(compressionLevel == DeflateCompressionLevel.DefaultCompression, "No deflate compression level is expected to be set"); DebugGuard.IsTrue(predictor == TiffPredictor.None, "Predictor should only be used with lzw or deflate compression"); return(new NoCompressor(output, allocator, width, bitsPerPixel)); case TiffCompression.Jpeg: DebugGuard.IsTrue(compressionLevel == DeflateCompressionLevel.DefaultCompression, "No deflate compression level is expected to be set"); DebugGuard.IsTrue(predictor == TiffPredictor.None, "Predictor should only be used with lzw or deflate compression"); return(new TiffJpegCompressor(output, allocator, width, bitsPerPixel)); case TiffCompression.PackBits: DebugGuard.IsTrue(compressionLevel == DeflateCompressionLevel.DefaultCompression, "No deflate compression level is expected to be set"); DebugGuard.IsTrue(predictor == TiffPredictor.None, "Predictor should only be used with lzw or deflate compression"); return(new PackBitsCompressor(output, allocator, width, bitsPerPixel)); case TiffCompression.Deflate: return(new DeflateCompressor(output, allocator, width, bitsPerPixel, predictor, compressionLevel)); case TiffCompression.Lzw: DebugGuard.IsTrue(compressionLevel == DeflateCompressionLevel.DefaultCompression, "No deflate compression level is expected to be set"); return(new LzwCompressor(output, allocator, width, bitsPerPixel, predictor)); case TiffCompression.CcittGroup3Fax: DebugGuard.IsTrue(compressionLevel == DeflateCompressionLevel.DefaultCompression, "No deflate compression level is expected to be set"); DebugGuard.IsTrue(predictor == TiffPredictor.None, "Predictor should only be used with lzw or deflate compression"); return(new T4BitCompressor(output, allocator, width, bitsPerPixel, false)); case TiffCompression.CcittGroup4Fax: DebugGuard.IsTrue(compressionLevel == DeflateCompressionLevel.DefaultCompression, "No deflate compression level is expected to be set"); DebugGuard.IsTrue(predictor == TiffPredictor.None, "Predictor should only be used with lzw or deflate compression"); return(new T6BitCompressor(output, allocator, width, bitsPerPixel)); case TiffCompression.Ccitt1D: DebugGuard.IsTrue(compressionLevel == DeflateCompressionLevel.DefaultCompression, "No deflate compression level is expected to be set"); DebugGuard.IsTrue(predictor == TiffPredictor.None, "Predictor should only be used with lzw or deflate compression"); return(new T4BitCompressor(output, allocator, width, bitsPerPixel, true)); default: throw TiffThrowHelper.NotSupportedCompressor(method.ToString()); } }
public SaveAsTiffOptions(bool useAntiAliasing, bool useHighQualityRendering, int pageCount, int pageIndex, int resolution, TiffCompression tiffCompression) { UseAntiAliasing = useAntiAliasing; UseHighQualityRendering = useHighQualityRendering; PageCount = pageCount; PageIndex = pageIndex; Resolution = resolution; TiffCompression = tiffCompression; }
public SaveAsTiffOptions() { UseAntiAliasing = true; UseHighQualityRendering = true; PageCount = 1; PageIndex = 1; Resolution = 200; TiffCompression = TiffCompression.Ccitt3; }
public SaveAsTiffOptions(bool useAntiAliasing, bool useHighQualityRendering, int pageCount, int pageIndex, int resolution, TiffCompression tiffCompression) { UseAntiAliasing = useAntiAliasing; UseHighQualityRendering = useHighQualityRendering; PageCount = pageCount; PageIndex = pageIndex; Resolution = resolution; TiffCompression = tiffCompression; }
public SaveAsTiffOptions() { UseAntiAliasing = true; UseHighQualityRendering = true; PageCount = 1; PageIndex=1; Resolution = 200; TiffCompression = TiffCompression.Ccitt3; }
public static bool SupportsCompression(TiffCompression compression) { switch (compression) { case TiffCompression.None: case TiffCompression.PackBits: return(true); default: return(false); } }
/// <summary> /// Apply the write operation for the specified geometry. /// </summary> /// <param name="geometry">The geometry.</param> /// <exception cref="System.ArgumentException">The number of images in the stream has reached the maximum.</exception> protected override void ApplyWriteGeometry(IGeometry geometry) { if (_imageCount == _maxImageCount) { throw new InvalidOperationException("The number of images in the stream has reached the maximum."); } IRaster raster = (geometry as ISpectralGeometry).Raster; if (raster == null) { return; } // TODO: compute the format more exactly Int64 contentSize = (Int64)raster.RadiometricResolution / 8 * raster.NumberOfBands * raster.NumberOfColumns * raster.NumberOfRows; InitializeStream(contentSize > BigTiffThreshold ? TiffStructure.BigTiff : TiffStructure.RegularTiff); TiffCompression compression = TiffCompression.None; // TODO: support other compressions TiffSampleFormat sampleFormat = (geometry as ISpectralGeometry).Raster.Format == RasterFormat.Floating ? TiffSampleFormat.Floating : TiffSampleFormat.UnsignedInteger; TiffImageFileDirectory imageFileDirectory = ComputeImageFileDirectory(geometry as ISpectralGeometry, compression, sampleFormat); // compute and update raster content position Int64 imageFileDirectorySize = ComputeImageFileDirectorySize(imageFileDirectory); Int64 rasterContentStartPosition = _baseStream.Position + imageFileDirectorySize; Int64 rasterContentSize = ComputeRasterContentSize(raster); // strip offset and length switch (_structure) { case TiffStructure.RegularTiff: imageFileDirectory[TiffTag.StripOffsets][0] = (UInt32)rasterContentStartPosition; imageFileDirectory[TiffTag.StripByteCounts][0] = (UInt32)rasterContentSize; WriteImageFileDirectory(imageFileDirectory); break; case TiffStructure.BigTiff: imageFileDirectory[TiffTag.StripOffsets][0] = (UInt64)rasterContentStartPosition; imageFileDirectory[TiffTag.StripByteCounts][0] = (UInt64)rasterContentSize; WriteBigImageFileDirectory(imageFileDirectory); break; } // perform writing based on representation WriteRasterContentToStrip((geometry as ISpectralGeometry).Raster, compression, sampleFormat); _imageCount++; }
public static Task <byte[]> DecompressStreamAsync(Stream stream, TiffCompression compression, int compressedLength, int uncompressedLength) { switch (compression) { case TiffCompression.None: return(DecompressStreamAsync_None(stream, compressedLength)); case TiffCompression.PackBits: return(PackBitsDecompressor.DecompressStreamAsync(stream, compressedLength, uncompressedLength)); default: throw new NotSupportedException($"The compression format '{compression}' is not supported."); } }
private void LoadOptions() { RegistryKey userKey = null; RegistryKey machineKey = null; RegistryKey key; if (String.IsNullOrEmpty(RegistryKeyToStoreOptions)) { return; } try { userKey = Registry.CurrentUser.OpenSubKey("Software\\" + RegistryKeyToStoreOptions); machineKey = Registry.LocalMachine.OpenSubKey("Software\\" + RegistryKeyToStoreOptions); } catch //(System.Exception e) { } if (userKey == null && machineKey == null) { return; } if (userKey != null) { key = userKey; } else { key = machineKey; } try { _defaultDevice = (String)key.GetValue("Default Device", ""); _saveTo = (SaveTo)Enum.Parse(typeof(SaveTo), (String)key.GetValue("Save To", SaveTo.File)); _outputFolder = (String)key.GetValue("Output Folder", SaveTo.File); _fileNamingTemplate = (String)key.GetValue("File Naming Template", "Image_{0:D2}"); _outputFormat = (OutputFormat)Enum.Parse(typeof(OutputFormat), (String)key.GetValue("Output Format", OutputFormat.JPEG)); _jpegQuality = (int)key.GetValue("JPEG Quality", 95); _tiffCompression = (TiffCompression)Enum.Parse(typeof(TiffCompression), (String)key.GetValue("TIFF Compression", TiffCompression.LZW)); } catch (Exception e) { throw new ScanException("Failed to get options.", e); } }
public bool BuildDefaultOverviews(RasterOverviewSampling method, TiffCompression compression = TiffCompression.Auto) { bool result = BuildOverviews(method, GetDefaultOverviewRatios(), compression); if (result) { Logger.Current.Info("Overviews were built: " + Filename); } else { Logger.Current.Warn("Failed to build overviews: " + Filename); } return(result); }
private static long TranslateTiffCompression(TiffCompression compression) { switch (compression) { case TiffCompression.None: return((long)EncoderValue.CompressionNone); case TiffCompression.RLE: return((long)EncoderValue.CompressionRle); case TiffCompression.CCITT3: return((long)EncoderValue.CompressionCCITT3); case TiffCompression.CCITT4: return((long)EncoderValue.CompressionCCITT4); case TiffCompression.LZW: return((long)EncoderValue.CompressionLZW); default: return((long)EncoderValue.CompressionLZW); } }
private static EncoderValue Cast(TiffCompression compression) { switch (compression) { case TiffCompression.None: return(EncoderValue.CompressionNone); case TiffCompression.CcittGroup3Fax: return(EncoderValue.CompressionCCITT3); case TiffCompression.Ccitt1D: return(EncoderValue.CompressionRle); case TiffCompression.Lzw: return(EncoderValue.CompressionLZW); default: throw new System.NotSupportedException(compression.ToString()); } }
public void TiffEncoder_EncodesWithCorrectBiColorModeCompression <TPixel>(TestImageProvider <TPixel> provider, TiffCompression compression, TiffCompression expectedCompression) where TPixel : unmanaged, IPixel <TPixel> { // arrange var encoder = new TiffEncoder() { Compression = compression, BitsPerPixel = TiffBitsPerPixel.Bit1 }; using Image <TPixel> input = provider.GetImage(); using var memStream = new MemoryStream(); // act input.Save(memStream, encoder); // assert memStream.Position = 0; using var output = Image.Load <Rgba32>(memStream); TiffFrameMetadata frameMetaData = output.Frames.RootFrame.Metadata.GetTiffMetadata(); Assert.Equal(TiffBitsPerPixel.Bit1, frameMetaData.BitsPerPixel); Assert.Equal(expectedCompression, frameMetaData.Compression); }
public void TiffEncoder_PreservesCompression <TPixel>(TestImageProvider <TPixel> provider, TiffCompression expectedCompression) where TPixel : unmanaged, IPixel <TPixel> { // arrange var tiffEncoder = new TiffEncoder(); using Image <TPixel> input = provider.GetImage(); using var memStream = new MemoryStream(); // act input.Save(memStream, tiffEncoder); // assert memStream.Position = 0; using var output = Image.Load <Rgba32>(memStream); Assert.Equal(expectedCompression, output.Frames.RootFrame.Metadata.GetTiffMetadata().Compression); }
protected static void TestStripLength <TPixel>( TestImageProvider <TPixel> provider, TiffPhotometricInterpretation photometricInterpretation, TiffCompression compression, bool useExactComparer = true, float compareTolerance = 0.01f) where TPixel : unmanaged, IPixel <TPixel> { // arrange var tiffEncoder = new TiffEncoder() { PhotometricInterpretation = photometricInterpretation, Compression = compression }; using Image <TPixel> input = provider.GetImage(); using var memStream = new MemoryStream(); TiffFrameMetadata inputMeta = input.Frames.RootFrame.Metadata.GetTiffMetadata(); TiffCompression inputCompression = inputMeta.Compression ?? TiffCompression.None; // act input.Save(memStream, tiffEncoder); // assert memStream.Position = 0; using var output = Image.Load <Rgba32>(memStream); ExifProfile exifProfileOutput = output.Frames.RootFrame.Metadata.ExifProfile; TiffFrameMetadata outputMeta = output.Frames.RootFrame.Metadata.GetTiffMetadata(); ImageFrame <Rgba32> rootFrame = output.Frames.RootFrame; Number rowsPerStrip = exifProfileOutput.GetValue(ExifTag.RowsPerStrip) != null?exifProfileOutput.GetValue(ExifTag.RowsPerStrip).Value : TiffConstants.RowsPerStripInfinity; Assert.True(output.Height > (int)rowsPerStrip); Assert.True(exifProfileOutput.GetValue(ExifTag.StripOffsets)?.Value.Length > 1); Number[] stripByteCounts = exifProfileOutput.GetValue(ExifTag.StripByteCounts)?.Value; Assert.NotNull(stripByteCounts); Assert.True(stripByteCounts.Length > 1); Assert.NotNull(outputMeta.BitsPerPixel); foreach (Number sz in stripByteCounts) { Assert.True((uint)sz <= TiffConstants.DefaultStripSize); } // For uncompressed more accurate test. if (compression == TiffCompression.None) { for (int i = 0; i < stripByteCounts.Length - 1; i++) { // The difference must be less than one row. int stripBytes = (int)stripByteCounts[i]; int widthBytes = ((int)outputMeta.BitsPerPixel + 7) / 8 * rootFrame.Width; Assert.True((TiffConstants.DefaultStripSize - stripBytes) < widthBytes); } } // Compare with reference. TestTiffEncoderCore( provider, inputMeta.BitsPerPixel, photometricInterpretation, inputCompression, useExactComparer: useExactComparer, compareTolerance: compareTolerance); }
private void LoadOptions() { RegistryKey userKey = null; RegistryKey machineKey = null; RegistryKey key; if (String.IsNullOrEmpty(RegistryKeyToStoreOptions)) { return; } try { userKey = Registry.CurrentUser.OpenSubKey("Software\\" + RegistryKeyToStoreOptions); machineKey = Registry.LocalMachine.OpenSubKey("Software\\" + RegistryKeyToStoreOptions); } catch //(System.Exception e) { } if (userKey == null && machineKey == null) { return; } if (userKey != null) { key = userKey; } else { key = machineKey; } try { _defaultDevice = (String) key.GetValue("Default Device", ""); _saveTo = (SaveTo) Enum.Parse(typeof(SaveTo), (String) key.GetValue("Save To", SaveTo.File)); _outputFolder = (String) key.GetValue("Output Folder", SaveTo.File); _fileNamingTemplate = (String) key.GetValue("File Naming Template", "Image_{0:D2}"); _outputFormat = (OutputFormat) Enum.Parse(typeof(OutputFormat), (String) key.GetValue("Output Format", OutputFormat.JPEG)); _jpegQuality = (int) key.GetValue("JPEG Quality", 95); _tiffCompression = (TiffCompression) Enum.Parse(typeof(TiffCompression), (String) key.GetValue("TIFF Compression", TiffCompression.LZW)); } catch (Exception e) { throw new ScanException("Failed to get options.", e); } }
public bool BuildOverviews(RasterOverviewSampling method, IEnumerable <int> scales, TiffCompression compression = TiffCompression.Auto) { if (compression == TiffCompression.Auto) { switch (DataType) { case GdalDataType.Float32: case GdalDataType.Float64: compression = TiffCompression.Lzw; break; } } MapConfig.CompressOverviews = compression; scales = scales.ToList(); return(_image.BuildOverviews((tkGDALResamplingMethod)method, scales.Count(), scales.ToArray())); }
/// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btn_OK_Click(object sender, EventArgs e) { // Preserve meta data. m_bPreserveMetadata = ckb_PreserveData.Checked; // Bit depth. if (rbtn_32Bits.Checked) m_nBitDepth = BitDepth.BPP32; else if (rbtn_24Bits.Checked) m_nBitDepth = BitDepth.BPP24; //Compression. if (rbtn_CompressionNone.Checked) m_nCompression = TiffCompression.None; else if (rbtn_CompressionCCITT3.Checked) m_nCompression = TiffCompression.CCITT3; else if (rbtn_CompressionCCITT4.Checked) m_nCompression = TiffCompression.CCITT4; else if (rbtn_CompressionLZW.Checked) m_nCompression = TiffCompression.LZW; else if (rbtn_CompressionRle.Checked) m_nCompression = TiffCompression.Rle; this.Close(); }
public void GetCompression_ReturnsValue(ByteOrder byteOrder, TiffType type, int?data, TiffCompression expectedResult) { var ifd = TiffIfdBuilder.GenerateIfd(TiffTags.Compression, type, data, byteOrder).Ifd; var result = ifd.GetCompression(byteOrder); Assert.Equal(expectedResult, result); }
/// <summary> /// Initialize the middleware with the specified compression. /// </summary> /// <param name="compression">The compression method.</param> /// <param name="compressionAlgorithm">A instance the handles the actual compression.</param> public TiffImageCompressionMiddleware(TiffCompression compression, ITiffCompressionAlgorithm compressionAlgorithm) { _compression = compression; _compressionAlgorithm = compressionAlgorithm; }
/// <summary> /// Convert document to tiff with detailed settings and save result to storage. /// </summary> /// <param name="name">The file name.</param> /// <param name="resultFile">Required parameter. Name of the resulting image. e.g. outFile.tiff The file will be saved in same folder as source file</param> /// <param name="useAntiAliasing">Optional, default is false.</param> /// <param name="useHighQualityRendering">Optional, default is false.</param> /// <param name="imageBrightness">Optional, from 0.0 (dimmest) to 1.0 (brightest).</param> /// <param name="imageColorMode">Optional, default is None, possible values are: None (preserves color), Grayscale, BlackAndWhite.</param> /// <param name="imageContrast">Optional, from 0.0 (the least contrast) to 1.0 (the greatest contrast).</param> /// <param name="numeralFormat">Optional, supported values are: European, ArabicIndic, EasternArabicIndic, Context, System.</param> /// <param name="pageCount">Optional, number of page to save. Can be used to save just a part of document. Default 0 means all pages</param> /// <param name="pageIndex">Optional, page index to start exporting (from 0). Can be used to save just a part of document.</param> /// <param name="paperColor">Optional, image background color. Well known or RGB (e.g. r0g255b128) color.</param> /// <param name="pixelFormat">Optional, specifies pixel format for generated image. Accepted values are: Format16BppRgb555, Format16BppRgb565, Format16BppArgb1555, Format24BppRgb, Format32BppRgb, Format32BppArgb, Format32BppPArgb, Format48BppRgb, Format64BppArgb, Format64BppPArgb.</param> /// <param name="resolution">Optional, default is 96 DPI.</param> /// <param name="scale">Optional, zoom factor.</param> /// <param name="tiffCompression">Optional, Tiff compression, possible values are: None, Rle, Lzw, Ccitt3, Ccitt4.</param> /// <param name="dmlRenderingMode">Optional, default is Fallback, possible values are: Fallback, DrawingML.</param> /// <param name="dmlEffectsRenderingMode">Optional, default is Simplified, possible values are: Simplified, None, Fine</param> /// <param name="tiffBinarizationMethod">Optional, default is Threshold. Optional values are: FloydSteinbergDithering, Threshold</param> /// <param name="folder">The document folder.</param> /// <param name="storage">The document storage.</param> public void ConvertDocumentToTiff(string name, string resultFile, string folder, bool useAntiAliasing = false, bool useHighQualityRendering = false, double imageBrightness = 0.5, WordTiffImageColorMode imageColorMode = WordTiffImageColorMode.None, double imageContrast = 0.9, WordTiffNumeralFormat numeralFormat = WordTiffNumeralFormat.System, int pageCount = 0, int pageIndex = 0, string paperColor = "", WordTiffPixelFormat pixelFormat = WordTiffPixelFormat.Format16BppRgb555, double resolution = 96, double scale = 0.0, TiffCompression tiffCompression = TiffCompression.None, DmlRenderingMode dmlRenderingMode = DmlRenderingMode.Fallback, DmlEffectsRenderingMode dmlEffectsRenderingMode = DmlEffectsRenderingMode.Simplified, TiffBinarizationMethod tiffBinarizationMethod = TiffBinarizationMethod.Threshold, string storage = "") { // PUT words/{name}/SaveAs/tiff?appSid={appSid}&resultFile={resultFile}&useAntiAliasing={useAntiAliasing}&useHighQualityRendering={useHighQualityRendering}&imageBrightness={imageBrightness}&imageColorMode={imageColorMode}&imageContrast={imageContrast}&numeralFormat={numeralFormat}&pageCount={pageCount}&pageIndex={pageIndex}&paperColor={paperColor}&pixelFormat={pixelFormat}&resolution={resolution}&scale={scale}&tiffCompression={tiffCompression}&dmlRenderingMode={dmlRenderingMode}&dmlEffectsRenderingMode={dmlEffectsRenderingMode}&tiffBinarizationMethod={tiffBinarizationMethod}&storage={storage}&folder={folder} string apiUrl = string.Format(@"words/{0}/SaveAs/tiff?resultFile={1}&useAntiAliasing={2}&useHighQualityRendering={3}&imageBrightness={4}&imageColorMode={5}&imageContrast={6}&numeralFormat={7}&pageIndex={8}&paperColor={9}&pixelFormat={10}&resolution={11}&dmlRenderingMode={12}&dmlEffectsRenderingMode={13}&tiffBinarizationMethod={14}&storage={15}&folder={16}", name, resultFile, useAntiAliasing, useHighQualityRendering, imageBrightness, imageColorMode, imageContrast, numeralFormat, pageIndex, paperColor, pixelFormat, resolution, dmlRenderingMode, dmlEffectsRenderingMode, tiffBinarizationMethod, storage, folder); if (pageCount > 0) apiUrl += string.Format("&pageCount={0}", pageCount); if (scale > 0) apiUrl += string.Format("&scale={0}", scale); if (tiffCompression != TiffCompression.None) apiUrl += string.Format("&tiffCompression={0}", tiffCompression); ServiceController.Put(apiUrl, AppSid, AppKey); }
/// <summary> /// Saves the current image object as a Tagged Image File Format file with the specified BitDepth and TiffCompression settings. /// </summary> /// <param name="nBitDepth">Specifies the BitDepth to use when saving.</param> /// <param name="nTiffCompression">Specifies the type of compression to use when saving.</param> /// <param name="oPropertyItems">Specifies an array of property items to write to the image file.</param> /// <exception cref="System.ArgumentException"></exception> /// <exception cref="System.UnauthorizedAccessException"></exception> /// <exception cref="System.IO.IOException"></exception> /// <exception cref="System.Security.SecurityException"></exception> public void SaveAsTiff(BitDepth nBitDepth, TiffCompression nTiffCompression, PropertyItem[] oPropertyItems) { string sFilePath = ValidateFilePath(m_sFilePath, ImageFileType.Tiff); if (string.IsNullOrEmpty(sFilePath)) { MessageBox.Show("The file path provided is invalid.", "Error Saving File", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } FileStream oStream = null; try { oStream = new FileStream(sFilePath, FileMode.Create, FileAccess.Write); using (EncoderParameter oBitDepthParam = new EncoderParameter(Encoder.ColorDepth, (long)nBitDepth)) { using (EncoderParameter oCompressionParam = new EncoderParameter(Encoder.Compression, (long)nTiffCompression)) { using (EncoderParameters oEncodeParams = new EncoderParameters(2)) { oEncodeParams.Param[0] = oBitDepthParam; oEncodeParams.Param[1] = oCompressionParam; // Set the property items. If there are any. if ((oPropertyItems != null) && (oPropertyItems.Length > 0)) { foreach (PropertyItem oPropItem in oPropertyItems) m_oBitmap.SetPropertyItem(oPropItem); } // Save the bitmap to the FileStream with the specified ImageCodecInfo and EncoderParameters. m_oBitmap.Save(oStream, GetImageEncoderInfo(ImageFormat.Tiff), oEncodeParams); } } } } catch (ArgumentException e) { throw new ArgumentException(e.Message, e); } catch (UnauthorizedAccessException e) { throw new UnauthorizedAccessException(e.Message, e); } catch (IOException e) { throw new IOException(e.Message, e); } catch (System.Security.SecurityException e) { throw new System.Security.SecurityException(e.Message, e); } finally { if (oStream != null) oStream.Close(); } }
/// <summary> /// Computes the Image File Directory of a geometry. /// </summary> /// <param name="geometry">The geometry.</param> /// <param name="compression">The compression.</param> /// <param name="format">The sample format.</param> /// <param name="startPosition">The starting position of the raster content within the stream.</param> /// <param name="endPosition">The ending position of the raster content within the stream.</param> /// <returns>The computed Image File Directory.</returns> protected override TiffImageFileDirectory ComputeImageFileDirectory(ISpectralGeometry geometry, TiffCompression compression, TiffSampleFormat format) { TiffImageFileDirectory imageFileDirectory = base.ComputeImageFileDirectory(geometry, compression, format); CoordinateReferenceSystem referenceSystem = geometry.ReferenceSystem as CoordinateReferenceSystem; GeoKeyDirectory geoKeyDirectory = new GeoKeyDirectory(); AddGeoKey(geoKeyDirectory, GeoKey.Citation, geometry.Metadata, "GeoTIFF::GeoCitation"); AddGeoKey(geoKeyDirectory, GeoKey.GeodeticCoordinateReferenceSystemCitation, geometry.Metadata, "GeoTIFF::GeodeticCoordinateReferenceSystemCitation"); AddGeoKey(geoKeyDirectory, GeoKey.ProjectedCoordinateReferenceSystemCitation, geometry.Metadata, "GeoTIFF::ProjectedCoordinateReferenceSystemCitation"); if (geometry.Raster.Mapper != null) // if mapper is available { geoKeyDirectory.Add(GeoKey.RasterType, (Int16)((geometry.Raster.Mapper.Mode == RasterMapMode.ValueIsArea) ? 1 : 2)); imageFileDirectory.Add(TiffTag.ModelTiepointTag, new Object[] { 0.0, 0.0, 0.0, geometry.Raster.Mapper.Translation.X, geometry.Raster.Mapper.Translation.Y, 0.0 }); imageFileDirectory.Add(TiffTag.ModelPixelScaleTag, new Object[] { geometry.Raster.Mapper.ColumnSize, geometry.Raster.Mapper.RowSize, 1.0 }); } if (referenceSystem != null) // if reference system is available (and supported) { switch (referenceSystem.Type) { case ReferenceSystemType.Projected: ComputeProjectedCoordinateReferenceSystem(geoKeyDirectory, referenceSystem as ProjectedCoordinateReferenceSystem); break; case ReferenceSystemType.Geographic2D: case ReferenceSystemType.Geographic3D: ComputeGeodeticCoordinateReferenceSystem(geoKeyDirectory, referenceSystem as GeographicCoordinateReferenceSystem); break; default: // other reference systems are not supported return(imageFileDirectory); } } WriteGeoKeyDirectory(imageFileDirectory, geoKeyDirectory); if (geometry.Imaging != null) // add imaging data { imageFileDirectory.Add(57410, new Object[] { geometry.Imaging.Device.Name }); imageFileDirectory.Add(57411, new Object[] { geometry.Imaging.Time.ToString(CultureInfo.InvariantCulture.DateTimeFormat) }); imageFileDirectory.Add(57412, new Object[] { geometry.Imaging.DeviceLocation.Latitude.BaseValue, geometry.Imaging.DeviceLocation.Longitude.BaseValue, geometry.Imaging.DeviceLocation.Height.BaseValue }); imageFileDirectory.Add(57413, new Object[] { geometry.Imaging.IncidenceAngle, geometry.Imaging.ViewingAngle, geometry.Imaging.SunAzimuth, geometry.Imaging.SunElevation }); imageFileDirectory.Add(57417, geometry.Imaging.Bands.Select(band => band.PhysicalGain).Cast <Object>().ToArray()); imageFileDirectory.Add(57418, geometry.Imaging.Bands.Select(band => band.PhysicalBias).Cast <Object>().ToArray()); imageFileDirectory.Add(57419, geometry.Imaging.Bands.Select(band => band.SolarIrradiance).Cast <Object>().ToArray()); Object[] imageLocation = new Object[12]; for (Int32 coordinateIndex = 0; coordinateIndex < geometry.Imaging.ImageLocation.Count; coordinateIndex++) { imageLocation[3 * coordinateIndex] = geometry.Imaging.ImageLocation[coordinateIndex].Latitude.BaseValue; imageLocation[3 * coordinateIndex + 1] = geometry.Imaging.ImageLocation[coordinateIndex].Longitude.BaseValue; imageLocation[3 * coordinateIndex + 2] = geometry.Imaging.ImageLocation[coordinateIndex].Height.BaseValue; } imageFileDirectory.Add(57420, imageLocation); } return(imageFileDirectory); }
public void TiffEncoder_StripLength_WithPalette <TPixel>(TestImageProvider <TPixel> provider, TiffPhotometricInterpretation photometricInterpretation, TiffCompression compression) where TPixel : unmanaged, IPixel <TPixel> => TestStripLength(provider, photometricInterpretation, compression, false, 0.01f);
public void TiffEncoder_StripLength_OutOfBounds <TPixel>(TestImageProvider <TPixel> provider, TiffPhotometricInterpretation photometricInterpretation, TiffCompression compression) where TPixel : unmanaged, IPixel <TPixel> => //// CcittGroup3Fax compressed data length can be larger than the original length. Assert.Throws <Xunit.Sdk.TrueException>(() => TestStripLength(provider, photometricInterpretation, compression));
public bool SaveMultipage(List <ScannedImage> images, string location, TiffCompression compression, Func <int, bool> progressCallback) { try { ImageCodecInfo codecInfo = GetCodecForString("TIFF"); if (!progressCallback(0)) { return(false); } PathHelper.EnsureParentDirExists(location); if (images.Count == 1) { var iparams = new EncoderParameters(1); Encoder iparam = Encoder.Compression; using (var bitmap = scannedImageRenderer.Render(images[0])) { ValidateBitmap(bitmap); var iparamPara = new EncoderParameter(iparam, (long)GetEncoderValue(compression, bitmap)); iparams.Param[0] = iparamPara; bitmap.Save(location, codecInfo, iparams); } } else if (images.Count > 1) { var encoderParams = new EncoderParameters(2); var saveEncoder = Encoder.SaveFlag; var compressionEncoder = Encoder.Compression; File.Delete(location); using (var bitmap0 = scannedImageRenderer.Render(images[0])) { ValidateBitmap(bitmap0); encoderParams.Param[0] = new EncoderParameter(compressionEncoder, (long)GetEncoderValue(compression, bitmap0)); encoderParams.Param[1] = new EncoderParameter(saveEncoder, (long)EncoderValue.MultiFrame);; bitmap0.Save(location, codecInfo, encoderParams); for (int i = 1; i < images.Count; i++) { if (images[i] == null) { break; } if (!progressCallback(i)) { bitmap0.Dispose(); File.Delete(location); return(false); } using (var bitmap = scannedImageRenderer.Render(images[i])) { ValidateBitmap(bitmap); encoderParams.Param[0] = new EncoderParameter(compressionEncoder, (long)GetEncoderValue(compression, bitmap)); encoderParams.Param[1] = new EncoderParameter(saveEncoder, (long)EncoderValue.FrameDimensionPage); bitmap0.SaveAdd(bitmap, encoderParams); } } encoderParams.Param[0] = new EncoderParameter(saveEncoder, (long)EncoderValue.Flush); bitmap0.SaveAdd(encoderParams); } } return(true); } catch (Exception ex) { throw new Exception("Error saving TIFF", ex); } }
public void SupportsCompression_ReturnsCorrectValue(TiffCompression compression, bool expectedResult) { var supported = TiffDecompressor.SupportsCompression(compression); Assert.Equal(expectedResult, supported); }
/// <summary> /// Save document as Tiff image. /// </summary> /// <param name="name">The document name.</param> /// <param name="resultFile">The resulting file. Resulting image saved to the same folder and storage where the original document is. Relative path can be used here for some subfolder of the document folder.</param> /// <param name="brightness">The image brightness.</param> /// <param name="compression">Tiff compression. Possible values are: LZW, CCITT4, CCITT3, RLE, None.</param> /// <param name="colorDepth">Image color depth. Possible valuse are: Default, Format8bpp, Format4bpp, Format1bpp.</param> /// <param name="leftMargin">Left image margin.</param> /// <param name="rightMargin">Right image margin.</param> /// <param name="topMargin">Top image margin.</param> /// <param name="bottomMargin">Bottom image margin.</param> /// <param name="orientation">Image orientation. Possible values are: None, Landscape, Portait.</param> /// <param name="skipBlankPages">Skip blank pages flag.</param> /// <param name="width">Image width.</param> /// <param name="height">Image height.</param> /// <param name="xResolution">Horizontal resolution.</param> /// <param name="yResolution">Vertical resolution.</param> /// <param name="pageIndex">Start page to export.</param> /// <param name="pageCount">Number of pages to export.</param> /// <param name="storage">The document storage.</param> /// <param name="folder">The document folder.</param> public void SaveDocumentAsTiffImage(string name, string resultFile, string folder, double brightness = 0.0, TiffCompression compression = TiffCompression.None, ImageColorDepth colorDepth = ImageColorDepth.Default, int leftMargin = 0, int rightMargin = 0, int topMargin = 0, int bottomMargin = 0, Orientation orientation = Orientation.None, bool skipBlankPages = true, int width = 0, int height = 0, int xResolution = 0, int yResolution = 0, int pageIndex = 0, int pageCount = 0, string storage = "") { // PUT pdf/{name}/SaveAs/tiff?appSid={appSid}&resultFile={resultFile}&brightness={brightness}&compression={compression}&colorDepth={colorDepth}&leftMargin={leftMargin}&rightMargin={rightMargin}&topMargin={topMargin}&bottomMargin={bottomMargin}&orientation={orientation}&skipBlankPages={skipBlankPages}&width={width}&height={height}&xResolution={xResolution}&yResolution={yResolution}&pageIndex={pageIndex}&pageCount={pageCount}&storage={storage}&folder={folder} string apiUrl = string.Format(@"pdf/{0}/SaveAs/tiff?resultFile={1}&skipBlankPages={2}&storage={3}&folder={4}", name, resultFile, skipBlankPages, storage, folder); if (brightness > 0) apiUrl += string.Format("&brightness={0}", brightness); if (compression != TiffCompression.None) apiUrl += string.Format("&compression={0}", compression); if (colorDepth > 0) apiUrl += string.Format("&colorDepth={0}", colorDepth); if (leftMargin > 0) apiUrl += string.Format("&leftMargin={0}", leftMargin); if (rightMargin > 0) apiUrl += string.Format("&rightMargin={0}", rightMargin); if (topMargin > 0) apiUrl += string.Format("&topMargin={0}", topMargin); if (bottomMargin > 0) apiUrl += string.Format("&bottomMargin={0}", bottomMargin); if (orientation != Orientation.None) apiUrl += string.Format("&orientation={0}", orientation); if (width > 0) apiUrl += string.Format("&width={0}", width); if (height > 0) apiUrl += string.Format("&height={0}", height); if (rightMargin > 0) apiUrl += string.Format("&rightMargin={0}", rightMargin); if (yResolution > 0) apiUrl += string.Format("&yResolution={0}", yResolution); if (pageIndex > 0) apiUrl += string.Format("&pageIndex={0}", pageIndex); if (pageCount > 0) apiUrl += string.Format("&pageCount={0}", pageCount); ServiceController.Put(apiUrl, AppSid, AppKey); }
public async Task <bool> SaveMultipage(List <ScannedImage.Snapshot> snapshots, string location, TiffCompression compression, ProgressHandler progressCallback, CancellationToken cancelToken) { try { ImageCodecInfo codecInfo = GetCodecForString("TIFF"); progressCallback(0, snapshots.Count); if (cancelToken.IsCancellationRequested) { return(false); } PathHelper.EnsureParentDirExists(location); if (snapshots.Count == 1) { var iparams = new EncoderParameters(1); Encoder iparam = Encoder.Compression; using (var bitmap = await scannedImageRenderer.Render(snapshots[0])) { ValidateBitmap(bitmap); var iparamPara = new EncoderParameter(iparam, (long)GetEncoderValue(compression, bitmap)); iparams.Param[0] = iparamPara; bitmap.Save(location, codecInfo, iparams); } } else if (snapshots.Count > 1) { var encoderParams = new EncoderParameters(2); var saveEncoder = Encoder.SaveFlag; var compressionEncoder = Encoder.Compression; File.Delete(location); using (var bitmap0 = await scannedImageRenderer.Render(snapshots[0])) { ValidateBitmap(bitmap0); encoderParams.Param[0] = new EncoderParameter(compressionEncoder, (long)GetEncoderValue(compression, bitmap0)); encoderParams.Param[1] = new EncoderParameter(saveEncoder, (long)EncoderValue.MultiFrame); bitmap0.Save(location, codecInfo, encoderParams); for (int i = 1; i < snapshots.Count; i++) { if (snapshots[i] == null) { break; } progressCallback(i, snapshots.Count); if (cancelToken.IsCancellationRequested) { bitmap0.Dispose(); File.Delete(location); return(false); } using (var bitmap = await scannedImageRenderer.Render(snapshots[i])) { ValidateBitmap(bitmap); encoderParams.Param[0] = new EncoderParameter(compressionEncoder, (long)GetEncoderValue(compression, bitmap)); encoderParams.Param[1] = new EncoderParameter(saveEncoder, (long)EncoderValue.FrameDimensionPage); bitmap0.SaveAdd(bitmap, encoderParams); } } encoderParams.Param[0] = new EncoderParameter(saveEncoder, (long)EncoderValue.Flush); bitmap0.SaveAdd(encoderParams); } } return(true); } catch (Exception ex) { throw new Exception("Error saving TIFF", ex); } }
/// <summary> /// Computes the image file directory of a geometry. /// </summary> /// <param name="geometry">The geometry.</param> /// <param name="compression">The compression.</param> /// <param name="format">The sample format.</param> /// <param name="startPosition">The starting position of the raster content within the stream.</param> /// <param name="endPosition">The ending position of the raster content within the stream.</param> /// <returns>The computed image file directory.</returns> protected virtual TiffImageFileDirectory ComputeImageFileDirectory(ISpectralGeometry geometry, TiffCompression compression, TiffSampleFormat format) { TiffImageFileDirectory imageFileDirectory = new TiffImageFileDirectory(); // compute photometric interpretation TiffPhotometricInterpretation photometricInterpretation = ComputePhotometricInterpretation(geometry); // add raster properties AddImageTag(imageFileDirectory, TiffTag.PhotometricInterpretation, (UInt16)photometricInterpretation); AddImageTag(imageFileDirectory, TiffTag.Compression, (UInt16)compression); AddImageTag(imageFileDirectory, TiffTag.ImageLength, (UInt32)geometry.Raster.NumberOfRows); AddImageTag(imageFileDirectory, TiffTag.ImageWidth, (UInt32)geometry.Raster.NumberOfColumns); AddImageTag(imageFileDirectory, TiffTag.ResolutionUnit, (UInt16)2); AddImageTag(imageFileDirectory, TiffTag.XResolution, (geometry.Raster.Mapper != null) ? (Rational)geometry.Raster.Mapper.ColumnSize : (Rational)1); AddImageTag(imageFileDirectory, TiffTag.YResolution, (geometry.Raster.Mapper != null) ? (Rational)geometry.Raster.Mapper.RowSize : (Rational)1); AddImageTag(imageFileDirectory, TiffTag.RowsPerStrip, (UInt32)geometry.Raster.NumberOfRows); AddImageTag(imageFileDirectory, TiffTag.StripOffsets, (UInt32)0); AddImageTag(imageFileDirectory, TiffTag.StripByteCounts, (UInt32)0); AddImageTag(imageFileDirectory, TiffTag.BitsPerSample, Enumerable.Repeat((UInt16)geometry.Raster.RadiometricResolution, geometry.Raster.NumberOfBands).Cast <Object>().ToArray()); AddImageTag(imageFileDirectory, TiffTag.SamplesPerPixel, (UInt32)geometry.Raster.NumberOfBands); AddImageTag(imageFileDirectory, TiffTag.SampleFormat, (UInt16)format); // add color palette if (photometricInterpretation == TiffPhotometricInterpretation.PaletteColor) { imageFileDirectory.Add(TiffTag.ColorMap, ComputeColorMap(geometry)); } // add metadata AddImageTag(imageFileDirectory, TiffTag.DocumentName, geometry.Metadata, "GeoTIFF::DocumentName"); AddImageTag(imageFileDirectory, TiffTag.ImageDescription, geometry.Metadata, "GeoTIFF::ImageDescription"); AddImageTag(imageFileDirectory, TiffTag.DocumentName, geometry.Metadata, "GeoTIFF::Make"); AddImageTag(imageFileDirectory, TiffTag.Make, geometry.Metadata, "GeoTIFF::DocumentName"); AddImageTag(imageFileDirectory, TiffTag.Model, geometry.Metadata, "GeoTIFF::Model"); AddImageTag(imageFileDirectory, TiffTag.PageName, geometry.Metadata, "GeoTIFF::PageName"); AddImageTag(imageFileDirectory, TiffTag.Artist, geometry.Metadata, "GeoTIFF::Artist"); AddImageTag(imageFileDirectory, TiffTag.HostComputer, geometry.Metadata, "GeoTIFF::HostComputer"); AddImageTag(imageFileDirectory, TiffTag.Copyright, geometry.Metadata, "GeoTIFF::Copyright"); AddImageTag(imageFileDirectory, TiffTag.Software, "AEGIS Geospatial Framework"); AddImageTag(imageFileDirectory, TiffTag.DateTime, DateTime.Now.ToString(CultureInfo.InvariantCulture.DateTimeFormat)); Dictionary <String, Object> attributes = geometry.Metadata.Where(attribute => !attribute.Key.Contains("GeoTIFF")).ToDictionary(attribute => attribute.Key, attribute => attribute.Value); if (geometry.Metadata.Count(attribute => !attribute.Key.Contains("GeoTIFF")) > 0) { imageFileDirectory.Add(TiffTag.AegisAttributes, new Object[] { JsonConvert.SerializeObject(attributes, Formatting.None, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All }) }); } return(imageFileDirectory); }
/// <summary> /// Writes the raster of the geometry into a strip. /// </summary> /// <param name="raster">The raster.</param> /// <param name="compression">The compression.</param> /// <param name="format">The sample format.</param> private void WriteRasterContentToStrip(IRaster raster, TiffCompression compression, TiffSampleFormat format) { _baseStream.Seek(_currentImageStartPosition, SeekOrigin.Begin); // mark the starting position of the strip UInt32 numberOfBytes = (UInt32)(Math.Ceiling(raster.RadiometricResolution / 8.0) * raster.NumberOfBands * raster.NumberOfRows * raster.NumberOfColumns); UInt32 numberOfBytesLeft = numberOfBytes; if (numberOfBytes % 2 != 0) // correct the number of bytes { numberOfBytes++; } Byte[] bytes = new Byte[numberOfBytes < NumberOfWritableBytes ? numberOfBytes : NumberOfWritableBytes]; Int32 byteIndex = 0; Int32 bitIndex = 8; for (Int32 rowIndex = 0; rowIndex < raster.NumberOfRows; rowIndex++) { for (Int32 columnIndex = 0; columnIndex < raster.NumberOfColumns; columnIndex++) { // write the values for each band into the buffer for (Int32 bandIndex = 0; bandIndex < raster.NumberOfBands; bandIndex++) { switch (format) { case TiffSampleFormat.Undefined: case TiffSampleFormat.UnsignedInteger: WriteUnsignedIntergerValue(raster.GetValue(rowIndex, columnIndex, bandIndex), raster.RadiometricResolution, bytes, ref byteIndex, ref bitIndex); break; case TiffSampleFormat.SignedInteger: case TiffSampleFormat.Floating: WriteFloatValue(raster.GetFloatValue(rowIndex, columnIndex, bandIndex), raster.RadiometricResolution, bytes, ref byteIndex, ref bitIndex); break; } if (byteIndex == bytes.Length) { // write the buffer to the file _baseStream.Write(bytes, 0, byteIndex); byteIndex = 0; numberOfBytesLeft -= (UInt32)byteIndex; // the final array of bytes should not be the number of bytes left if (numberOfBytes > NumberOfWritableBytes && numberOfBytesLeft > 0 && numberOfBytesLeft < NumberOfWritableBytes) { bytes = new Byte[numberOfBytesLeft % 2 == 0 ? numberOfBytesLeft : numberOfBytesLeft + 1]; } } } } } // if any values are left if (numberOfBytesLeft > 0) { _baseStream.Write(bytes, 0, byteIndex); } }
private static long TranslateTiffCompression(TiffCompression compression) { switch (compression) { case TiffCompression.None: return (long) EncoderValue.CompressionNone; case TiffCompression.RLE: return (long) EncoderValue.CompressionRle; case TiffCompression.CCITT3: return (long) EncoderValue.CompressionCCITT3; case TiffCompression.CCITT4: return (long) EncoderValue.CompressionCCITT4; case TiffCompression.LZW: return (long) EncoderValue.CompressionLZW; default: return (long) EncoderValue.CompressionLZW; } }