예제 #1
0
        /// <summary>
        /// Merges files to tifffile
        /// </summary>
        public static void MergeFiles(string destinationFileName, IEnumerable <string> filesToMerge)
        {
            TiffBitmapEncoder encoder = new TiffBitmapEncoder();

            encoder.Compression = GetImageCompression(Image.FromFile(filesToMerge.ElementAt(0)));

            foreach (var file in filesToMerge)
            {
                BitmapDecoder decoder = TiffBitmapDecoder.Create(
                    ReadFile(file), BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);

                for (int i = 0; i < decoder.Frames.Count; i++)
                {
                    encoder.Frames.Add(decoder.Frames[i]);
                }
            }

            MemoryStream memoryStream = new MemoryStream();

            encoder.Save(memoryStream);

            using (Stream stream = File.Open(destinationFileName, FileMode.CreateNew, FileAccess.Write))
            {
                stream.Write(memoryStream.ToArray(), 0, (int)memoryStream.Length);
            }
        }
예제 #2
0
        /// <summary>
        /// Rotates specified page in tifffile. Rotate angle should be 0, 90, 180, 270
        /// </summary>
        public static Stream Rotate(Stream stream, int pageIndex, double angle)
        {
            TiffBitmapDecoder decoder = (TiffBitmapDecoder)TiffBitmapDecoder.Create(
                stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);

            TiffBitmapEncoder encoder = new TiffBitmapEncoder();

            encoder.Compression = GetImageCompression(new Bitmap(stream));

            for (int i = 0; i < decoder.Frames.Count; i++)
            {
                if (i == pageIndex)
                {
                    encoder.Frames.Add(RotateImage(decoder.Frames[i], angle));
                }
                else
                {
                    encoder.Frames.Add(decoder.Frames[i]);
                }
            }

            MemoryStream imageStream = new MemoryStream();

            encoder.Save(imageStream);

            return(imageStream);
        }
