public void ConvertToGdiPlusBitmap()
        {
            // arrange
            BitmapSource bitmapSource;
            const string fileName = "1200x1500.png";
            using (var inputStream = AssemblyExtensions.OpenScopedResourceStream<BitmapSourceExtensionsTest> (fileName))
            {
                var decoder = new PngBitmapDecoder (
                    inputStream,
                    BitmapCreateOptions.PreservePixelFormat,
                    BitmapCacheOption.Default
                    );
                bitmapSource = decoder.Frames[0];
            }

            // act
            var bitmap = bitmapSource.ConvertToGdiPlusBitmap ();

            // assert
            using (var actualStream = new MemoryStream())
            {
                bitmap.Save (actualStream, ImageFormat.Png);
                ProgramTest.AssertStreamsAreEqual<BitmapSourceExtensionsTest> (fileName, actualStream);
            }
        }
Example #2
0
        private static ImageSource RetriveImage(string imagePath)
        {
            Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(imagePath);

            switch (imagePath.Substring(imagePath.Length - 3))
            {
            case "jpg":
                var jpgDecoder = new System.Windows.Media.Imaging.JpegBitmapDecoder(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
                return(jpgDecoder.Frames[0]);

            case "bmp":
                var bmpDecoder = new System.Windows.Media.Imaging.BmpBitmapDecoder(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
                return(bmpDecoder.Frames[0]);

            case "png":
                var pngDecoder = new System.Windows.Media.Imaging.PngBitmapDecoder(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
                return(pngDecoder.Frames[0]);

            case "ico":
                var icoDecoder = new System.Windows.Media.Imaging.IconBitmapDecoder(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
                return(icoDecoder.Frames[0]);

            default:
                return(null);
            }
        }
Example #3
0
 public static BitmapSource GetIcon(string icData) {
   BitmapSource rez;
   if(string.IsNullOrEmpty(icData)) {
     icData = string.Empty;
   }
   if(_icons.TryGetValue(icData, out rez)) {
     return rez;
   }
   lock(_icons) {
     if(!_icons.TryGetValue(icData, out rez)) {
       if(icData.StartsWith("data:image/png;base64,")) {
         var bitmapData = Convert.FromBase64String(icData.Substring(22));
         var streamBitmap = new System.IO.MemoryStream(bitmapData);
         var decoder = new PngBitmapDecoder(streamBitmap, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.None);
         rez = decoder.Frames[0];
         _icons[icData] = rez;
       } else if(icData.StartsWith("component/Images/")) {
         var url = new Uri("pack://application:,,,/Dashboard;" + icData, UriKind.Absolute);
         var decoder = new PngBitmapDecoder(url, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.None);
         rez = decoder.Frames[0];
         _icons[icData] = rez;
       }
     }
   }
   return rez;
 }
Example #4
0
        /// <summary>
        /// WriteableBitmap -> IplImage
        /// </summary>
        private void TestWriteableBitmap()
        {
            // Load 16-bit image to WriteableBitmap
            PngBitmapDecoder decoder = new PngBitmapDecoder(
                new Uri(FilePath.Image.Depth16Bit, UriKind.Relative),
                BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default
            );
            BitmapSource bs = decoder.Frames[0];
            WriteableBitmap wb = new WriteableBitmap(bs);

            // Convert wb into IplImage
            IplImage ipl = wb.ToIplImage();
            //IplImage ipl32 = new IplImage(wb.PixelWidth, wb.PixelHeight, BitDepth.U16, 1);
            //WriteableBitmapConverter.ToIplImage(wb, ipl32);

            // Print pixel values
            for (int i = 0; i < ipl.Height; i++)
            {
                Console.WriteLine("x:{0} y:{1} v:{2}", i, i, ipl[i, 128]);
            }

            // Show 16-bit IplImage
            using (new CvWindow("from WriteableBitmap to IplImage", ipl))
            {
                Cv.WaitKey();
            }
        }
        void CreateImage()
        {
            Random random = new Random();
            int pictureNumber = random.Next(0, this.imageNameList.Count);

            string background_path = this.PicturePathList[pictureNumber];
            Stream imageStreamSource = new FileStream(background_path, FileMode.Open, FileAccess.Read, FileShare.Read);
            PngBitmapDecoder decoder = new PngBitmapDecoder(imageStreamSource, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
            BitmapSource bitmapSource = decoder.Frames[0];

            Image newImage = new Image();
            newImage.Source = bitmapSource;
            newImage.MaxWidth = this.pictureSize;
            newImage.MaxHeight = this.pictureSize;

            Canvas root = this.Content as Canvas;
            Point point = new Point(random.Next(0, (int)root.ActualWidth - this.pictureSize), -this.pictureSize);
            float speed = (random.Next((int)(this.minDownSpeed * 1000), (int)(this.maxDownSpeed * 1000))) / 1000.0f;

            PictureData pictureData = new PictureData(
                newImage,
                speed,
                point,
                this.imageNameList[pictureNumber]
                );

            root.Children.Add(newImage);

            imageDictionary[this.imageNameList[pictureNumber]].Add(pictureData);
        }
Example #6
0
        private ImageSource assembleTiles(String tileDirectory, int tileW, int tileH, string instanceMarker, string extension, out int width, out int height, string name, int imageWidth, int imageHeight, double scale, CropTransform cropAfterRotating, Model.RotateTransform rotate, String outputDirectory)
        {
            // Now that we have our tiles on the hard drive, piece them back together to display to the user

            // WPF assemblage is too memory-intensive (as far as I can tell). Shell out to GDI+
            TileHelper.Concatenater helper = new TileHelper.Concatenater();
            string fileName = helper.ConcatenateTiles(imageHeight, imageWidth, tileH, tileW, tileDirectory, instanceMarker, extension, name, scale, cropAfterRotating, rotate, outputDirectory);
            // Now that the files are concatenated, save off the matching xml
            string xmlFileName = String.Format("{0}.{1}.{2}.xml", _container.Name, instanceMarker, extension);
            saveXmlFile(xmlFileName);
            // I think I need to save off a small version to display in the UI

            DrawingVisual dv = new DrawingVisual();
            using (DrawingContext ctx = dv.RenderOpen())
            {
                PngBitmapDecoder d = new PngBitmapDecoder(new Uri(fileName), BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
                ctx.DrawImage(d.Frames[0], new Rect(0, 0, (int)d.Frames[0].Width, (int)d.Frames[0].Height));
            }
            // Scale it back down for UI
            double displayScale = (_container.DisplayScale <= 0 ? 0.1 : _container.DisplayScale);
            width = (int)(dv.ContentBounds.Width * displayScale);
            height = (int)(dv.ContentBounds.Height * displayScale);
            ScaleTransform scaleTrans = new ScaleTransform(displayScale, displayScale);
            dv.Transform = scaleTrans;
            _rtb = new RenderTargetBitmap(width, height, 96, 96, PixelFormats.Pbgra32);
            _rtb.Render(dv);

            // Now that we're done with the tiles, clean up
            if (System.Configuration.ConfigurationSettings.AppSettings["deleteTiles"].ToLower() == "true")
            {
                helper.deleteTiles(tileDirectory, instanceMarker, extension);
            }

            return (ImageSource)_rtb;
        }
Example #7
0
        private System.Windows.Media.ImageSource PngImageSource(string embeddedPath)
        {
            Stream stream  = this.GetType().Assembly.GetManifestResourceStream(embeddedPath);
            var    decoder = new System.Windows.Media.Imaging.PngBitmapDecoder(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);

            return(decoder.Frames[0]);
        }
        // Deserializes a serialized grid tile, making it fit for use in our editor grid.
        public GridTile DeserializeGridTile(GridTileSerializable tile)
        {
            if (tile.Image == null) return null;

            try
            {
                // Effectively creating an image out of the byte array in the serialized grid tile.
                Image myImage = new Image();
                using (MemoryStream stream = new MemoryStream(tile.Image))
                {
                    PngBitmapDecoder decoder = new PngBitmapDecoder(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad);
                    BitmapSource bitmapSource = decoder.Frames[0];
                    myImage.Source = bitmapSource;
                }

                return new GridTile(tile.Rotation, tile.Id, myImage, tile.CollisionMap)
                {
                    Row = tile.Row,
                    Column = tile.Column,
                    CollisionMap = tile.CollisionMap
                };
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                return null;
            }
        }
 public ImageSource GetImageSource()
 {
     using (var stream = new FileStream(this.path, FileMode.Open, FileAccess.Read))
     {
         var png = new PngBitmapDecoder(stream, BitmapCreateOptions.None, BitmapCacheOption.Default);
         return png.Frames[0];
     }
 }
Example #10
0
 public static BitmapSource ByteToBitmapSource(byte[] blob)
 {
     byte[] picture = blob;
     MemoryStream stream = new MemoryStream();
     stream.Write(picture, 0, picture.Length);
     PngBitmapDecoder bmpDecoder = new PngBitmapDecoder(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.None);
     return (BitmapSource)bmpDecoder.Frames[0];
 }
 public static ImageSource FromArray(byte[] bytes)
 {
     using (var memoryStream = new MemoryStream(bytes))
     {
         var decoder = new PngBitmapDecoder(memoryStream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad);
         BitmapSource bitmapFrame = decoder.Frames[0];                            
         return bitmapFrame;
     }
 }
Example #12
0
 public static ImageSource ToImageSource(this string source)
 {
     var bytes = Convert.FromBase64String(source);
     using (var memoryStream = new MemoryStream(bytes))
     {
         var decoder = new PngBitmapDecoder(memoryStream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
         return decoder.Frames.FirstOrDefault();
     }
 }
Example #13
0
 public BitmapToImage(System.Drawing.Bitmap bitmap) : base()
 {
     MemoryStream stream = new MemoryStream();
     bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
     PngBitmapDecoder decoder = new PngBitmapDecoder(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
     BitmapSource destination = decoder.Frames[0];
     destination.Freeze();
     this.Source = destination;
 }
Example #14
0
        public Settings()
        {
            InitializeComponent();

            Assembly a = Assembly.GetExecutingAssembly();
            Stream pngstream = a.GetManifestResourceStream("YAWAMT.SystemTrayClient.save.png");

            PngBitmapDecoder decoder = new PngBitmapDecoder(pngstream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
            image1.Source = decoder.Frames[0];

            //textBox1.Text = YAWAMT.SystemTrayClient.Properties.Settings.Default.Url;
        }
        private static BitmapSource BitmapSourceFromImage(System.Drawing.Image img)
        {
            MemoryStream memStream = new MemoryStream();

            // save the image to memStream as a png
            img.Save(memStream, System.Drawing.Imaging.ImageFormat.Png);

            // gets a decoder from this stream
            System.Windows.Media.Imaging.PngBitmapDecoder decoder = new System.Windows.Media.Imaging.PngBitmapDecoder(memStream, System.Windows.Media.Imaging.BitmapCreateOptions.PreservePixelFormat, System.Windows.Media.Imaging.BitmapCacheOption.Default);

            return(decoder.Frames[0]);
        }
Example #16
0
		private static BitmapFrame ConvertFromIcon(Icon icon)
		{
			var iconStream = new MemoryStream();

			using (var bmp = icon.ToBitmap())
			{
				bmp.Save(iconStream, ImageFormat.Png);
			}

			iconStream.Position = 0;
			var decoder = new PngBitmapDecoder(iconStream, BitmapCreateOptions.None, BitmapCacheOption.None);
			return decoder.Frames.Last();
		}
Example #17
0
		private void SetIcon()
		{
			try
			{
				Uri myUri = new Uri("pack://application:,,,/" + GetType().Assembly.GetName().Name + ";component/Scutex.png",
														UriKind.RelativeOrAbsolute);
				PngBitmapDecoder decoder = new PngBitmapDecoder(myUri, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
				BitmapSource bitmapSource = decoder.Frames[0];
				imageIcon.Source = bitmapSource;
			}
			catch
			{ }
		}
        public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            var isChecked = (bool)values[0];
              var imageBase = (String)values[1];

              String imagePath = String.Format("Images/{0}.png", imageBase);
              if(isChecked)
            imagePath = String.Format("Images/{0}Selected.png", imageBase);

              FileStream pngStream = new FileStream(imagePath, FileMode.Open, FileAccess.Read);
              PngBitmapDecoder pngDecoder = new PngBitmapDecoder(pngStream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
              BitmapFrame pngFrame = pngDecoder.Frames[0];
              return pngFrame;
        }
Example #19
0
        private void CreateAndShowMainWindow()
        {
            // Create the application's main window
            _mainWindow = new Window {Title = "Image Metadata"};

            Stream pngStream = new FileStream("smiley.png", FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
            var pngDecoder = new PngBitmapDecoder(pngStream, BitmapCreateOptions.PreservePixelFormat,
                BitmapCacheOption.Default);
            var pngFrame = pngDecoder.Frames[0];
            var pngInplace = pngFrame.CreateInPlaceBitmapMetadataWriter();
            if (pngInplace.TrySave())
            {
                pngInplace.SetQuery("/Text/Description", "Have a nice day.");
            }
            pngStream.Close();

            // Draw the Image
            var myImage = new Image
            {
                Source = new BitmapImage(new Uri("smiley.png", UriKind.Relative)),
                Stretch = Stretch.None,
                Margin = new Thickness(20)
            };


            // Add the metadata of the bitmap image to the text block.
            var myTextBlock = new TextBlock
            {
                Text =
                    "The Description metadata of this image is: " + pngInplace.GetQuery("/Text/Description")
            };

            // Define a StackPanel to host Controls
            var myStackPanel = new StackPanel
            {
                Orientation = Orientation.Vertical,
                Height = 200,
                VerticalAlignment = VerticalAlignment.Top,
                HorizontalAlignment = HorizontalAlignment.Center
            };

            // Add the Image and TextBlock to the parent Grid
            myStackPanel.Children.Add(myImage);
            myStackPanel.Children.Add(myTextBlock);

            // Add the StackPanel as the Content of the Parent Window Object
            _mainWindow.Content = myStackPanel;
            _mainWindow.Show();
        }
Example #20
0
        public static ImageSource GetIcon(string name)
        {
            Uri uriSource = new Uri(string.Format("/Miiror;component/Resources/{0}.png", name.Trim().ToLower()), UriKind.RelativeOrAbsolute);
            StreamResourceInfo sri = Application.GetResourceStream(uriSource);
            ImageSource icon = null;

            PngBitmapDecoder decoder;

            decoder = new PngBitmapDecoder(sri.Stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.None);

            if (decoder.Frames != null && decoder.Frames.Count > 0)
                icon = decoder.Frames[0];

            return icon;
        }
Example #21
0
 public static void Charge(byte[] payload, string sourcePath, string destPath)
 {
     using (var sourceFile = new FileStream(sourcePath, FileMode.Open))
     using (var destFile = new FileStream(destPath, FileMode.Create))
     {
         var decoder = new PngBitmapDecoder(sourceFile,
             BitmapCreateOptions.PreservePixelFormat,
             BitmapCacheOption.Default);
         BitmapSource sourceBitmap = decoder.Frames[0];
         BitmapSource result = Charge(payload, sourceBitmap);
         var encoder = new PngBitmapEncoder();
         encoder.Frames.Add(BitmapFrame.Create(result));
         encoder.Save(destFile);
     }
 }
Example #22
0
 LoadPNGImageFromResource(string imageResourceName)
 {
     System.Reflection.Assembly dotNetAssembly =
         System.Reflection.Assembly.GetExecutingAssembly();
     System.IO.Stream iconStream =
         dotNetAssembly.GetManifestResourceStream(imageResourceName);
     System.Windows.Media.Imaging.PngBitmapDecoder bitmapDecoder =
         new System.Windows.Media.Imaging.PngBitmapDecoder(iconStream,
                                                           System.Windows.Media.Imaging.BitmapCreateOptions.
                                                           PreservePixelFormat, System.Windows.Media.Imaging.
                                                           BitmapCacheOption.Default);
     System.Windows.Media.ImageSource imageSource =
         bitmapDecoder.Frames[0];
     return(imageSource);
 }
Example #23
0
        public Notification(Color startcolor, string url, DateTime downtime)
        {
            InitializeComponent();

            this.Background = new LinearGradientBrush(startcolor, Color.FromRgb(0, 0, 0), 90);
            this.Opacity = 0.7;

            label1.Content = url;
            label2.Content = downtime.ToString();

            Assembly a = Assembly.GetExecutingAssembly();
            Stream globe = a.GetManifestResourceStream("YAWAMT.SystemTrayClient.globe.png");

            PngBitmapDecoder decoder = new PngBitmapDecoder(globe, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
            image1.Source = decoder.Frames[0];
        }
Example #24
0
        public MainWindow()
        {
           
            InitializeComponent();
            Stream imageStreamSource = new FileStream("C:/Users/Saideh/Desktop/siri_icon_lg[1].png", FileMode.Open, FileAccess.Read, FileShare.Read);
            PngBitmapDecoder decoder = new PngBitmapDecoder(imageStreamSource, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
            BitmapSource bitmapSource = decoder.Frames[0];
            image1.Source = bitmapSource;
            Style s = new Style();
          // label1.s
            
          
           // Color z = Color.FromArgb(255, 0, 0, 255);
            rectangle1.Fill=new SolidColorBrush(Colors.Black);
            

        }
 private void InitializeImageResources()
 {
     using (var badStream = this.GetType().Assembly.GetManifestResourceStream(icon_resource_bad))
     {
         PngBitmapDecoder bitmapDecoder = new PngBitmapDecoder(badStream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
         BadBMP = bitmapDecoder.Frames[0];
     }
     using (var waitStream = this.GetType().Assembly.GetManifestResourceStream(icon_resource_wait))
     {
         PngBitmapDecoder bitmapDecoder = new PngBitmapDecoder(waitStream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
         WaitBMP = bitmapDecoder.Frames[0];
     }
     using (var goodStream = this.GetType().Assembly.GetManifestResourceStream(icon_resource_good))
     {
         PngBitmapDecoder bitmapDecoder = new PngBitmapDecoder(goodStream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
         GoodBMP = bitmapDecoder.Frames[0];
     }
 }
Example #26
0
        public static void ImportPng(Uri path, InkCanvas Surface)
        {
            if (path == null) return;

            BitmapSource bitmapSource;

            using (Stream imageStreamSource = new FileStream(path.LocalPath, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                PngBitmapDecoder decoder = new PngBitmapDecoder(imageStreamSource, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad);
                bitmapSource = decoder.Frames[0];
            }
           
            // Draw the Image
            var image = new Image();
            image.Source = bitmapSource;
            image.Stretch = Stretch.UniformToFill;
            Surface.Children.Add(image);
        }
		public ImageSource GetPng(string ImageName, int Size)
		{
			ImageSource result = null;
			
			var imgName = Size > 0 
				? String.Format("${SolutionName}.Base.Resource.Images._{0}x{1}.{2}.png",Size, Size, ImageName) 
				: String.Format("${SolutionName}.Base.Resource.Images.Misc.{0}.png", ImageName);

			System.IO.Stream fileStream = this.GetType().Assembly.GetManifestResourceStream(imgName);
			
			if (fileStream != null)
			{
				PngBitmapDecoder bitmapDecoder = new PngBitmapDecoder(fileStream,
					BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
				result = bitmapDecoder.Frames[0];
			}

			return result;
		}
        public TemplateWizardDialog(IEnumerable<Tuple<string, string, string>> projects)
        {
            InitializeComponent();
            lvwProjectType.Items.Clear();

            foreach (var project in projects)
            {
                // Get the project related info
                var displayText = project.Item2;
                var iconFileName = project.Item3.ToLower() == "fsharp" ? "MultiProjectDialog.images.file-icon.png" : "MultiProjectDialog.images.generic-file-icon.png";

                // Build the image
                var iconImage = new Image();
                using (var fileStream = GetType().Assembly.GetManifestResourceStream(iconFileName))
                {
                    var bitmapDecoder = new PngBitmapDecoder(fileStream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
                    var imageSource = bitmapDecoder.Frames[0];
                    iconImage.Source = imageSource;
                }
                Grid.SetRow(iconImage, 0);

                // Build the label
                var label = new Label { Content = displayText, HorizontalAlignment = HorizontalAlignment.Center };
                Grid.SetRow(label, 1);

                // Build the Grid
                var grid = new Grid { Width = 96 };
                var row1 = new RowDefinition();
                var row2 = new RowDefinition();
                grid.RowDefinitions.Add(row1);
                grid.RowDefinitions.Add(row2);

                grid.Children.Add(label);
                grid.Children.Add(iconImage);

                var content = new ContentControl { Content = grid };

                var listItem = new ListViewItem { Content = content };

                lvwProjectType.Items.Add(listItem);
            }
        }
 /// <summary>
 /// Загрузка изображения в массив байт
 /// </summary>
 /// <param name="path">путь к файлу</param>
 /// <returns></returns>
 public static byte[,] LoadImage(string path)
 {
     Uri myUri = new Uri(path, UriKind.RelativeOrAbsolute);
     PngBitmapDecoder decoder = new PngBitmapDecoder(myUri, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
     BitmapSource bs = decoder.Frames[0];
     //Конвертируем изображение в оттенки серого
     FormatConvertedBitmap fcb = new FormatConvertedBitmap(bs, PixelFormats.Gray8, BitmapPalettes.BlackAndWhite, 1);
     bs = fcb;
     byte[] arr = new byte[(int)(bs.Width * bs.Height)];
     //Извлекаем пиксели
     bs.CopyPixels(arr, (int)(8 * bs.Width) / 8, 0);
     int count = 0;
     byte[,] img = new byte[(int)bs.Height, (int)bs.Width];
     //формируем двумерный массив
     for (int i = 0; i < bs.Height; ++i)
     {
         for (int j = 0; j < bs.Width; ++j)
         {
             img[i, j] = arr[count++];
         }
     }
     return img;
 }
Example #30
0
        private ImageSource iconImage(string sourcename)
        {
            try
            {
              Stream icon = Assembly.GetExecutingAssembly().GetManifestResourceStream(sourcename);
              if (icon != null)
              {
            PngBitmapDecoder decoder = new PngBitmapDecoder(
              icon,
              BitmapCreateOptions.PreservePixelFormat,
              BitmapCacheOption.Default);

            ImageSource source = decoder.Frames[0];
            return source;
              }

            }
            catch (Exception ex)
            {
            throw new Exception(ex.Message);
            }
            return null;
        }
Example #31
0
        /// <summary>
        /// 从资源中恢复图像(png、ico、jpeg、bmp)
        /// </summary>
        /// <param name="nomImage"></param>
        /// <returns></returns>
        public static ImageSource ImageSource(string nomImage)
        {
            Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(nomImage);

            if (Path.GetExtension(nomImage).ToLower().EndsWith(".png")) // Cas png
            {
                PngBitmapDecoder img = new System.Windows.Media.Imaging.PngBitmapDecoder(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
                return(img.Frames[0]);
            }

            if (Path.GetExtension(nomImage).ToLower().EndsWith(".bmp")) // Cas bmp
            {
                BmpBitmapDecoder img = new System.Windows.Media.Imaging.BmpBitmapDecoder(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
                return(img.Frames[0]);
            }

            if (Path.GetExtension(nomImage).ToLower().EndsWith(".jpg")) // Cas jpg
            {
                JpegBitmapDecoder img = new System.Windows.Media.Imaging.JpegBitmapDecoder(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
                return(img.Frames[0]);
            }

            if (Path.GetExtension(nomImage).ToLower().EndsWith(".tiff")) // Cas tiff
            {
                TiffBitmapDecoder img = new System.Windows.Media.Imaging.TiffBitmapDecoder(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
                return(img.Frames[0]);
            }

            if (Path.GetExtension(nomImage).ToLower().Contains(".ico")) // Cas  ico
            {
                IconBitmapDecoder img = new System.Windows.Media.Imaging.IconBitmapDecoder(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
                return(img.Frames[0]);
            }

            return(null);
        }
        internal static BitmapSource ToImageSource(string ext, Stream s)
        {
            ext = ext.ToLower();

            if (ext.EndsWith(".png"))
            {
                var bitmapDecoder = new PngBitmapDecoder(s, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.None);
                return bitmapDecoder.Frames[0];
            }

            if (ext.EndsWith(".gif"))
            {
                var bitmapDecoder = new GifBitmapDecoder(s, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.None);
                return bitmapDecoder.Frames[0];
            }

            if (ext.EndsWith(".jpg"))
            {
                var bitmapDecoder = new JpegBitmapDecoder(s, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.None);
                return bitmapDecoder.Frames[0];
            }

            // http://stackoverflow.com/questions/2835502/rotating-cursor-according-to-rotated-textbox
            // http://stackoverflow.com/questions/46805/custom-cursor-in-wpf
            // http://stackoverflow.com/questions/2284353/is-there-a-good-way-to-convert-between-bitmapsource-and-bitmap
            // http://www.gdgsoft.com/anituner/help/aniformat.htm



            // http://msdn.microsoft.com/en-us/library/ms608877.aspx
            throw new NotSupportedException(ext);
        }
        private BitmapSource BitmapSourceFromImage(System.Drawing.Image img)
        {

            if (img != null)
            {

                System.IO.MemoryStream memStream = new System.IO.MemoryStream();

                //save the image to memStream as a png
                img.Save(memStream, System.Drawing.Imaging.ImageFormat.Png);

                //gets a decoder from this stream
                System.Windows.Media.Imaging.PngBitmapDecoder decoder = new System.Windows.Media.Imaging.PngBitmapDecoder(memStream, System.Windows.Media.Imaging.BitmapCreateOptions.PreservePixelFormat, System.Windows.Media.Imaging.BitmapCacheOption.Default);

                return decoder.Frames[0];
            }
            else
                return null;
        }
Example #34
0
        /// <summary>
        /// WriteableBitmap (Format = Bgr32) -> IplImage
        /// </summary>
        private void TestWriteableBitmapBgr32()
        {
            // loads color image
            PngBitmapDecoder decoder = new PngBitmapDecoder(
                new Uri(FilePath.Image.Lenna, UriKind.Relative),
                BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default
            );
            BitmapSource bs = decoder.Frames[0];

            // converts pixelformat from Bgr24 to Bgr32 (for this test)
            FormatConvertedBitmap fcb = new FormatConvertedBitmap();
            fcb.BeginInit();
            fcb.Source = bs;
            fcb.DestinationFormat = PixelFormats.Gray8;
            fcb.EndInit();

            // creates WriteableBitmap
            WriteableBitmap wb = new WriteableBitmap(fcb);

            // shows wb 
            /*
            var image = new System.Windows.Controls.Image { Source = wb };
            var window = new System.Windows.Window
            {
                Title = string.Format("wb (Format:{0})", wb.Format),
                Width = wb.PixelWidth,
                Height = wb.PixelHeight,
                Content = image
            };
            var app = new System.Windows.Application();
            app.Run(window);
            //*/

            // convert wb into IplImage
            IplImage ipl = wb.ToIplImage();
            //IplImage ipl32 = new IplImage(wb.PixelWidth, wb.PixelHeight, BitDepth.U16, 1);
            //WriteableBitmapConverter.ToIplImage(wb, ipl32);

            using (new CvWindow("from WriteableBitmap(Bgr32) to IplImage", ipl))
            {
                Cv.WaitKey();
            }
        }
Example #35
0
        public override ImageData Read(Stream stream, ImageMetaData info)
        {
            var meta = info as BipMetaData;
            if (null == meta)
                throw new ArgumentException ("BipFormat.Read should be supplied with BipMetaData", "info");

            var header = new byte[0x7c];
            var bitmap = new WriteableBitmap ((int)meta.Width, (int)meta.Height,
                    ImageData.DefaultDpiX, ImageData.DefaultDpiY, PixelFormats.Bgra32, null);
            foreach (var tile in meta.Tiles)
            {
                stream.Position = tile.Offset;
                if (header.Length != stream.Read (header, 0, header.Length))
                    throw new InvalidFormatException ("Invalid tile header");
                if (!Binary.AsciiEqual (header, "PNGFILE2"))
                    throw new InvalidFormatException ("Unknown tile format");
                int data_size = LittleEndian.ToInt32 (header, 0x18) - header.Length;
                int alpha = LittleEndian.ToInt32 (header, 0x68);
                int x = LittleEndian.ToInt32 (header, 0x6c);
                int y = LittleEndian.ToInt32 (header, 0x70);
                using (var png = new StreamRegion (stream, stream.Position, data_size, true))
                {
                    var decoder = new PngBitmapDecoder (png,
                        BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
                    BitmapSource frame = decoder.Frames[0];
                    PixelFormat format = 0 == alpha ? PixelFormats.Bgr32 : PixelFormats.Bgra32;
                    var converted = new FormatConvertedBitmap (frame, format, null, 0);
                    int stride = converted.PixelWidth * 4;
                    var pixels = new byte[stride * converted.PixelHeight];
                    converted.CopyPixels (pixels, stride, 0);
                    for (int p = 0; p < pixels.Length; p += 4)
                    {
                        byte r = pixels[p];
                        pixels[p] = pixels[p+2];
                        pixels[p+2] = r;
                        int a = 0 == alpha ? 0xff : pixels[p+3] * 0xff / 0x80;
                        if (a > 0xff) a = 0xff;
                        pixels[p+3] = (byte)a;
                    }
                    var rect = new Int32Rect (tile.Left+x, tile.Top+y, converted.PixelWidth, converted.PixelHeight);
                    bitmap.WritePixels (rect, pixels, stride, 0);
                }
            }
            bitmap.Freeze();
            return new ImageData (bitmap, meta);
        }