Exemplo n.º 1
0
 public static void SaveTiff8(string outputFilename, IBitmap <byte> bitmap)
 {
     using (var tiffWriter = new TiffWriter(File.Create(outputFilename)))
     {
         tiffWriter.WriteImageFile(bitmap);
     }
 }
Exemplo n.º 2
0
        public Replay(Queue <string> originalTrackData, Queue <string> originalInfoData, OriginalType originalType, int originalLength, int frameRate, int pxPERmm, string folder, string name, string fishID) :
            base(folder, name, fishID, originalLength, frameRate, pxPERmm)
        {
            if (FileSaver != null)
            {
                _trackWriter      = FileSaver.GetStreamWriter(".track");
                _imageWriter      = FileSaver.GetTiffWriter("_camImage.tif", true);
                _backgroundWriter = FileSaver.GetTiffWriter("_bgImage.tif", true);
                //Create 10x10 mm region image
                _camRegion = new Image8(Properties.Settings.Default.PixelsPermm * 10, Properties.Settings.Default.PixelsPermm * 10);
            }
            _laser = new SDLPS500Controller(Properties.Settings.Default.DAQ, Properties.Settings.Default.LaserAO);
            string xchannel = Properties.Settings.Default.DAQ + "/" + Properties.Settings.Default.ScannerX;
            string ychannel = Properties.Settings.Default.DAQ + "/" + Properties.Settings.Default.ScannerY;

            //Load scan lookup table from file
            try
            {
                TextReader reader    = File.OpenText("main.calib");
                var        scanTable = BLIScanLookupTable.LoadFromFile(reader);
                _scanner = new RandomAccessScanner(scanTable, xchannel, ychannel, -10, 10);
                reader.Dispose();
            }
            catch (IOException)
            {
                System.Diagnostics.Debug.WriteLine("Could not find calibration data. No targeting available");
            }
            //This is a closed-loop experiment - try to stay fully up-to-date
            SuggestedBufferSeconds = 0;
            _originalType          = originalType;
            _originalTrackData     = originalTrackData;
            _originalInfoData      = originalInfoData;
            _experimentPhase       = ExperimentPhase.Replay;
        }
Exemplo n.º 3
0
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            Directory.SetCurrentDirectory(@"c:\Ludde\FractalWorlds");

            var sw = Stopwatch.StartNew();

//            var demReader = new DemZipRawReader(@"\\luddepc\Earth2\SRTM.zip", "{0}.hgt", 3601, 3601);
            var demReader = new DemZipTiffReader(@"\\luddepc\Earth2\ASTER.zip", "ASTGTM2_{0}_dem.tif", 3601, 3601);
            //var demReader = new DemTiffReader(@"\\luddepc\Earth\ASTERunzip\ASTGTM2_{0}_dem.tif", 3601, 3601);

            //t.Join(78, -83, 68, -73);
            // t.Join(64, 5, 54, 15);

            // Kazbek 42°41′57″N 44°31′06″ECoordinates: 42°41′57″N 44°31′06″E [1]
            int lat0      = 48;
            int lon0      = 40;
            int lat1      = 40;
            int lon1      = 48;
            var theBitmap = demReader.LoadBitmap(lat0, lon0, lat1, lon1);

            using (var tiffWriter = new TiffWriter(File.Create(string.Format(@"Datasets\Planets\Earth\ASTER_{0}_{1}.tif", demReader.MapGranulateName(lat0, lon0), demReader.MapGranulateName(lat1, lon1)))))
            {
                tiffWriter.BigTiff = true;
                tiffWriter.WriteImageFile(theBitmap);
            }

            Console.WriteLine($"Saving bitmap in {sw.Elapsed}");

            Console.WriteLine("Done!");
        }
Exemplo n.º 4
0
 protected override void Dispose(bool disposing)
 {
     base.Dispose(disposing);
     if (disposing)
     {
         if (_trackWriter != null)
         {
             _trackWriter.Dispose();
             _trackWriter = null;
         }
         if (_imageWriter != null)
         {
             _imageWriter.Dispose();
             _imageWriter = null;
         }
         if (_laser != null)
         {
             _laser.Dispose();
         }
         if (_scanner != null)
         {
             _scanner.Dispose();
         }
     }
 }
Exemplo n.º 5
0
        public TargetingTest(int expSeconds, int frameRate, int pxPERmm, string folder, string name, string fishID) : base(folder, name, fishID, expSeconds, frameRate, pxPERmm)
        {
            _totalFrames = ExperimentLength * FrameRate;
            if (FileSaver != null)
            {
                _trackWriter = FileSaver.GetStreamWriter(".track");
                _imageWriter = FileSaver.GetTiffWriter("_camImage.tif", true);
            }
            _laser = new SDLPS500Controller(Properties.Settings.Default.DAQ, Properties.Settings.Default.LaserAO);
            string xchannel = Properties.Settings.Default.DAQ + "/" + Properties.Settings.Default.ScannerX;
            string ychannel = Properties.Settings.Default.DAQ + "/" + Properties.Settings.Default.ScannerY;

            //Load scan lookup table from file
            try
            {
                TextReader reader    = File.OpenText("main.calib");
                var        scanTable = BLIScanLookupTable.LoadFromFile(reader);
                _scanner = new RandomAccessScanner(scanTable, xchannel, ychannel, -10, 10);
                reader.Dispose();
            }
            catch (IOException)
            {
                System.Diagnostics.Debug.WriteLine("Could not find calibration data. No targeting available");
            }
            //This is an closed-loop experiment - try to stay fully up-to-date
            SuggestedBufferSeconds = 0;
        }
Exemplo n.º 6
0
 protected override void Dispose(bool disposing)
 {
     base.Dispose(disposing);
     if (disposing)
     {
         if (_trackWriter != null)
         {
             _trackWriter.Dispose();
             _trackWriter = null;
         }
         if (_imageWriter != null)
         {
             _imageWriter.Dispose();
             _imageWriter = null;
         }
         if (_backgroundWriter != null)
         {
             _backgroundWriter.Dispose();
             _backgroundWriter = null;
         }
         if (_laser != null)
         {
             _laser.Dispose();
         }
         if (_scanner != null)
         {
             _scanner.Dispose();
         }
         if (_camRegion != null)
         {
             _camRegion.Dispose();
             _camRegion = null;
         }
     }
 }
Exemplo n.º 7
0
 public static void SaveTiff8(string outputFilename, IBitmap <short> bitmap)
 {
     using (var tiffWriter = new TiffWriter(File.Create(outputFilename)))
     {
         var bitmap2 = bitmap.Convert((p) => (byte)((p >> 8) + 128));
         tiffWriter.WriteImageFile(bitmap2);
     }
 }