예제 #3
0
        public static void InsertFile(string destinationFileName, Dictionary <int, string> pageList)
        {
            TiffBitmapEncoder encoder = new TiffBitmapEncoder();

            encoder.Compression = GetImageCompression(Image.FromFile(destinationFileName));

            for (int i = 0; i < GetPageCount(destinationFileName); i++)
            {
                BitmapDecoder decoder = TiffBitmapDecoder.Create(ReadFile(destinationFileName), BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
                encoder.Frames.Add(decoder.Frames[i]);
            }

            foreach (var item in pageList)
            {
                BitmapDecoder newDecoder = TiffBitmapDecoder.Create(ReadFile(item.Value), BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
                int           indx       = item.Key == 0 ? 0 : item.Key - 1;
                encoder.Frames.Insert(indx, newDecoder.Frames[0]);
            }

            MemoryStream memoryStream = new MemoryStream();

            encoder.Save(memoryStream);

            Stream UpdateFile = File.Open(destinationFileName, FileMode.Create, FileAccess.Write);

            UpdateFile.Write(memoryStream.ToArray(), 0, (int)memoryStream.Length);
            UpdateFile.Close();
            UpdateFile.Dispose();
        }
예제 #4
0
        /// <summary>
        /// Swaps pages in tiff file
        /// </summary>
        /// <param name="fileName">Multitiff file name</param>
        /// <param name="sourcePageIndex">Source index</param>
        /// <param name="destinationPageIndex">Destination index</param>
        public static Stream SwapPages(Stream stream, int sourcePageIndex, int destinationPageIndex)
        {
            TiffBitmapDecoder decoder = (TiffBitmapDecoder)TiffBitmapDecoder.Create(
                stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);

            TiffBitmapEncoder encoder = new TiffBitmapEncoder();

            encoder.Compression = GetImageCompression(new Bitmap(stream));

            for (int i = 0; i < decoder.Frames.Count; i++)
            {
                if (i == sourcePageIndex)
                {
                    encoder.Frames.Add(decoder.Frames[destinationPageIndex]);
                }
                else if (i == destinationPageIndex)
                {
                    encoder.Frames.Add(decoder.Frames[sourcePageIndex]);
                }
                else
                {
                    encoder.Frames.Add(decoder.Frames[i]);
                }
            }

            MemoryStream imageStream = new MemoryStream();

            encoder.Save(imageStream);

            return(imageStream);
        }
예제 #5
0
        public override Models.Document LoadDocument(FileIOInfo info)
        {
            if (info == null)
            {
                return(null);
            }

            TiffBitmapDecoder tiff = new TiffBitmapDecoder(info.Stream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);

            Models.Document doc = new Models.Document();
            Models.Page     page;

            for (int i = 0; i < tiff.Frames.Count; i++)
            //foreach (BitmapFrame frame in tiff.Frames)
            {
                page = new Models.Page();

                page.fName       = info.FullFileName;
                page.image       = TiffFrameToBitmapImage(tiff.Frames[i]);
                page.number      = i + 1;
                page.imageStream = (MemoryStream)page.image.StreamSource;

                doc.pages.Add(new ViewModels.PageViewModel(page));
            }


            return(doc);
        }
예제 #6
0
        /// <summary>
        /// Loads the PNG XMP meta data using a dummy TIFF.
        /// </summary>
        /// <param name="xmp">The XMP string to load.</param>
        /// <returns>The loaded XMP block, or null.</returns>
        private static BitmapMetadata LoadPNGMetadata(string xmp)
        {
            BitmapMetadata xmpData = null;

            using (MemoryStream stream = new MemoryStream())
            {
                // PNG stores the XMP meta-data in an iTXt chunk as an UTF8 encoded string,
                // so we have to save it to a dummy tiff and grab the XMP meta-data on load.
                BitmapMetadata tiffMetadata = new BitmapMetadata("tiff");
                tiffMetadata.SetQuery("/ifd/xmp", new BitmapMetadata("xmp"));
                tiffMetadata.SetQuery("/ifd/xmp", Encoding.UTF8.GetBytes(xmp));

                BitmapSource      source  = BitmapSource.Create(1, 1, 96.0, 96.0, PixelFormats.Gray8, null, new byte[] { 255 }, 1);
                TiffBitmapEncoder encoder = new TiffBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(source, null, tiffMetadata, null));
                encoder.Save(stream);

                TiffBitmapDecoder dec = new TiffBitmapDecoder(stream, BitmapCreateOptions.DelayCreation, BitmapCacheOption.None);

                if (dec.Frames.Count == 1)
                {
                    BitmapMetadata meta = dec.Frames[0].Metadata as BitmapMetadata;
                    if (meta != null)
                    {
                        xmpData = meta.GetQuery("/ifd/xmp") as BitmapMetadata;
                    }
                }
            }

            return(xmpData);
        }
예제 #7
0
        public override void Show(System.Windows.Controls.ContentControl contentControl, object writer)
        {
            ScrollViewer scrollViewer = new ScrollViewer();
            StackPanel   stackPanel   = new StackPanel();

            stackPanel.Orientation = Orientation.Vertical;
            scrollViewer.Content   = stackPanel;

            this.m_ImageStreamSource = new FileStream(this.FullFileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            TiffBitmapDecoder tiffDecoder = new TiffBitmapDecoder(this.m_ImageStreamSource, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);

            try
            {
                for (int i = 0; i < tiffDecoder.Frames.Count; i++)
                {
                    BitmapSource bitMapSource = tiffDecoder.Frames[i];
                    Image        image        = new Image();
                    image.Source = bitMapSource;
                    stackPanel.Children.Add(image);
                }
                contentControl.Content = scrollViewer;
            }
            catch
            {
            }
        }
예제 #8
0
        public BitmapSource GetTiffBitmapSource(string filename, int pageIndex, CancellationTokenSource cancellationTokenSource)
        {
            BitmapSource result = null;

            lock (m_lock)
            {
                TiffBitmapDecoder tiffBitmapDecoder = null;
                while (tiffBitmapDecoder == null && !cancellationTokenSource.IsCancellationRequested)
                {
                    System.Windows.Application.Current.Dispatcher.Invoke(new Action(() =>
                    {
                        //using (MemoryStream fileMem = new MemoryStream(File.ReadAllBytes(filename)))
                        {
                            tiffBitmapDecoder = new TiffBitmapDecoder(new Uri(filename), BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
                            m_TiffBitmapDecodersFrameCount[filename] = tiffBitmapDecoder.Frames.Count;
                            result = tiffBitmapDecoder.Frames[pageIndex];
                        }
                    }), TimeSpan.FromMilliseconds(500), null);
                }

                // Use GC.Collect to release the TiffBitmapDecoder memory - (.NET "Bug")
                GC.Collect();

                return(result);
            }
        }
예제 #9
0
        /// <summary>
        /// Reads Frame by its index
        /// </summary>
        public static BitmapFrame GetTiffPage(Stream stream, int pageIndex)
        {
            TiffBitmapDecoder decoder = new TiffBitmapDecoder(
                stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnDemand);

            return(decoder.Frames[pageIndex]);
        }
예제 #10
0
        public static AsterTileLocal FromFile(string geotiffFilename, Point ptSw)
        {
            var rt = new AsterTileLocal
            {
                PtSouthwest = ptSw,
                PtNortheast = new Point(ptSw.Lat + 1, ptSw.Lon + 1)
            };

            // Open a Stream and decode a GeoTIFF image
            Stream imageStreamSource = new FileStream(geotiffFilename, FileMode.Open, FileAccess.Read, FileShare.Read);
            var    decoder           = new TiffBitmapDecoder(imageStreamSource, BitmapCreateOptions.PreservePixelFormat,
                                                             BitmapCacheOption.Default);
            BitmapSource bitmapSource = decoder.Frames[0];

            var pixels = new short[AsterTileSidePointCount * AsterTileSidePointCount];


            bitmapSource.CopyPixels(pixels, sizeof(short) * AsterTileSidePointCount, 0);

            //organize pixels in 2d array
            rt.GeotiffPoints = new short[AsterTileSidePointCount, AsterTileSidePointCount];
            //Buffer.BlockCopy(pixels, 0, rt.geotiff_points, 0, sizeof(short) * ASTERTileSidePointCount * ASTERTileSidePointCount);

            for (var yc = 0; yc < AsterTileSidePointCount; yc++)
            {
                for (var xc = 0; xc < AsterTileSidePointCount; xc++)
                {
                    rt.GeotiffPoints[xc, yc] = pixels[xc + yc * AsterTileSidePointCount];
                }
            }

            return(rt);
        }
예제 #11
0
        /// <summary>
        /// Opens image file.
        /// </summary>
        /// <param name="stream">Specifies the image file.</param>
        /// <returns>True, if succeeded; otherwise - false.</returns>
        public bool Open(Stream stream)
        {
            try
            {
                using (stream)
                {
                    TiffBitmapDecoder tiffDecoder = new TiffBitmapDecoder(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad);

                    //we need to break out the frames now because they can only be accessed on the same thread we do the decode on.
                    _bitmapFrames = new ObservableCollection <BitmapFrame>(tiffDecoder.Frames);

                    //_currentFrameNumber = 0;
                    CurrentFrameNumber = 0;
                    LastError          = null;
                    return(true);
                }
            }

            catch (Exception ex)
            {
                LastError = String.Format("Can't open stream: {0}", ex.Message);
            }

            return(false);
        }
예제 #12
0
        static public void Split(string fileName)
        {
            using (Stream imageStreamSource = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                TiffBitmapDecoder decoder = new TiffBitmapDecoder(imageStreamSource, BitmapCreateOptions.DelayCreation, BitmapCacheOption.OnDemand);

                int count = decoder.Frames.Count;
                for (int _i = 0; _i < count; _i++)
                {
                    string outName = Path.GetDirectoryName(fileName) + @"\" + Path.GetFileNameWithoutExtension(fileName) + "_PAGE" + _i + Path.GetExtension(fileName);

                    using (FileStream splitFiles = new FileStream(outName, FileMode.Create))
                    {
                        TiffBitmapEncoder encoder = new TiffBitmapEncoder();
                        encoder.Compression = TiffCompressOption.Ccitt4;
                        List <ColorContext> c = new List <ColorContext>();
                        c.Add(new ColorContext(System.Windows.Media.PixelFormats.BlackWhite));
                        encoder.ColorContexts = new System.Collections.ObjectModel.ReadOnlyCollection <ColorContext>(c);
                        encoder.Frames.Add(decoder.Frames[_i]);
                        encoder.Save(splitFiles);
                    }
                }
            }
            return;
        }
예제 #13
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="image"></param>
        /// <param name="pagesToRemove"></param>
        /// <returns></returns>
        public static Stream RemovePagesFromImageStream(Stream image, IEnumerable <int> pagesToRemove)
        {
            MemoryStream write = new MemoryStream();

            Dictionary <int, int> pages   = (pagesToRemove == null) ? new Dictionary <int, int>() : pagesToRemove.ToDictionary(p => p);
            TiffBitmapEncoder     encoder = new TiffBitmapEncoder();

            encoder.Compression = TiffCompressOption.Ccitt4;
            TiffBitmapDecoder decoder;

            decoder = new TiffBitmapDecoder(image, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnDemand);

            int frames = decoder.Frames.Count;

            for (int i = 0; i < frames; i++)
            {
                if (pages.ContainsKey(i) == true)
                {
                    continue;
                }
                encoder.Frames.Add(decoder.Frames[i]);
            }

            encoder.Save(write);

            return(write);
        }
예제 #14
0
        public static BitmapDecoder CreateBitmapDecoder(BitmapEncodingMode mode, Stream fs, BitmapCreateOptions createOpt, BitmapCacheOption cacheOpt)
        {
            BitmapDecoder e = null;

            switch (mode)
            {
            case BitmapEncodingMode.Bmp:
                e = new BmpBitmapDecoder(fs, createOpt, cacheOpt);
                break;

            case BitmapEncodingMode.Gif:
                e = new GifBitmapDecoder(fs, createOpt, cacheOpt);
                break;

            case BitmapEncodingMode.Jpeg:
                e = new JpegBitmapDecoder(fs, BitmapCreateOptions.None, BitmapCacheOption.Default);
                break;

            case BitmapEncodingMode.Png:
                e = new PngBitmapDecoder(fs, createOpt, cacheOpt);
                break;

            case BitmapEncodingMode.Tiff:
                e = new TiffBitmapDecoder(fs, createOpt, cacheOpt);
                break;

            case BitmapEncodingMode.Wmp:
                e = new WmpBitmapDecoder(fs, createOpt, cacheOpt);
                break;
            }
            return(e);
        }
        public static BitmapFrame GetBitmapFrameFromImageStream(Stream imageStream, String fileType)
        {
            BitmapFrame bitmapFrame;
            BitmapDecoder bitmapDecoder;
            
            if (fileType.Equals("TIF",StringComparison.OrdinalIgnoreCase))
            {
                bitmapDecoder = new TiffBitmapDecoder(imageStream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
            }
            else if (fileType.Equals("PNG",StringComparison.OrdinalIgnoreCase))
            {
                bitmapDecoder = new PngBitmapDecoder(imageStream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
            }
            else if (fileType.Equals("JPG", StringComparison.OrdinalIgnoreCase) || fileType.Equals("JPEG", StringComparison.OrdinalIgnoreCase))
            {
                bitmapDecoder = new JpegBitmapDecoder(imageStream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
            }
            else
            {
                throw new Exception(String.Format("Not supported file type: {0}", fileType));
            }

            bitmapFrame = bitmapDecoder.Frames[0];
            return bitmapFrame;
        }
예제 #16
0
        public async Task <SplitResult> SplitAsync(string inputFilePath, string outputFilePath, int[] pageNumbers)
        {
            SplitResult result = new SplitResult();

            try
            {
                if (inputFilePath == null)
                {
                    throw new ArgumentNullException(nameof(inputFilePath));
                }

                if (outputFilePath == null)
                {
                    throw new ArgumentNullException(nameof(outputFilePath));
                }

                if (pageNumbers == null)
                {
                    throw new ArgumentNullException(nameof(pageNumbers));
                }

                result.InputFilePath = inputFilePath;

                await using (Stream inputStream = _fileSystem.FileStream.Create(inputFilePath, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    var decoder = new TiffBitmapDecoder(inputStream, BitmapCreateOptions.PreservePixelFormat,
                                                        BitmapCacheOption.Default);

                    Encoder = new TiffBitmapEncoder();

                    foreach (int pageNumber in pageNumbers)
                    {
                        if (pageNumber > 0 && pageNumber <= decoder.Frames.Count)
                        {
                            Encoder.Frames.Add(decoder.Frames[pageNumber - 1]);
                        }
                    }

                    if (Encoder.Frames.Any())
                    {
                        await using (Stream outputStream = _fileSystem.FileStream.Create(outputFilePath, FileMode.Create, FileAccess.Write))
                        {
                            Encoder.Save(outputStream);
                        }
                    }
                    else
                    {
                        throw new InvalidOperationException("No pages were saved to the output. This may be because no pages were indicated, or the indicated pages were not found in the source file.");
                    }
                }
            }
            catch (Exception e)
            {
                result.ErrorStatus = e.Message;
                result.StackTrace  = e.StackTrace;
            }

            return(result);
        }
예제 #17
0
        public static void LoadImage(Uri fileUri, Image frente)
        {
            TiffBitmapDecoder tiffBitmapDecoder = new TiffBitmapDecoder(fileUri,
                                                                        BitmapCreateOptions.None,
                                                                        BitmapCacheOption.Default);

            frente.Source = tiffBitmapDecoder.Frames[0];
        }
예제 #18
0
        public override ImageData Read(Stream file, ImageMetaData info)
        {
            var decoder = new TiffBitmapDecoder(file,
                                                BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad);
            var frame = decoder.Frames[0];

            frame.Freeze();
            return(new ImageData(frame, info));
        }
예제 #19
0
 public static ImageSource GetTiffImageFromSource(string embededlargeImageName)
 {
     try
     {
         var stream   = Assembly.GetExecutingAssembly().GetManifestResourceStream(embededlargeImageName);
         var decorder = new TiffBitmapDecoder(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
         return(decorder.Frames[0]);
     }
     catch { return(null); }
 }
예제 #20
0
        public void Open(string fileName)
        {
            this.imageStreamSource = new MemoryStream();
            Bitmap b = new Bitmap(fileName);

            b.Save(imageStreamSource, ImageFormat.Tiff);
            b.Dispose();
            this.imageStreamSource.Seek(0, SeekOrigin.Begin);
            this.decoder = new TiffBitmapDecoder(imageStreamSource, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnDemand);
        }
예제 #21
0
        /// <summary>
        /// Returns the pages number in given tiff file
        /// </summary>
        public static int GetPageCount(string fileName)
        {
            using (Stream stream = File.OpenRead(fileName))
            {
                BitmapDecoder decoder = TiffBitmapDecoder.Create(
                    stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);

                return(decoder.Frames.Count);
            }
        }
    private static IEnumerable <BitmapSource> Load16BitTiff(Stream source)
    {
        var decoder = new TiffBitmapDecoder(source, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);

        for (int i = 0; i < decoder.Frames.Count; i++)
        {
            // return all frames that are present in the input.
            yield return(decoder.Frames[i]);
        }
    }
예제 #23
0
        private static void Test(string path)
        {
            //TiffBitmapDecoder decoder = new TiffBitmapDecoder(new MemoryStream(File.ReadAllBytes(path)), BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
            //int totFrames = decoder.Frames.Count;

            //BitmapEncoder enc = new BmpBitmapEncoder();

            //foreach (var item in decoder.Frames)
            //{
            //    enc.Frames.Add(BitmapFrame.Create());
            //}



            //for (int i = 0; i < totFrames; i++)
            //{
            //    enc.Frames.Add(BitmapFrame.Create());
            //}

            using (var msTemp = new MemoryStream(File.ReadAllBytes(path)))
            {
                TiffBitmapDecoder decoder = new TiffBitmapDecoder(msTemp, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
                int          totFrames    = decoder.Frames.Count;
                BitmapSource bitmapSource = decoder.Frames[0];

                TiffBitmapEncoder encoder = new TiffBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(bitmapSource));
            }



            //System.Drawing.Imaging.Encoder encoder = System.Drawing.Imaging.Encoder.SaveFlag;
            //ImageCodecInfo encoderInfo = ImageCodecInfo.GetImageEncoders().First(i => i.MimeType == "image/tiff");
            //EncoderParameters encoderParameters = new EncoderParameters(1);

            //Image tiffImage = Image.FromFile(path);

            //// Save the first frame of the multi page tiff
            //encoderParameters.Param[0] = new EncoderParameter(encoder, (long)EncoderValue.MultiFrame);
            //Bitmap firstImage = (Bitmap)_scannedPages[0].RawContent;
            //firstImage.Save(fileName, encoderInfo, encoderParameters);

            //// Add the remaining images to the tiff
            //encoderParameters.Param[0] = new EncoderParameter(encoder, (long)EncoderValue.FrameDimensionPage);

            //for (int i = 1; i < _scannedPages.Count; i++)
            //{
            //    Bitmap img = (Bitmap)_scannedPages[i].RawContent;
            //    firstImage.SaveAdd(img, encoderParameters);
            //}

            //// Close out the file
            //encoderParameters.Param[0] = new EncoderParameter(encoder, (long)EncoderValue.Flush);
            //firstImage.SaveAdd(encoderParameters);
        }
예제 #24
0
        public bool ReadNextTiff(ref Image8 nextImage)
        {
            BitmapSource bitmapSource;

            if (_imageStreamSource == null)//this is the first read
            {
                //Initialize image stream - open first file
                _imageStreamSource = new FileStream(_fileNames[_currentFileIndex], FileMode.Open, FileAccess.Read, FileShare.Read);
                _tiffDecoder       = new TiffBitmapDecoder(_imageStreamSource, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.None);
            }
            else//this is not the first read
            {
                //check if the frame we are supposed to read is outside of the current file
                if (_currentImageIndex >= _tiffDecoder.Frames.Count)
                {
                    //close old file
                    _tiffDecoder = null;
                    _imageStreamSource.Close();
                    _imageStreamSource.Dispose();
                    //advance file index
                    _currentFileIndex++;
                    //check if the current file is already the last file - in that case we are done reading
                    if (_currentFileIndex >= _fileNames.Length)
                    {
                        return(false);
                    }
                    else
                    {
                        //open next file and create corresponding decoder
                        _imageStreamSource = new FileStream(_fileNames[_currentFileIndex], FileMode.Open, FileAccess.Read, FileShare.Read);
                        _tiffDecoder       = new TiffBitmapDecoder(_imageStreamSource, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.None);
                        _currentImageIndex = 0;
                    }
                }//if _currentImageIndex >= _tiffDecoder.Frames.Count
            }
            //at this point we should have a valid file open, the tiffdecoder set and _currentImageIndex should point to the image we want to return next
            bitmapSource = _tiffDecoder.Frames[_currentImageIndex];
            //check that nextImage is compatible with the images
            if (nextImage == null || nextImage.Width != bitmapSource.PixelWidth || nextImage.Height != bitmapSource.PixelHeight)
            {
                nextImage = new Image8(bitmapSource.PixelWidth, bitmapSource.PixelHeight);
            }
            //copy content from the bitmap source into nextImage
            if (bitmapSource.Format == PixelFormats.Gray8 || bitmapSource.Format == PixelFormats.Indexed8)
            {
                bitmapSource.CopyPixels(System.Windows.Int32Rect.Empty, (IntPtr)nextImage.Image, nextImage.Height * nextImage.Stride, nextImage.Stride);
            }
            else
            {
                throw new NotSupportedException("File pixel formats other than 8-bit indexed or 8-bit grayscale are currently not supported");
            }
            _currentImageIndex++;
            return(true);
            //throw new NotImplementedException();
        }
        /// <summary>
        /// Load an image from file.
        /// </summary>
        /// <param name="filename">Absolute path to image to load, incl. extension</param>
        /// <returns>Bitmap instance, or null if loading failed</returns>
        public static BitmapSource LoadImageFromFile(string filename)
        {
            if (filename == null)
            {
                return(null);
            }
            if (!File.Exists(filename))
            {
                return(null);
            }

            string ext = Path.GetExtension(filename).ToLower();

            BitmapSource bitmap = null;

            try
            {
                using (Stream in_strm = File.OpenRead(filename))
                {
                    BitmapCreateOptions cr_option = BitmapCreateOptions.PreservePixelFormat;
                    BitmapCacheOption   ca_option = BitmapCacheOption.OnLoad;
                    BitmapDecoder       dec       = null;
                    switch (ext)
                    {
                    case ".bmp":  dec = new BmpBitmapDecoder(in_strm, cr_option, ca_option); break;

                    case ".gif":  dec = new GifBitmapDecoder(in_strm, cr_option, ca_option); break;

                    case ".jpeg": dec = new JpegBitmapDecoder(in_strm, cr_option, ca_option); break;

                    case ".jpg":  dec = new JpegBitmapDecoder(in_strm, cr_option, ca_option); break;

                    case ".png":  dec = new PngBitmapDecoder(in_strm, cr_option, ca_option); break;

                    case ".tiff": dec = new TiffBitmapDecoder(in_strm, cr_option, ca_option); break;
                    }
                    if (dec == null)
                    {
                        Log.Error("No suitable encoder found for file '{0}'", filename);
                        return(null);
                    }

                    bitmap = dec.Frames[0];
                }
            }
            catch (Exception exc)
            {
                Log.Error("Error loading file '{0}': {1}", filename, exc);
                bitmap = null;
            }

            return(bitmap);
        }
예제 #26
0
        /// <summary>
        /// Loads an image from a given file path
        /// </summary>
        /// <param name="path">File Path to image</param>
        /// <param name="bitDepth">bit depth of each pixel</param>
        /// <param name="isBayered">Flag to indicate if the image is bayer matrix encoded</param>
        /// <param name="rawConverter">Which type of raw converter to use, when image is in RAW format</param>
        /// <param name="ct">Token to cancel operation</param>
        /// <returns></returns>
        public static Task <IImageData> FromFile(string path, int bitDepth, bool isBayered, RawConverterEnum rawConverter, CancellationToken ct = default(CancellationToken))
        {
            return(Task.Run(async() => {
                if (!File.Exists(path))
                {
                    throw new FileNotFoundException();
                }
                BitmapDecoder decoder;
                switch (Path.GetExtension(path).ToLower())
                {
                case ".gif":
                    decoder = new GifBitmapDecoder(new Uri(path), BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad);
                    return await BitmapToImageArray(decoder, isBayered);

                case ".tif":
                case ".tiff":
                    decoder = new TiffBitmapDecoder(new Uri(path), BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad);
                    return await BitmapToImageArray(decoder, isBayered);

                case ".jpg":
                case ".jpeg":
                    decoder = new JpegBitmapDecoder(new Uri(path), BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad);
                    return await BitmapToImageArray(decoder, isBayered);

                case ".png":
                    decoder = new PngBitmapDecoder(new Uri(path), BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad);
                    return await BitmapToImageArray(decoder, isBayered);

                case ".xisf":
                    return await XISF.Load(new Uri(path), isBayered);

                case ".fit":
                case ".fits":
                    return await FITS.Load(new Uri(path), isBayered);

                case ".cr2":
                case ".cr3":
                case ".nef":
                case ".raf":
                case ".raw":
                case ".pef":
                case ".dng":
                case ".arw":
                case ".orf":
                    return await RawToImageArray(path, bitDepth, rawConverter, ct);

                default:
                    throw new NotSupportedException();
                }
            }));
        }
예제 #27
0
        private BitmapSource LoadReference(string fileName)
        {
            var imageStreamSource = Assembly
                                    .GetExecutingAssembly()
                                    .GetManifestResourceStream(
                "NSane.Tests.images." + fileName + ".tiff");

            var decoder = new TiffBitmapDecoder(imageStreamSource,
                                                BitmapCreateOptions.PreservePixelFormat,
                                                BitmapCacheOption.Default);
            BitmapSource ret = decoder.Frames[0];

            return(ret);
        }
예제 #28
0
        private void LoadDataFromFile(string filePath, int frameNumber = 0)
        {
            // open a file stream and keep it open until we're done reading the file
            System.IO.Stream stream = new System.IO.FileStream(filePath, System.IO.FileMode.Open,
                                                               System.IO.FileAccess.Read, System.IO.FileShare.Read);

            // carefully open the file to see if it will decode
            TiffBitmapDecoder decoder;

            try
            {
                decoder = new TiffBitmapDecoder(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
            }
            catch
            {
                Console.WriteLine("TiffBitmapDecoder crashed");
                stream.Dispose();
                data = null;
                return;
            }

            // access information about the image
            int          imageFrames      = decoder.Frames.Count;
            BitmapSource bitmapSource     = decoder.Frames[frameNumber];
            int          sourceImageDepth = bitmapSource.Format.BitsPerPixel;
            int          bytesPerPixel    = sourceImageDepth / 8;
            Size         imageSize        = new Size(bitmapSource.PixelWidth, bitmapSource.PixelHeight);

            width  = imageSize.Width;
            height = imageSize.Height;

            // fill a byte array with source data bytes from the file
            int imageByteCount = pixelCount * bytesPerPixel;

            byte[] bytesSource = new byte[imageByteCount];
            bitmapSource.CopyPixels(bytesSource, imageSize.Width * bytesPerPixel, 0);

            // close the original file
            stream.Dispose();

            // convert the byte array to an array of values (works on any bit depth)
            data = new double[pixelCount];
            for (int i = 0; i < data.Length; i++)
            {
                for (int byteNumber = 0; byteNumber < bytesPerPixel; byteNumber++)
                {
                    data[i] += bytesSource[i * bytesPerPixel + byteNumber] << (byteNumber * 8);
                }
            }
        }
        public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (values != null && values.Length == 2)
            {
                string fileName = values[0] as string;
                int    pageNo   = (int)values[1];

                string key = fileName + "_P" + pageNo.ToString();

                BitmapImage bitmapImage;

                if (bitmapCache.TryGetValue(key, out bitmapImage) == false)
                {
                    // Performance -  Do nothing while the system is running -
                    if (AppDataCenter.Singleton.IsRunning == true)
                    {
                        return(null);
                    }

                    lock (m_lock)
                    {
                        using (var srcFile = System.IO.File.OpenRead(fileName))
                        {
                            var dec = TiffBitmapDecoder.Create(srcFile, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);

                            var page = dec.Frames[pageNo - 1];

                            var buff = BitmapFrameToStream(page);

                            bitmapImage = new BitmapImage();

                            bitmapImage.BeginInit();
                            bitmapImage.CacheOption       = BitmapCacheOption.OnLoad;
                            bitmapImage.DecodePixelHeight = 200;
                            bitmapImage.StreamSource      = buff;
                            bitmapImage.CreateOptions     = BitmapCreateOptions.PreservePixelFormat;
                            bitmapImage.EndInit();

                            bitmapCache[key] = bitmapImage;
                        }
                    }
                }

                return(bitmapImage);
            }
            else
            {
                return(null);
            }
        }
        /// <summary>
        /// Loads image from specified file.
        /// </summary>
        private BitmapSource LoadImage(string filename, ref int pageIndex)
        {
            if (_imageFileStream != null)
            {
                _imageFileStream.Dispose();
                _imageFileStream = null;
            }

            string fileExt = System.IO.Path.GetExtension(filename).ToUpper();

            switch (fileExt)
            {
            // PDF file
            case ".PDF":
                if (BarcodeGlobalSettings.IsDemoVersion)
                {
                    MessageBox.Show("Evaluation version allows to extract images only from the first page of PDF document.", "Warning", MessageBoxButton.OK, MessageBoxImage.Warning);
                }
                if (pageIndex == -1)
                {
                    return(SelectPdfPageWindow.SelectPdfPageImage(filename, ref pageIndex));
                }
                else
                {
                    return(SelectPdfPageWindow.GetPdfPageImage(filename, pageIndex));
                }

            // TIFF file
            case ".TIF":
            case ".TIFF":
                _imageFileStream = new FileStream(filename, FileMode.Open, FileAccess.Read);
                TiffBitmapDecoder tiffDecoder = new TiffBitmapDecoder(_imageFileStream, BitmapCreateOptions.None, BitmapCacheOption.Default);
                if (pageIndex == -1 && tiffDecoder.Frames.Count > 1)
                {
                    pageIndex = SelectImageFrameWindow.SelectFrameIndex(tiffDecoder.Frames.Count);
                    return(tiffDecoder.Frames[pageIndex]);
                }
                return(tiffDecoder.Frames[0]);

            // image
            default:
                _imageFileStream = new FileStream(filename, FileMode.Open, FileAccess.Read);
                BitmapImage image = new BitmapImage();
                image.BeginInit();
                image.StreamSource = _imageFileStream;
                image.CacheOption  = BitmapCacheOption.OnLoad;
                image.EndInit();
                return(image);
            }
        }