Exemplo n.º 8
0
        public void Create()
        {
            Stopwatch sw;

            sw = Stopwatch.StartNew();
            using (var tiffReader = new TiffReader(File.OpenRead(@"Datasets\Planets\Mars\Mars_HRSC_MOLA_BlendDEM_Global_200mp.tif")))
            {
                var ifd = tiffReader.ImageFileDirectories[0];

                _topSectorOffsetY = (int)(ifd.ImageHeight * (Math.PI / 2 - LatT0) / Math.PI);
                _topSectorOffsetX = (int)(ifd.ImageWidth * (Math.PI + LonT0) / (Math.PI * 2));

                _topSectorWidth  = (int)Math.Ceiling(ifd.ImageHeight * (LatT0 - LatT1) / Math.PI);
                _topSectorHeight = (int)Math.Ceiling(ifd.ImageWidth * (LonT1 - LonT0) / (Math.PI * 2));

                var topElevationBitmap = tiffReader.ReadImageFile <short>(ifd, _topSectorOffsetX, _topSectorOffsetY, _topSectorWidth, _topSectorHeight);
                _topElevationBitmap = topElevationBitmap /*Resampler.Resample(topElevationBitmap, 1024, 1024)*/.ToBitmap();
                Console.WriteLine($"Loading image top {_topElevationBitmap.Width}x{_topElevationBitmap.Height} sector used {sw.Elapsed}");

                using (var tiffWriter = new TiffWriter(File.Create($@"Generated\Planets\MarsDouble2\MarsTop.tif")))
                {
                    var bitmap = _topElevationBitmap.Convert((p) => { return((ushort)(p - short.MinValue)); });
                    tiffWriter.WriteImageFile(bitmap);
                }

                //--
                _bottomSectorOffsetY = (int)(ifd.ImageHeight * (Math.PI / 2 - LatB0) / Math.PI);
                _bottomSectorOffsetX = (int)(ifd.ImageWidth * (Math.PI + LonB0) / (Math.PI * 2));

                _bottomSectorWidth  = (int)Math.Ceiling(ifd.ImageHeight * (LatB0 - LatB1) / Math.PI);
                _bottomSectorHeight = (int)Math.Ceiling(ifd.ImageWidth * (LonB1 - LonB0) / (Math.PI * 2));

                var bottomElevationBitmap = tiffReader.ReadImageFile <short>(ifd, _bottomSectorOffsetX, _bottomSectorOffsetY, _bottomSectorWidth, _bottomSectorHeight);
                _bottomElevationBitmap = bottomElevationBitmap /*Resampler.Resample(bottomElevationBitmap, 1024, 1024)*/.ToBitmap();
                Console.WriteLine($"Loading image bottom {_bottomElevationBitmap.Width}x{_bottomElevationBitmap.Height} sector used {sw.Elapsed}");

                using (var tiffWriter = new TiffWriter(File.Create($@"Generated\Planets\MarsDouble2\MarsBottom.tif")))
                {
                    var bitmap = _bottomElevationBitmap.Convert((p) => { return((ushort)(p - short.MinValue)); });
                    tiffWriter.WriteImageFile(bitmap);
                }
            }

            Init();

            sw = Stopwatch.StartNew();
            Split();
            Console.WriteLine($"Time used to split planet geometry: {sw.Elapsed}");
            PrintSummary();

            sw = Stopwatch.StartNew();
            Merge();
            Console.WriteLine($"Time used to merge planet geometry: {sw.Elapsed}");
            PrintSummary();

            SaveStl("Generated/Planets/MarsDouble2/MarsDouble2.stl");
        }
Exemplo n.º 9
0
    /// <summary>
    /// Reads image in JPEG format and saves to TIFF format using memory-friendly Pipeline API
    /// </summary>
    private static void WriteTiffMemoryFriendly()
    {
        using (var reader = new JpegReader("../../../../_Input/Chicago.jpg"))
            using (var flip = new Flip(FlipType.Vertical))
                using (var writer = new TiffWriter("../../../../_Output/WriteTiffMemoryFriendly.tif"))
                {
                    writer.Compression = CompressionType.Jpeg;
                    writer.Quality     = 85;

                    Pipeline.Run(reader + flip + writer);
                }
    }
Exemplo n.º 10
0
        public bool SaveTiff(string Filename)
        {
            try {
                using (var stream = File.Create(Filename))
                {
                    var writer = TiffWriter.Create(stream);
                    var handle = writer.WriteHeader(); // Write Header

                    var bitPerSample = (ushort)Dictionary[TiffTags.BitsPerSample][0];

                    var strips          = new TiffHandle[ValuesList.Count];
                    var stripByteCounts = new uint[ValuesList.Count];
                    for (int i = 0; i < ValuesList.Count; i++)
                    {
                        var _buf = new byte[ValuesList[i].Length];
                        Buffer.BlockCopy(ValuesList[i], 0, _buf, 0, ValuesList[i].Length);

                        // Generating data ...
                        strips[i]          = writer.WriteData(_buf); // Write Strip
                        stripByteCounts[i] = (uint)_buf.Length;
                    }

                    // Write Image File Directory
                    handle = writer.WriteImageFileDirectory(handle, new Collection <ITag> {
                        Tag <uint> .Create(TiffTags.ImageWidth, ImageWidth),
                        Tag <uint> .Create(TiffTags.ImageLength, ImageHeight),
                        Tag <ushort> .Create(TiffTags.BitsPerSample, bitPerSample),
                        Tag <TiffCompression> .Create(TiffTags.Compression, TiffCompression.NONE),
                        Tag <TiffPhotoMetric> .Create(TiffTags.PhotometricInterpretation, TiffPhotoMetric.BlackIsZero),
                        Tag <TiffHandle> .Create(TiffTags.StripOffsets, strips),
                        Tag <ushort> .Create(TiffTags.SamplesPerPixel, 1),
                        Tag <uint> .Create(TiffTags.RowsPerStrip, ImageWidth),
                        Tag <uint> .Create(TiffTags.StripByteCounts, stripByteCounts),
                        Tag <char> .Create(TiffTags.SampleFormat, "INT".ToCharArray()),
                        Tag <double> .Create((TiffTags)33550, 0.000277777777778001, 0.000277777777778001, 0),
                        Tag <double> .Create((TiffTags)33922, 0, 0, 0, 0, 0, 0),
                        Tag <double> .Create((TiffTags)34735, 1, 1, 0, 7, 1024, 0, 1, 2, 1025, 0, 1, 1, 2048,
                                             0, 1, 4326, 2049, 34737, 7, 0, 2054, 0, 1, 9102, 2057, 34736, 1, 1, 2059, 34736, 1, 0),
                        Tag <double> .Create((TiffTags)298.257223563, 6378137),
                        Tag <char> .Create((TiffTags)34737, "WGS 84|".ToCharArray()),
                        Tag <char> .Create(TiffTags.Software, "BirdEye Software".ToCharArray()),
                        Tag <char> .Create(TiffTags.Copyright, "(c) Alos Gdem".ToCharArray())
                    });
                }
                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
Exemplo n.º 11
0
    /// <summary>
    /// Saves multiframe (multipage) image
    /// </summary>
    private static void SaveMultiframeImage()
    {
        using (var writer = new TiffWriter("../../../../_Output/SaveMultiframe.tif"))
        {
            using (var frame1 = new Bitmap("../../../../_Input/Chicago.jpg"))
            {
                Pipeline.Run(frame1 + writer);
            }

            using (var frame2 = new Bitmap("../../../../_Input/Copenhagen_RGB.jpg"))
            {
                Pipeline.Run(frame2 + writer);
            }
        }
    }
Exemplo n.º 12
0
    /// <summary>
    /// Writes multiframe image in TIFF format using memory-friendly Pipeline API
    /// </summary>
    private static void WriteMultiframeTiffMemoryFriendly()
    {
        using (var writer = new TiffWriter("../../../../_Output/WriteMultiframeTiffMemoryFriendly.tif"))
        {
            using (var reader1 = new JpegReader("../../../../_Input/Chicago.jpg"))
            {
                Pipeline.Run(reader1 + writer);
            }

            using (var reader2 = new JpegReader("../../../../_Input/Copenhagen_RGB.jpg"))
            {
                Pipeline.Run(reader2 + writer);
            }
        }
    }
Exemplo n.º 13
0
    /// <summary>
    /// Splits image channels into multiple receivers
    /// </summary>
    private static void SplitChannels()
    {
        using (var reader = ImageReader.Create("../../../../_Input/Copenhagen_CMYK.jpg"))
            using (var splitter = new CmykChannelSplitter())
                using (var writerC = new TiffWriter("../../../../_Output/Copenhagen_C.tif"))
                    using (var writerM = new TiffWriter("../../../../_Output/Copenhagen_M.tif"))
                        using (var writerY = new TiffWriter("../../../../_Output/Copenhagen_Y.tif"))
                            using (var writerK = new TiffWriter("../../../../_Output/Copenhagen_K.tif"))
                            {
                                splitter.C = writerC;
                                splitter.M = writerM;
                                splitter.Y = writerY;
                                splitter.K = writerK;

                                Pipeline.Run(reader + splitter);
                            }
    }
    /// <summary>
    /// Creates business card 3.5"x2.0" size with extra channel
    /// </summary>
    private static void WriteExtraChannel()
    {
        using (var reader = new TiffReader("../../../../_Output/BusinessCard_Base.tif"))
            using (var writer = new TiffWriter("../../../../_Output/BusinessCard.tif"))
            {
                // Load bitmap for the extra channel.
                // Note: image for extra channel must be grayscale and have the same dimensions and DPI as the source one.
                using (var extraBitmap = new Bitmap("../../../../_Output/BusinessCard_Extra.tif"))
                {
                    // Create extra channel options based on extraBitmap.
                    var extraChannel = new TiffExtraChannelEntry(extraBitmap, TiffChannelType.Alpha);

                    writer.ExtraChannels.Add(extraChannel);
                    Pipeline.Run(reader + writer);
                }
            }
    }
Exemplo n.º 15
0
        public void Join(int lat0, int lon0, int lat1, int lon1)
        {
            int dlat = lat0 - lat1;
            int dlon = lon1 - lon0;

            var readers = new List <RawReader>();

            var concatBitmaps = new List <EnumerableBitmap <short> >();

            for (int lat = lat0; lat >= lat1; lat--)
            {
                var bitmapPaths = new List <string>();
                for (int lon = lon0; lon <= lon1; lon++)
                {
                    string bitmapPath = string.Format(_inputPath, MapPosition(lat, lon));
                    bitmapPaths.Add(bitmapPath);
                }
                var rawReaders = bitmapPaths.Select(p => File.Exists(p) ? new RawReader(File.OpenRead(p)) : null).ToArray();
                readers.AddRange(rawReaders);

                var rowBitmaps = rawReaders.Select(r => r != null ? r.ReadBitmap <short>(1201, 1201) : (IBitmap <short>)_oceanBitmap).ToArray();
                var rowBitmap  = BitmapTools.Concatenate(rowBitmaps);

                concatBitmaps.Add(rowBitmap);
            }

            var theBitmap = BitmapTools.Append(concatBitmaps.ToArray());

            using (var tiffWriter = new TiffWriter(File.Create($@"Datasets\Planets\Earth\ViewFinderPanoramas\dem3_{MapPosition(lat0, lon0)}_{MapPosition(lat1, lon1)}.tif")))
            {
                tiffWriter.BigTiff = true;
                theBitmap          = theBitmap.Convert((p) =>
                {
                    return((short)(((p >> 8) & 0xff) | ((p << 8) & 0xff00)));
                });
                tiffWriter.WriteImageFile(theBitmap);
            }

            foreach (var reader in readers)
            {
                reader?.Dispose();
            }
        }
Exemplo n.º 16
0
        /// <summary>
        /// Write palette-color image data to a stack image. Also test the availability of required info. May throw WriteFileException.
        /// </summary>
        /// <param name="data">Image data in a 2D jagged array, with dimesion number of planes * (height * width).</param>
        /// <param name="allInfo">Info collection to be written in the stack file.</param>
        public void writePaletteColorStack(Array[] data, byte[][] colormap, int width, int height, StkInfoCollection allInfo)
        {
            if (data == null || data.Length == 0)
            {
                throw new WriteFileException("Empty image data");
            }
            if (allInfo == null)
            {
                throw new WriteFileException("Info collection is NULL");
            }

            System.IO.Stream stream = writer.BaseStream;
            int planeNum            = data.Length;

            if (planeNum != allInfo.NumberOfPlanes)
            {
                throw new WriteFileException("Incompatible image data and image info collection: Inconsistent plane number");
            }
            int size = width * height;

            for (int i = 0; i < planeNum; i++)
            {
                if (data[i] == null || data[i].Length != size)
                {
                    throw new WriteFileException("Invalid image data");
                }
            }

            prepareWritePaletteColorStack(allInfo, width, height, TiffWriter.getArrayDataType(data[0]), planeNum, colormap);
            if (!isPrepared)
            {
                throw new WriteFileException("Failed to pre-write data");
            }

            if (BufferSize < MIN_BUFFER_SIZE)
            {
                BufferSize = MIN_BUFFER_SIZE;
            }
            BufferSize = BufferSize / 4 * 4;

            writeGrayScaleImageDataStrips(data, byteCountsPerPlane, (uint)width, (uint)height, allInfo);
            finalizeImageWriting(allInfo, new StkStruct());
        }
Exemplo n.º 17
0
 public TrackAndWrite(int expSeconds, int frameRate, int pxPERmm, string folder, string name, string fishID, bool writeImage) : base(folder, name, fishID, expSeconds, frameRate, pxPERmm)
 {
     _totalFrames     = ExperimentLength * FrameRate;
     _writeFishImages = writeImage;
     if (FileSaver != null)
     {
         _trackWriter = FileSaver.GetStreamWriter(".track");
         if (_writeFishImages)
         {
             _imageWriter      = FileSaver.GetTiffWriter("_camImage.tif", true);
             _backgroundWriter = FileSaver.GetTiffWriter("_bgImage.tif", true);
             //Create 10x10 mm region image
             _camRegion = new Image8(Properties.Settings.Default.PixelsPermm * 10,
                                     Properties.Settings.Default.PixelsPermm * 10);
         }
     }
     //This is an open-loop experiment rather not important to stay fully up-to-date
     SuggestedBufferSeconds = 0.1f;
 }
Exemplo n.º 18
0
    /// <summary>
    /// Writes multiframe image in TIFF format
    /// </summary>
    private static void WriteMultiframeTiff()
    {
        using (var writer = new TiffWriter("../../../../_Output/WriteMultiframeTiff.tif"))
        {
            using (var frame1 = new Bitmap("../../../../_Input/Chicago.jpg"))
            {
                // You can specify the compression of each frame separately
                writer.Compression = CompressionType.Jpeg;
                writer.Quality     = 85;

                Pipeline.Run(frame1 + writer);
            }

            using (var frame2 = new Bitmap("../../../../_Input/Copenhagen_RGB.jpg"))
            {
                writer.Compression = CompressionType.Lzw;

                Pipeline.Run(frame2 + writer);
            }
        }
    }
Exemplo n.º 19
0
        public void TestWriteRGB8()
        {
            var bitmap = new Bitmap <byte>(32, 32, 3);

            CreateGradient(bitmap);

            var tempFile = Path.Combine(Path.GetTempPath(), "TestWriteRGB8.tif");

            using (var tiffWriter = new TiffWriter(File.Create(tempFile)))
            {
                var ifd = tiffWriter.WriteImageFile(bitmap);

                Assert.Equal(32, ifd.ImageWidth);
                Assert.Equal(32, ifd.ImageHeight);
                Assert.Equal(8, ifd.BitsPerSample);
                Assert.Equal(3, ifd.SamplesPerPixel);
                Assert.Equal(Compression.NoCompression, ifd.Compression);
            }

            var bitmap2 = TiffReader.LoadBitmap <short>(File.OpenRead(tempFile));
        }
Exemplo n.º 20
0
        public CircularGradient(int habitSeconds, int preSeconds, int gradientSeconds, int nTrials, int frameRate, int pxPERmm, string folder, string name, string fishID) :
            base(folder, name, fishID, habitSeconds + (preSeconds + gradientSeconds) * nTrials, frameRate, pxPERmm)
        {
            if (FileSaver != null)
            {
                _trackWriter      = FileSaver.GetStreamWriter(".track");
                _imageWriter      = FileSaver.GetTiffWriter("_camImage.tif", true);
                _backgroundWriter = FileSaver.GetTiffWriter("_bgImage.tif", true);
                //Create 10x10 mm region image
                _camRegion = new Image8(Properties.Settings.Default.PixelsPermm * 10, Properties.Settings.Default.PixelsPermm * 10);
            }
            _laser = new SDLPS500Controller(Properties.Settings.Default.DAQ, Properties.Settings.Default.LaserAO);
            string xchannel = Properties.Settings.Default.DAQ + "/" + Properties.Settings.Default.ScannerX;
            string ychannel = Properties.Settings.Default.DAQ + "/" + Properties.Settings.Default.ScannerY;

            //Load scan lookup table from file
            try
            {
                TextReader reader    = File.OpenText("main.calib");
                var        scanTable = BLIScanLookupTable.LoadFromFile(reader);
                _scanner = new RandomAccessScanner(scanTable, xchannel, ychannel, -10, 10);
                reader.Dispose();
            }
            catch (IOException)
            {
                System.Diagnostics.Debug.WriteLine("Could not find calibration data. No targeting available");
            }
            _preFrames         = preSeconds * FrameRate;
            _gradFrames        = gradientSeconds * FrameRate;
            _habitFrames       = habitSeconds * FrameRate;
            _nTrials           = nTrials;
            _currentPhaseFrame = 0;
            _currentTrial      = 0;//Start at 0 during habituation will be pre-incremented as we enter pre-phase and will be checked for completing at end of gradient phase
            //This is a closed-loop experiment - try to stay fully up-to-date
            SuggestedBufferSeconds = 0;
            //Start in habituation phase
            _experimentPhase = ExperimentPhase.Habituation;
        }
Exemplo n.º 21
0
        public void Join()
        {
            var tiffReaders  = _inputFiles.Select(p => new TiffReader(File.OpenRead(p))).ToArray();
            var inputBitmaps = tiffReaders.Select(r => r.ReadImageFile <short>()).ToArray();

            var b1 = BitmapTools.Concatenate(inputBitmaps[0], inputBitmaps[1], inputBitmaps[2], inputBitmaps[3], inputBitmaps[4], inputBitmaps[5]);
            var b2 = BitmapTools.Concatenate(inputBitmaps[6], inputBitmaps[7], inputBitmaps[8], inputBitmaps[9], inputBitmaps[10], inputBitmaps[11]);
            var b3 = BitmapTools.Concatenate(inputBitmaps[12], inputBitmaps[13], inputBitmaps[14], inputBitmaps[15], inputBitmaps[16], inputBitmaps[17]);
            var b4 = BitmapTools.Concatenate(inputBitmaps[18], inputBitmaps[19], inputBitmaps[20], inputBitmaps[21], inputBitmaps[22], inputBitmaps[23]);

            var b = BitmapTools.Append(b1, b2, b3, b4);

            using (var tiffWriter = new TiffWriter(File.Create($@"Datasets\Planets\Earth\ViewFinderPanoramas\dem15.tif")))
            {
                tiffWriter.BigTiff = true;
//                var bitmap = _topElevationBitmap.Convert((p) => { return (ushort)(p - short.MinValue); });
                tiffWriter.WriteImageFile(b);
            }

            foreach (var reader in tiffReaders)
            {
                reader.Dispose();
            }
        }
Exemplo n.º 22
0
        public void Create()
        {
            double dLat = Lat0 - Lat1;
            double dLon = Lon1 - Lon0;

            // Calculate sector transform
            _sx  = Math.PI * 2 / dLon;
            _sy  = Math.PI / dLat;
            _sx0 = (Math.PI + Lon0) / (Math.PI * 2) * _sx;
            _sy0 = (Math.PI / 2 - Lat0) / Math.PI * _sy;

            Stopwatch sw;

            sw = Stopwatch.StartNew();
            using (var tiffReader = new TiffReader(File.OpenRead(@"Datasets\Planets\Mars\Mars_HRSC_MOLA_BlendDEM_Global_200mp.tif")))
            {
                var ifd = tiffReader.ImageFileDirectories[0];

                _elevationWidth  = ifd.ImageWidth;
                _elevationHeight = ifd.ImageHeight;

                _sectorOffsetY = (int)(_elevationHeight * (Math.PI / 2 - Lat0) / Math.PI);
                _sectorOffsetX = (int)(_elevationWidth * (Math.PI + Lon0) / (Math.PI * 2));

                _sectorHeight = (int)Math.Ceiling(_elevationHeight * dLat / Math.PI);
                _sectorWidth  = (int)Math.Ceiling(_elevationWidth * dLon / (Math.PI * 2));

                _elevationSectorBitmap = tiffReader.ReadImageFile <short>(ifd, _sectorOffsetX, _sectorOffsetY, _sectorWidth, _sectorHeight).ToBitmap();
                Console.WriteLine($"Loading image sector used {sw.Elapsed}");

                // _elevationSectorBitmap = Resampler.Resample(elevationBitmap, width, height).ToBitmap();
                // Console.WriteLine($"Resampling used {sw.Elapsed}");

                using (var tiffWriter = new TiffWriter(File.Create($@"Generated\Planets\MarsSector\Mars{_elevationSectorBitmap.Width}x{_elevationSectorBitmap.Height}.tif")))
                {
                    var bitmap = _elevationSectorBitmap.Convert((p) => { return((ushort)(p - short.MinValue)); });
                    tiffWriter.WriteImageFile(bitmap);
                }

                BitmapHelper.SaveTiff8($@"Generated\Planets\MarsSector\Mars{_elevationSectorBitmap.Width}x{_elevationSectorBitmap.Height}.tif", _elevationSectorBitmap);

                int    width  = 2880;
                int    height = 1440;
                string elevationTextureBlurFilename = $@"Generated\Planets\MarsSector\MarsBlur{width}x{height}.raw";
                if (!File.Exists(elevationTextureBlurFilename))
                {
                    var elevationTextureSmall = Resampler.Resample(_elevationSectorBitmap, width, height).ToBitmap();

                    sw = Stopwatch.StartNew();
                    var blurFilter = new BlurFilter(PlanetProjection);
                    _elevationBitmapBlur = blurFilter.Blur3(elevationTextureSmall, MathHelper.ToRadians(10));
                    Console.WriteLine($"Blur used {sw.Elapsed}");

                    BitmapHelper.SaveRaw16($@"Generated\Planets\MarsSector\MarsBlur{_elevationBitmapBlur.Width}x{_elevationBitmapBlur.Height}.raw", _elevationBitmapBlur);
                    BitmapHelper.SaveTiff8($@"Generated\Planets\MarsSector\MarsBlur{_elevationBitmapBlur.Width}x{_elevationBitmapBlur.Height}.tif", _elevationBitmapBlur);
                }
                else
                {
                    _elevationBitmapBlur = BitmapHelper.LoadRaw16(elevationTextureBlurFilename, width, height);
                }
            }

            sw = Stopwatch.StartNew();

            var sphericalSector = new SphericalSector();

            sphericalSector.ComputeRadiusTop = ComputeModelElevationTop;

            sphericalSector.Create(Lat0, Lon0, Lat1, Lon1, NumSegments, NumSegments, PlanetRadius - 50000);

            PlanetVertexes  = sphericalSector.Vertexes;
            PlanetTriangles = sphericalSector.Triangles;

            Console.WriteLine($"Time used to create planet vertexes: {sw.Elapsed}");

            SaveStl($@"Generated\Planets\MarsSector\MarsSector{NumSegments}.stl");
        }
Exemplo n.º 23
0
        public byte[] GetImageAsBytes()
        {
            if (streamBytes == null)
            {
                return(null);
            }
            if (!decoded)
            {
                // if the stream hasn't been decoded, check to see if it is a single stage JPG or JPX encoded stream.  If it is,
                // then we can just use stream as-is
                PdfName filter = dictionary.GetAsName(PdfName.FILTER);
                if (filter == null)
                {
                    PdfArray filterArray = dictionary.GetAsArray(PdfName.FILTER);
                    if (filterArray.Size == 1)
                    {
                        filter = filterArray.GetAsName(0);
                    }
                    else
                    {
                        throw new UnsupportedPdfException("Multi-stage filters not supported here (" + filterArray + ")");
                    }
                }
                if (PdfName.DCTDECODE.Equals(filter))
                {
                    fileType = TYPE_JPG;
                    return(streamBytes);
                }
                else if (PdfName.JPXDECODE.Equals(filter))
                {
                    fileType = TYPE_JP2;
                    return(streamBytes);
                }
                throw new UnsupportedPdfException("Unsupported stream filter " + filter);
            }
            pngColorType = -1;
            width        = dictionary.GetAsNumber(PdfName.WIDTH).IntValue;
            height       = dictionary.GetAsNumber(PdfName.HEIGHT).IntValue;
            bpc          = dictionary.GetAsNumber(PdfName.BITSPERCOMPONENT).IntValue;
            pngBitDepth  = bpc;
            PdfObject colorspace = dictionary.GetDirectObject(PdfName.COLORSPACE);

            palette = null;
            icc     = null;
            stride  = 0;
            FindColorspace(colorspace, true);
            MemoryStream ms = new MemoryStream();

            if (pngColorType < 0)
            {
                if (bpc != 8)
                {
                    return(null);
                }
                if (PdfName.DEVICECMYK.Equals(colorspace))
                {
                }
                else if (colorspace is PdfArray)
                {
                    PdfArray  ca   = (PdfArray)colorspace;
                    PdfObject tyca = ca.GetDirectObject(0);
                    if (!PdfName.ICCBASED.Equals(tyca))
                    {
                        return(null);
                    }
                    PRStream pr = (PRStream)ca.GetDirectObject(1);
                    int      n  = pr.GetAsNumber(PdfName.N).IntValue;
                    if (n != 4)
                    {
                        return(null);
                    }
                    icc = PdfReader.GetStreamBytes(pr);
                }
                else
                {
                    return(null);
                }
                stride = 4 * width;
                TiffWriter wr = new TiffWriter();
                wr.AddField(new TiffWriter.FieldShort(TIFFConstants.TIFFTAG_SAMPLESPERPIXEL, 4));
                wr.AddField(new TiffWriter.FieldShort(TIFFConstants.TIFFTAG_BITSPERSAMPLE, new int[] { 8, 8, 8, 8 }));
                wr.AddField(new TiffWriter.FieldShort(TIFFConstants.TIFFTAG_PHOTOMETRIC, TIFFConstants.PHOTOMETRIC_SEPARATED));
                wr.AddField(new TiffWriter.FieldLong(TIFFConstants.TIFFTAG_IMAGEWIDTH, width));
                wr.AddField(new TiffWriter.FieldLong(TIFFConstants.TIFFTAG_IMAGELENGTH, height));
                wr.AddField(new TiffWriter.FieldShort(TIFFConstants.TIFFTAG_COMPRESSION, TIFFConstants.COMPRESSION_LZW));
                wr.AddField(new TiffWriter.FieldShort(TIFFConstants.TIFFTAG_PREDICTOR, TIFFConstants.PREDICTOR_HORIZONTAL_DIFFERENCING));
                wr.AddField(new TiffWriter.FieldLong(TIFFConstants.TIFFTAG_ROWSPERSTRIP, height));
                wr.AddField(new TiffWriter.FieldRational(TIFFConstants.TIFFTAG_XRESOLUTION, new int[] { 300, 1 }));
                wr.AddField(new TiffWriter.FieldRational(TIFFConstants.TIFFTAG_YRESOLUTION, new int[] { 300, 1 }));
                wr.AddField(new TiffWriter.FieldShort(TIFFConstants.TIFFTAG_RESOLUTIONUNIT, TIFFConstants.RESUNIT_INCH));
                wr.AddField(new TiffWriter.FieldAscii(TIFFConstants.TIFFTAG_SOFTWARE, Document.Version));
                MemoryStream comp = new MemoryStream();
                TiffWriter.CompressLZW(comp, 2, streamBytes, height, 4, stride);
                byte[] buf = comp.ToArray();
                wr.AddField(new TiffWriter.FieldImage(buf));
                wr.AddField(new TiffWriter.FieldLong(TIFFConstants.TIFFTAG_STRIPBYTECOUNTS, buf.Length));
                if (icc != null)
                {
                    wr.AddField(new TiffWriter.FieldUndefined(TIFFConstants.TIFFTAG_ICCPROFILE, icc));
                }
                wr.WriteFile(ms);
                fileType = TYPE_TIF;
                return(ms.ToArray());
            }
            PngWriter png = new PngWriter(ms);

            png.WriteHeader(width, height, pngBitDepth, pngColorType);
            if (icc != null)
            {
                png.WriteIccProfile(icc);
            }
            if (palette != null)
            {
                png.WritePalette(palette);
            }
            png.WriteData(streamBytes, stride);
            png.WriteEnd();
            fileType = TYPE_PNG;
            return(ms.ToArray());
        }
Exemplo n.º 24
0
        public void Create()
        {
            var targetPath = $@"Generated\Planets\Earth\{Name}";

            Directory.CreateDirectory(targetPath);

            int lat0deg = (int)Math.Floor(MathHelper.ToDegrees(Lat0));
            int lat1deg = (int)Math.Floor(MathHelper.ToDegrees(Lat1));
            int lon0deg = (int)Math.Floor(MathHelper.ToDegrees(Lon0));
            int lon1deg = (int)Math.Floor(MathHelper.ToDegrees(Lon1));

            double lat0 = MathHelper.ToRadians(lat0deg + 1);
            double lat1 = MathHelper.ToRadians(lat1deg);
            double lon0 = MathHelper.ToRadians(lon0deg);
            double lon1 = MathHelper.ToRadians(lon1deg + 1);

            // Calculate sector transform
            _sx  = Math.PI * 2 / (lon1 - lon0);
            _sy  = Math.PI / (lat0 - lat1);
            _sx0 = (Math.PI + lon0) / (Math.PI * 2) * _sx;
            _sy0 = (Math.PI / 2 - lat0) / Math.PI * _sy;

            // --

            int totalWidth  = 3601 * 360;
            int totalHeight = 3601 * 180;

            int sectorHeight = (int)Math.Round(totalHeight * (Lat0 - Lat1) / Math.PI);
            int sectorWidth  = (int)Math.Round(totalWidth * (Lon1 - Lon0) / (Math.PI * 2));

            Console.WriteLine($"Using image sector {sectorWidth}x{sectorHeight}");

            var sw = Stopwatch.StartNew();

            if (UseAster)
            {
                using (var demReader = new DemZipTiffReader(@"Datasets\Planets\Earth\ASTER.zip", "ASTGTM2_{0}_dem.tif", 3601, 3601))
                {
                    var elevationSectorBitmap = demReader.LoadBitmap(lat0deg, lon0deg, lat1deg, lon1deg);

                    Console.WriteLine($"Loading ASTER image {elevationSectorBitmap.Width}x{elevationSectorBitmap.Height}");

                    int w = Math.Min(elevationSectorBitmap.Width, (elevationSectorBitmap.Width * NumSegmentsLon) / sectorWidth);
                    int h = Math.Min(elevationSectorBitmap.Height, (elevationSectorBitmap.Height * NumSegmentsLat) / sectorHeight);

                    _elevationSectorBitmap = Resampler.Resample(elevationSectorBitmap, w, h).ToBitmap();
                }
            }
            else
            {
                using (var demReader = new DemZipRawReader(@"Datasets\Planets\Earth\SRTM.zip", "{0}.hgt", 3601, 3601))
                {
                    var elevationSectorBitmap = demReader.LoadBitmap(lat0deg, lon0deg, lat1deg, lon1deg);

                    Console.WriteLine($"Loading SRTM image {elevationSectorBitmap.Width}x{elevationSectorBitmap.Height}");

                    int w = Math.Min(elevationSectorBitmap.Width, (elevationSectorBitmap.Width * NumSegmentsLon) / sectorWidth);
                    int h = Math.Min(elevationSectorBitmap.Height, (elevationSectorBitmap.Height * NumSegmentsLat) / sectorHeight);

//                    _elevationSectorBitmap = Resampler.Resample(elevationSectorBitmap, w, h).ToBitmap();
                    _elevationSectorBitmap = elevationSectorBitmap.ToBitmap();
                }
            }
            Console.WriteLine($"Loading image sector {_elevationSectorBitmap.Width}x{_elevationSectorBitmap.Height} used {sw.Elapsed}");

            using (var tiffWriter = new TiffWriter(File.Create(Path.Combine(targetPath, $"Earth{_elevationSectorBitmap.Width}x{_elevationSectorBitmap.Height}.tif"))))
            {
                var bitmap = _elevationSectorBitmap.Convert((p) => { return((ushort)(p - short.MinValue)); });
                tiffWriter.WriteImageFile(bitmap);
            }

            sw = Stopwatch.StartNew();

            var sphericalSector = new SphericalSector();

            sphericalSector.ComputeRadiusTop = ComputeModelElevationTop;

            sphericalSector.Create(Lat0, Lon0, Lat1, Lon1, NumSegmentsLat, NumSegmentsLon, ModelScale * (PlanetRadius + ElevationBottom * ElevationScale));

            CenterVertexes(sphericalSector.Vertexes);

            PlanetVertexes  = sphericalSector.Vertexes;
            PlanetTriangles = sphericalSector.Triangles;

            Console.WriteLine($"Time used to create planet vertexes: {sw.Elapsed}");

            SaveStl(Path.Combine(targetPath, $"{Name}{NumSegmentsLon}_{ElevationScale}x.stl"));
        }
Exemplo n.º 25
0
        public void Create()
        {
            Stopwatch sw;

            sw = Stopwatch.StartNew();
            using (var tiffReader = new TiffReader(File.OpenRead(@"Datasets\Planets\Mars\Mars_HRSC_MOLA_BlendDEM_Global_200mp.tif")))
            {
                var ifd = tiffReader.ImageFileDirectories[0];

                _topSectorOffsetY = (int)(ifd.ImageHeight * (Math.PI / 2 - LatT0) / Math.PI);
                _topSectorOffsetX = (int)(ifd.ImageWidth * (Math.PI + LonT0) / (Math.PI * 2));

                _topSectorWidth  = (int)Math.Ceiling(ifd.ImageHeight * (LatT0 - LatT1) / Math.PI);
                _topSectorHeight = (int)Math.Ceiling(ifd.ImageWidth * (LonT1 - LonT0) / (Math.PI * 2));

                var topElevationBitmap = tiffReader.ReadImageFile <short>(ifd, _topSectorOffsetX, _topSectorOffsetY, _topSectorWidth, _topSectorHeight);
                // _topElevationBitmap = Resampler.Resample(topElevationBitmap, 899, 899).ToBitmap();
                _topElevationBitmap = topElevationBitmap.ToBitmap();
                Console.WriteLine($"Loading image top {_topElevationBitmap.Width}x{_topElevationBitmap.Height} sector used {sw.Elapsed}");

                using (var tiffWriter = new TiffWriter(File.Create($@"Generated\Planets\MarsDouble\MarsTop.tif")))
                {
                    var bitmap = _topElevationBitmap.Convert((p) => { return((ushort)(p - short.MinValue)); });
                    tiffWriter.WriteImageFile(bitmap);
                }

                //--
                _bottomSectorOffsetY = (int)(ifd.ImageHeight * (Math.PI / 2 - LatB0) / Math.PI);
                _bottomSectorOffsetX = (int)(ifd.ImageWidth * (Math.PI + LonB0) / (Math.PI * 2));

                _bottomSectorWidth  = (int)Math.Ceiling(ifd.ImageHeight * (LatB0 - LatB1) / Math.PI);
                _bottomSectorHeight = (int)Math.Ceiling(ifd.ImageWidth * (LonB1 - LonB0) / (Math.PI * 2));

                var bottomElevationBitmap = tiffReader.ReadImageFile <short>(ifd, _bottomSectorOffsetX, _bottomSectorOffsetY, _bottomSectorWidth, _bottomSectorHeight);
                // _bottomElevationBitmap = Resampler.Resample(bottomElevationBitmap, 899, 899).ToBitmap();
                _bottomElevationBitmap = bottomElevationBitmap.ToBitmap();
                Console.WriteLine($"Loading image bottom {_bottomElevationBitmap.Width}x{_bottomElevationBitmap.Height} sector used {sw.Elapsed}");

                using (var tiffWriter = new TiffWriter(File.Create($@"Generated\Planets\MarsDouble\MarsBottom.tif")))
                {
                    var bitmap = _bottomElevationBitmap.Convert((p) => { return((ushort)(p - short.MinValue)); });
                    tiffWriter.WriteImageFile(bitmap);
                }
            }

            sw = Stopwatch.StartNew();

            var sphericalSector = new Box();

            sphericalSector.ComputeRadiusTop    = ComputeModelElevationTop;
            sphericalSector.ComputeRadiusBottom = ComputeModelElevationBottom;

            sphericalSector.Create(NumSegments, NumSegments);

            PlanetVertexes  = sphericalSector.Vertexes;
            PlanetTriangles = sphericalSector.Triangles;

            Console.WriteLine($"Time used to create planet vertexes: {sw.Elapsed}");

            Console.WriteLine($"NumVertexes: {PlanetVertexes.Count()}");
            Console.WriteLine($"NumTriangles: {PlanetTriangles.Count()}");

            SaveStl($@"Generated\Planets\MarsDouble\MarsDouble{NumSegments}.stl");
        }
Exemplo n.º 26
0
        protected void prepareWriteStack(StkInfoCollection allInfo, int width, int height, ImageDataType dataType, int planeNum, ushort photometricInterpretation)
        {
            if (allInfo == null)
            {
                return;
            }
            stkInfo = allInfo;
            TiffWriter.getDataTypeInfo(dataType, out numberOfBits, out isFloatPoint);

            isPrepared   = false;
            planeCounter = 0;
            if (width <= 0 || height <= 0 || planeNum <= 0)
            {
                throw new WriteFileException("Invalid image parameters");
            }
            this.width    = width;
            this.height   = height;
            this.planeNum = planeNum;

            System.IO.Stream stream = writer.BaseStream;
            prepareWriteFile();

            allInfo.forceAdd(new TiffInfo(TiffInfoCollection.PhotometricInterpretation, "", photometricInterpretation));
            allInfo.add(new TiffInfo(TiffInfoCollection.XResolution, "", (uint)1, (uint)1));
            allInfo.add(new TiffInfo(TiffInfoCollection.YResolution, "", (uint)1, (uint)1));
            allInfo.add(new TiffInfo(TiffInfoCollection.ResolutionUnit, "", (ushort)1));

            if (isFloatPoint)
            {
                allInfo.setSampleFormat(TiffInfoCollection.SampleFormatType.FloatPoint);
            }
            else
            {
                allInfo.setSampleFormat(TiffInfoCollection.SampleFormatType.UnsignedInteger);
            }

            if (photometricInterpretation <= 1 || photometricInterpretation == 3)
            {
                allInfo.forceAdd(new TiffInfo(TiffInfoCollection.BitsPerSample, "Bits per Sample", (ushort)numberOfBits));
                byteCountsPerPlane = (uint)(width * height * numberOfBits / 8);
            }
            else if (photometricInterpretation == 2)
            {
                allInfo.forceAdd(new TiffInfo(TiffInfoCollection.BitsPerSample, "Bits per Sample", new ushort[] { (ushort)8, (ushort)8, (ushort)8 }));
                allInfo.forceAdd(new TiffInfo(TiffInfoCollection.SamplesPerPixel, "Sample per Pixel", (ushort)3));
                allInfo.forceAdd(new TiffInfo(TiffInfoCollection.PlanarConfiguration, "", (ushort)1));
                byteCountsPerPlane = (uint)(width * height * 3);
            }
            else
            {
                throw new Exception("Only support grayscale, palette-color, or RGB images.");
            }

            stripOffset = (uint)stream.Position;

            allInfo.forceAdd(new TiffInfo(TiffInfoCollection.ImageWidth, "width", (uint)width));
            allInfo.forceAdd(new TiffInfo(TiffInfoCollection.ImageLength, "height", (uint)height));
            allInfo.forceAdd(new TiffInfo(TiffInfoCollection.StripOffsets, "strip Offsets", stripOffset));
            allInfo.forceAdd(new TiffInfo(TiffInfoCollection.StripByteCounts, "strip Byte Counts", byteCountsPerPlane));
            allInfo.forceAdd(new TiffInfo(TiffInfoCollection.RowsPerStrip, "Rows per strip", (uint)height));
            MyTiffCompression.setCompressionTag(allInfo, CompressMethod, CompressLevel);
            MyTiffCompression.setHorizontalDifferencing(allInfo, HorizontalDifferencing);

            int[] missing;
            if (photometricInterpretation <= 1)
            {
                missing = allInfo.missingInfoGrayscale();
            }
            else if (photometricInterpretation == 2)
            {
                missing = allInfo.missingInfoRGB();
            }
            else
            {
                missing = allInfo.missingInfoPaletteColor();
            }

            if (missing.Length > 0)
            {
                String msg = "Missing tags: ";
                for (int i = 0; i < missing.Length; i++)
                {
                    msg += missing[i] + " ";
                }
                throw new WriteFileException(msg);
            }

            if (!allInfo.validUIC2tag())
            {
                throw new WriteFileException("Invalid UIC2 data");
            }

            isPrepared = true;
        }
Exemplo n.º 27
0
        /**
         * decodes the bytes currently captured in the streamBytes and replaces it with an image representation of the bytes
         * (this will either be a png or a tiff, depending on the color depth of the image)
         * @throws IOException
         */
        private void DecodeImageBytes()
        {
            if (streamContentType != null)
            {
                throw new ArgumentException(MessageLocalization.GetComposedMessage("Decoding.can't.happen.on.this.type.of.stream.(.1.)", streamContentType.FileExtension));
            }
            pngColorType = -1;
            PdfArray decode = dictionary.GetAsArray(PdfName.DECODE);

            width       = dictionary.GetAsNumber(PdfName.WIDTH).IntValue;
            height      = dictionary.GetAsNumber(PdfName.HEIGHT).IntValue;
            bpc         = dictionary.GetAsNumber(PdfName.BITSPERCOMPONENT).IntValue;
            pngBitDepth = bpc;
            PdfObject colorspace = dictionary.GetDirectObject(PdfName.COLORSPACE);

            if (colorspace is PdfName && colorSpaceDic != null)
            {
                PdfObject csLookup = colorSpaceDic.GetDirectObject((PdfName)colorspace);
                if (csLookup != null)
                {
                    colorspace = csLookup;
                }
            }

            palette = null;
            icc     = null;
            stride  = 0;
            FindColorspace(colorspace, true);
            MemoryStream ms = new MemoryStream();

            if (pngColorType < 0)
            {
                if (bpc != 8)
                {
                    throw new UnsupportedPdfException(MessageLocalization.GetComposedMessage("the.color.depth.1.is.not.supported", bpc));
                }
                if (PdfName.DEVICECMYK.Equals(colorspace))
                {
                }
                else if (colorspace is PdfArray)
                {
                    PdfArray  ca   = (PdfArray)colorspace;
                    PdfObject tyca = ca.GetDirectObject(0);
                    if (!PdfName.ICCBASED.Equals(tyca))
                    {
                        throw new UnsupportedPdfException(MessageLocalization.GetComposedMessage("the.color.space.1.is.not.supported", colorspace));
                    }
                    PRStream pr = (PRStream)ca.GetDirectObject(1);
                    int      n  = pr.GetAsNumber(PdfName.N).IntValue;
                    if (n != 4)
                    {
                        throw new UnsupportedPdfException(MessageLocalization.GetComposedMessage("N.value.1.is.not.supported", n));
                    }
                    icc = PdfReader.GetStreamBytes(pr);
                }
                else
                {
                    throw new UnsupportedPdfException(MessageLocalization.GetComposedMessage("the.color.space.1.is.not.supported", colorspace));
                }
                stride = 4 * width;
                TiffWriter wr = new TiffWriter();
                wr.AddField(new TiffWriter.FieldShort(TIFFConstants.TIFFTAG_SAMPLESPERPIXEL, 4));
                wr.AddField(new TiffWriter.FieldShort(TIFFConstants.TIFFTAG_BITSPERSAMPLE, new int[] { 8, 8, 8, 8 }));
                wr.AddField(new TiffWriter.FieldShort(TIFFConstants.TIFFTAG_PHOTOMETRIC, TIFFConstants.PHOTOMETRIC_SEPARATED));
                wr.AddField(new TiffWriter.FieldLong(TIFFConstants.TIFFTAG_IMAGEWIDTH, width));
                wr.AddField(new TiffWriter.FieldLong(TIFFConstants.TIFFTAG_IMAGELENGTH, height));
                wr.AddField(new TiffWriter.FieldShort(TIFFConstants.TIFFTAG_COMPRESSION, TIFFConstants.COMPRESSION_LZW));
                wr.AddField(new TiffWriter.FieldShort(TIFFConstants.TIFFTAG_PREDICTOR, TIFFConstants.PREDICTOR_HORIZONTAL_DIFFERENCING));
                wr.AddField(new TiffWriter.FieldLong(TIFFConstants.TIFFTAG_ROWSPERSTRIP, height));
                wr.AddField(new TiffWriter.FieldRational(TIFFConstants.TIFFTAG_XRESOLUTION, new int[] { 300, 1 }));
                wr.AddField(new TiffWriter.FieldRational(TIFFConstants.TIFFTAG_YRESOLUTION, new int[] { 300, 1 }));
                wr.AddField(new TiffWriter.FieldShort(TIFFConstants.TIFFTAG_RESOLUTIONUNIT, TIFFConstants.RESUNIT_INCH));
                wr.AddField(new TiffWriter.FieldAscii(TIFFConstants.TIFFTAG_SOFTWARE, Version.GetInstance().GetVersion));
                MemoryStream comp = new MemoryStream();
                TiffWriter.CompressLZW(comp, 2, imageBytes, height, 4, stride);
                byte[] buf = comp.ToArray();
                wr.AddField(new TiffWriter.FieldImage(buf));
                wr.AddField(new TiffWriter.FieldLong(TIFFConstants.TIFFTAG_STRIPBYTECOUNTS, buf.Length));
                if (icc != null)
                {
                    wr.AddField(new TiffWriter.FieldUndefined(TIFFConstants.TIFFTAG_ICCPROFILE, icc));
                }
                wr.WriteFile(ms);
                streamContentType = ImageBytesType.CCITT;
                imageBytes        = ms.ToArray();
                return;
            }
            else
            {
                PngWriter png = new PngWriter(ms);
                if (decode != null)
                {
                    if (pngBitDepth == 1)
                    {
                        // if the decode array is 1,0, then we need to invert the image
                        if (decode.GetAsNumber(0).IntValue == 1 && decode.GetAsNumber(1).IntValue == 0)
                        {
                            int len = imageBytes.Length;
                            for (int t = 0; t < len; ++t)
                            {
                                imageBytes[t] ^= 0xff;
                            }
                        }
                        else
                        {
                            // if the decode array is 0,1, do nothing.  It's possible that the array could be 0,0 or 1,1 - but that would be silly, so we'll just ignore that case
                        }
                    }
                    else
                    {
                        // todo: add decode transformation for other depths
                    }
                }
                png.WriteHeader(width, height, pngBitDepth, pngColorType);
                if (icc != null)
                {
                    png.WriteIccProfile(icc);
                }
                if (palette != null)
                {
                    png.WritePalette(palette);
                }
                png.WriteData(imageBytes, stride);
                png.WriteEnd();
                streamContentType = ImageBytesType.PNG;
                imageBytes        = ms.ToArray();
            }
        }
Exemplo n.º 28
0
        /// <exception cref="System.IO.IOException"/>
        private byte[] DecodeTiffAndPngBytes(byte[] imageBytes)
        {
            PdfObject colorspace = GetPdfObject().Get(PdfName.ColorSpace);

            PrepareAndFindColorspace(colorspace);
            MemoryStream ms = new MemoryStream();

            if (pngColorType < 0)
            {
                if (bpc != 8)
                {
                    throw new iText.IO.IOException(iText.IO.IOException.ColorDepthIsNotSupported).SetMessageParams(bpc);
                }
                if (colorspace is PdfArray)
                {
                    PdfArray  ca   = (PdfArray)colorspace;
                    PdfObject tyca = ca.Get(0);
                    if (!PdfName.ICCBased.Equals(tyca))
                    {
                        throw new iText.IO.IOException(iText.IO.IOException.ColorSpaceIsNotSupported).SetMessageParams(tyca.ToString
                                                                                                                           ());
                    }
                    PdfStream pr = (PdfStream)ca.Get(1);
                    int       n  = pr.GetAsNumber(PdfName.N).IntValue();
                    if (n != 4)
                    {
                        throw new iText.IO.IOException(iText.IO.IOException.NValueIsNotSupported).SetMessageParams(n);
                    }
                    icc = pr.GetBytes();
                }
                else
                {
                    if (!PdfName.DeviceCMYK.Equals(colorspace))
                    {
                        throw new iText.IO.IOException(iText.IO.IOException.ColorSpaceIsNotSupported).SetMessageParams(colorspace.
                                                                                                                       ToString());
                    }
                }
                stride = (int)(4 * width);
                TiffWriter wr = new TiffWriter();
                wr.AddField(new TiffWriter.FieldShort(TIFFConstants.TIFFTAG_SAMPLESPERPIXEL, 4));
                wr.AddField(new TiffWriter.FieldShort(TIFFConstants.TIFFTAG_BITSPERSAMPLE, new int[] { 8, 8, 8, 8 }));
                wr.AddField(new TiffWriter.FieldShort(TIFFConstants.TIFFTAG_PHOTOMETRIC, TIFFConstants.PHOTOMETRIC_SEPARATED
                                                      ));
                wr.AddField(new TiffWriter.FieldLong(TIFFConstants.TIFFTAG_IMAGEWIDTH, (int)width));
                wr.AddField(new TiffWriter.FieldLong(TIFFConstants.TIFFTAG_IMAGELENGTH, (int)height));
                wr.AddField(new TiffWriter.FieldShort(TIFFConstants.TIFFTAG_COMPRESSION, TIFFConstants.COMPRESSION_LZW));
                wr.AddField(new TiffWriter.FieldShort(TIFFConstants.TIFFTAG_PREDICTOR, TIFFConstants.PREDICTOR_HORIZONTAL_DIFFERENCING
                                                      ));
                wr.AddField(new TiffWriter.FieldLong(TIFFConstants.TIFFTAG_ROWSPERSTRIP, (int)height));
                wr.AddField(new TiffWriter.FieldRational(TIFFConstants.TIFFTAG_XRESOLUTION, new int[] { 300, 1 }));
                wr.AddField(new TiffWriter.FieldRational(TIFFConstants.TIFFTAG_YRESOLUTION, new int[] { 300, 1 }));
                wr.AddField(new TiffWriter.FieldShort(TIFFConstants.TIFFTAG_RESOLUTIONUNIT, TIFFConstants.RESUNIT_INCH));
                wr.AddField(new TiffWriter.FieldAscii(TIFFConstants.TIFFTAG_SOFTWARE, iText.Kernel.Version.GetInstance().GetVersion
                                                          ()));
                MemoryStream comp = new MemoryStream();
                TiffWriter.CompressLZW(comp, 2, imageBytes, (int)height, 4, stride);
                byte[] buf = comp.ToArray();
                wr.AddField(new TiffWriter.FieldImage(buf));
                wr.AddField(new TiffWriter.FieldLong(TIFFConstants.TIFFTAG_STRIPBYTECOUNTS, buf.Length));
                if (icc != null)
                {
                    wr.AddField(new TiffWriter.FieldUndefined(TIFFConstants.TIFFTAG_ICCPROFILE, icc));
                }
                wr.WriteFile(ms);
                imageBytes = ms.ToArray();
                return(imageBytes);
            }
            else
            {
                PngWriter png    = new PngWriter(ms);
                PdfArray  decode = GetPdfObject().GetAsArray(PdfName.Decode);
                if (decode != null)
                {
                    if (pngBitDepth == 1)
                    {
                        // if the decode array is 1,0, then we need to invert the image
                        if (decode.GetAsNumber(0).IntValue() == 1 && decode.GetAsNumber(1).IntValue() == 0)
                        {
                            int len = imageBytes.Length;
                            for (int t = 0; t < len; ++t)
                            {
                                imageBytes[t] ^= 0xff;
                            }
                        }
                    }
                }
                // if the decode array is 0,1, do nothing.  It's possible that the array could be 0,0 or 1,1 - but that would be silly, so we'll just ignore that case
                // todo: add decode transformation for other depths
                png.WriteHeader((int)width, (int)height, pngBitDepth, pngColorType);
                if (icc != null)
                {
                    png.WriteIccProfile(icc);
                }
                if (palette != null)
                {
                    png.WritePalette(palette);
                }
                png.WriteData(imageBytes, stride);
                png.WriteEnd();
                imageBytes = ms.ToArray();
                return(imageBytes);
            }
        }