static void Main(string[] args)
        {
            ResourceWriter myResource = new ResourceWriter("Images.resources");
            myResource.AddResource("flash", new Bitmap("flashScreen.png"));
            Image simpleImage = new Image();
            simpleImage.Margin = new Thickness(0);

            BitmapImage bi = new BitmapImage();
            //BitmapImage.UriSource must be in a BeginInit/EndInit block
            bi.BeginInit();





            bi.UriSource = new Uri(@"pack://siteoforigin:,,,/alarm3.png");
            bi.EndInit();
            //set image source
            simpleImage.Source = bi;
            //        simpleImage.Stretch = Stretch.None;
            simpleImage.HorizontalAlignment = HorizontalAlignment.Center;
            simpleImage.Visibility = Visibility.Hidden;
            simpleImage.Name = "AlarmIndicator";
            simpleImage.Width = 13;


            myResource.AddResource("alarm", new Image("alarm3.png"));
            myResource.Close(); 


        }
Пример #2
0
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value == null)
            return null;

            if (!string.IsNullOrEmpty(value.ToString()))
            {
            BitmapImage bi = new BitmapImage();
            bi.BeginInit();
            bi.UriSource = new Uri(value.ToString());
            bi.CacheOption = BitmapCacheOption.OnLoad;
            bi.EndInit();
            return bi;
            }

            return null;
        }
Пример #3
0
 private static BitmapImage LoadImage(byte[] imageData)
 {
     if (imageData == null || imageData.Length == 0) return null;
     var image = new BitmapImage();
     using (var mem = new MemoryStream(imageData))
     {
         mem.Position = 0;
         image.BeginInit();
         image.CreateOptions = BitmapCreateOptions.PreservePixelFormat;
         image.CacheOption = BitmapCacheOption.OnLoad;
         image.UriSource = null;
         image.StreamSource = mem;
         image.EndInit();
     }
     image.Freeze();
     return image;
 }
Пример #4
0
 public static IObservable<BitmapImage> BytesToImage(byte[] compressedImage)
 {
     try
     {
         var ret = new BitmapImage();
     #if SILVERLIGHT
         ret.SetSource(new MemoryStream(compressedImage));
     #else
         ret.BeginInit();
         ret.StreamSource = new MemoryStream(compressedImage);
         ret.EndInit();
         ret.Freeze();
     #endif
         return Observable.Return(ret);
     }
     catch (Exception ex)
     {
         return Observable.Throw<BitmapImage>(ex);
     }
 }
Пример #5
0
        // We could use this piece of code to also download the thumb
        // if we had WPF. But we don't.
        private void LoadThumbnail(Uri url)
        {
            try
            {
                    WebClient wc = new WebClient();
                    byte[] bytes = wc.DownloadData(url);

                    MemoryStream stream = new MemoryStream(bytes);
                    BitmapImage image = new BitmapImage();
                    image.BeginInit();
                    image.StreamSource = stream;
                    image.EndInit();
                    //set thumbnail
                    Thumbnail = image;
            }
            catch
            {
                BitmapImage image = new BitmapImage();
                image.BeginInit();
                image.UriSource = new Uri("youtube_logo.png", UriKind.Relative);
                image.EndInit();
                Thumbnail = image;
            }
        }
Пример #6
0
 /// <summary>
 /// Saves the cropped image area to a temp file, and shows a confirmation
 /// popup from where the user may accept or reject the cropped image.
 /// If they accept the new cropped image will be used as the new image source
 /// for the current canvas, if they reject the crop, the existing image will
 /// be used for the current canvas
 /// </summary>
 public BitmapImage SaveCroppedImage()
 {
     if (popUpImage.Source != null)
     {
         popUpImage.Source = null;
     }
     try
     {
         rubberBandLeft = Canvas.GetLeft(rubberBand);
         rubberBandTop  = Canvas.GetTop(rubberBand);
         //create a new .NET 2.0 bitmap (which allowing saving) based on the bound bitmap url
         using (System.Drawing.Bitmap source = new System.Drawing.Bitmap(ImgUrl))
         {
             //create a new .NET 2.0 bitmap (which allowing saving) to store cropped image in, should be
             //same size as rubberBand element which is the size of the area of the original image we want to keep
             using (System.Drawing.Bitmap target = new System.Drawing.Bitmap((int)rubberBand.Width, (int)rubberBand.Height))
             {
                 //create a new destination rectange
                 System.Drawing.RectangleF recDest = new System.Drawing.RectangleF(0.0f, 0.0f, (float)target.Width, (float)target.Height);
                 //different resolution fix prior to cropping image
                 float hd     = 1.0f / (target.HorizontalResolution / source.HorizontalResolution);
                 float vd     = 1.0f / (target.VerticalResolution / source.VerticalResolution);
                 float hScale = 1.0f / (float)zoomFactor;
                 float vScale = 1.0f / (float)zoomFactor;
                 System.Drawing.RectangleF recSrc = new System.Drawing.RectangleF((hd * (float)rubberBandLeft) * hScale, (vd * (float)rubberBandTop) * vScale, (hd * (float)rubberBand.Width) * hScale, (vd * (float)rubberBand.Height) * vScale);
                 using (System.Drawing.Graphics gfx = System.Drawing.Graphics.FromImage(target))
                 {
                     gfx.DrawImage(source, recDest, recSrc, System.Drawing.GraphicsUnit.Pixel);
                 }
                 //create a new temporary file, and delete all old ones prior to this new temp file
                 //This is is a hack that I had to put in, due to GDI+ holding on to previous
                 //file handles used by the Bitmap.Save() method the last time this method was run.
                 //This is a well known issue see http://support.microsoft.com/?id=814675 for example
                 tempFileName = System.IO.Path.GetTempPath();
                 if (fixedTempIdx > 2)
                 {
                     fixedTempIdx = 0;
                 }
                 else
                 {
                     ++fixedTempIdx;
                 }
                 //do the clean
                 CleanUp(tempFileName, fixedTempName, fixedTempIdx);
                 //Due to the so problem above, which believe you me I have tried and tried to resolve
                 //I have tried the following to fix this, incase anyone wants to try it
                 //1. Tried reading the image as a strea of bytes into a new bitmap image
                 //2. I have tried to use teh WPF BitmapImage.Create()
                 //3. I have used the trick where you use a 2nd Bitmap (GDI+) to be the newly saved
                 //   image
                 //
                 //None of these worked so I was forced into using a few temp files, and pointing the
                 //cropped image to the last one, and makeing sure all others were deleted.
                 //Not ideal, so if anyone can fix it please this I would love to know. So let me know
                 tempFileName = tempFileName + fixedTempName + fixedTempIdx.ToString() + ".jpg";
                 target.Save(tempFileName, System.Drawing.Imaging.ImageFormat.Jpeg);
                 //rewire up context menu
                 cmDragCanvas.RemoveHandler(MenuItem.ClickEvent, cmDragCanvasRoutedEventHandler);
                 dragCanvasForImg.ContextMenu = null;
                 cmDragCanvas = null;
                 //create popup BitmapImage
                 bmpPopup = new BitmapImage();
                 bmpPopup.BeginInit();
                 bmpPopup.StreamSource = File.OpenRead(tempFileName);
                 bmpPopup.EndInit();
                 popUpImage.Source = bmpPopup;
                 return(bmpPopup);
             }
         }
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message);
         return(null);
     }
 }
        public Control_DefaultKeycapBackglow(KeyboardKey key, string image_path)
        {
            InitializeComponent();

            associatedKey = key.tag;

            this.Width  = key.width.Value;
            this.Height = key.height.Value;

            //Keycap adjustments
            if (string.IsNullOrWhiteSpace(key.image))
            {
                keyBorder.BorderThickness = new Thickness(1.5);
            }
            else
            {
                keyBorder.BorderThickness = new Thickness(0.0);
            }
            keyBorder.IsEnabled = key.enabled.Value;

            if (!key.enabled.Value)
            {
                ToolTipService.SetShowOnDisabled(keyBorder, true);
                keyBorder.ToolTip = new ToolTip {
                    Content = "Changes to this key are not supported"
                };
            }

            if (string.IsNullOrWhiteSpace(key.image))
            {
                keyCap.Text       = key.visualName;
                keyCap.Tag        = key.tag;
                keyCap.FontSize   = key.font_size.Value;
                keyCap.Visibility = System.Windows.Visibility.Visible;
            }
            else
            {
                keyCap.Visibility        = System.Windows.Visibility.Hidden;
                grid_backglow.Visibility = Visibility.Hidden;

                if (System.IO.File.Exists(image_path))
                {
                    var         memStream = new System.IO.MemoryStream(System.IO.File.ReadAllBytes(image_path));
                    BitmapImage image     = new BitmapImage();
                    image.BeginInit();
                    image.StreamSource = memStream;
                    image.EndInit();

                    if (key.tag == DeviceKeys.NONE)
                    {
                        keyBorder.Background = new ImageBrush(image);
                    }
                    else
                    {
                        keyBorder.Background  = new SolidColorBrush(System.Windows.Media.Color.FromArgb(255, 0, 0, 0));
                        keyBorder.OpacityMask = new ImageBrush(image);
                    }

                    isImage = true;
                }
            }
        }
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {


            #region Data loading on my tables
            ///
            /// Load Data for loading into Clickedbase 
            ///
            Load1.Text = Convert.ToString(Rate1.Content);
            Load2.Text = Convert.ToString(Rate2.Content);
            Load3.Text = Convert.ToString(Rate3.Content);
            Load4.Text = Convert.ToString(Rate4.Content);
            #endregion



            #region Loading Images into Rectange

            SqlConnection con1 = new SqlConnection(PublicVar.ConnectionString);
            con1.Open();

            ShowUserInfo(searchstate);
            string Finder = Rate1.Content + " , " + Rate2.Content + " , " + Rate3.Content + " , " + Rate4.Content;

            SqlCommand Commandcmd = new SqlCommand(
                "SELECT (MorabiImage) FROM MorabiTable where MorabiID = " + Load1.Text, con1);
            SqlDataReader rdr1 = null;
            rdr1 = Commandcmd.ExecuteReader();
            while (rdr1.Read())
            {
                if (rdr1 != null)
                {
                    byte[] data = (byte[])rdr1[0]; // 0 is okay if you only selecting one column
                    //And use:
                    using (System.IO.MemoryStream ms = new System.IO.MemoryStream(data))
                    {
                        var imageSource = new BitmapImage();
                        imageSource.BeginInit();
                        imageSource.StreamSource = ms;
                        imageSource.CacheOption = BitmapCacheOption.OnLoad;
                        imageSource.EndInit();

                        // Assign the Source property of your image
                        //  MyImage.Source = imageSource;
                        Image1.Fill = new ImageBrush
                        {
                            ImageSource = imageSource
                        };
                    }

                }
                SqlCommand Rect2 = new SqlCommand(
               "SELECT (MorabiImage) FROM MorabiTable where MorabiID = " + Load2.Text, con1);
                SqlDataReader rdr11 = null;
                rdr11 = Rect2.ExecuteReader();
                while (rdr11.Read())
                {
                    if (rdr11 != null)
                    {
                        byte[] data = (byte[])rdr1[0]; // 0 is okay if you only selecting one column
                                                       //And use:
                        using (System.IO.MemoryStream ms = new System.IO.MemoryStream(data))
                        {
                            var imageSource = new BitmapImage();
                            imageSource.BeginInit();
                            imageSource.StreamSource = ms;
                            imageSource.CacheOption = BitmapCacheOption.OnLoad;
                            imageSource.EndInit();

                            // Assign the Source property of your image
                            //  MyImage.Source = imageSource;
                            Image2.Fill = new ImageBrush
                            {
                                ImageSource = imageSource
                            };
                        }

                    }
                    SqlCommand Rect3 = new SqlCommand(
               "SELECT (MorabiImage) FROM MorabiTable where MorabiID = " + Load3.Text, con1);
                    SqlDataReader rdr3 = null;
                    rdr3 = Rect3.ExecuteReader();
                    while (rdr3.Read())
                    {
                        if (rdr1 != null)
                        {
                            byte[] data = (byte[])rdr3[0]; // 0 is okay if you only selecting one column
                                                           //And use:
                            using (System.IO.MemoryStream ms = new System.IO.MemoryStream(data))
                            {
                                var imageSource = new BitmapImage();
                                imageSource.BeginInit();
                                imageSource.StreamSource = ms;
                                imageSource.CacheOption = BitmapCacheOption.OnLoad;
                                imageSource.EndInit();

                                // Assign the Source property of your image
                                //  MyImage.Source = imageSource;
                                Image3.Fill = new ImageBrush
                                {
                                    ImageSource = imageSource
                                };
                            }

                        }
                        SqlCommand Rect4 = new SqlCommand(
               "SELECT (MorabiImage) FROM MorabiTable where MorabiID = " + Load4.Text, con1);
                        SqlDataReader rdr4 = null;
                        rdr4 = Rect4.ExecuteReader();
                        while (rdr4.Read())
                        {
                            if (rdr4 != null)
                            {
                                byte[] data = (byte[])rdr4[0]; // 0 is okay if you only selecting one column
                                                               //And use:
                                using (System.IO.MemoryStream ms = new System.IO.MemoryStream(data))
                                {
                                    var imageSource = new BitmapImage();
                                    imageSource.BeginInit();
                                    imageSource.StreamSource = ms;
                                    imageSource.CacheOption = BitmapCacheOption.OnLoad;
                                    imageSource.EndInit();

                                    // Assign the Source property of your image
                                    //  MyImage.Source = imageSource;
                                    Image4.Fill = new ImageBrush
                                    {
                                        ImageSource = imageSource
                                    };
                                }

                            }
                        }
                    }
                }
            }
            if (DataGrid_User.SelectedItem != null)
            {
                var itemOne = DataGrid_User.SelectedItem;

            }
            #endregion



        }
Пример #9
0
        public static void LoadImagesToImageView(string path)
        {
            CurrentPath = path;

            //var files = Directory.GetFiles(path, "*.jpg");

            string[] fnsjpg = Directory.GetFiles(path, "*.jpg");
            // string[] fnswmv = Directory.GetFiles(path, "*.wmv");
            string[] fnswmv = Directory.GetFiles(path, "*.mp4");

            string[] fnsmp4 = Directory.GetFiles(path, "*.wmv");

            List <string> fns = fnsjpg.Union(fnswmv).Union(fnsmp4).ToList <string>();

            StonesRepository rep = new StonesRepository(CurrentPath);


            switch (_sortproperty)
            {
            case 1:
                if (_sortpropertydirection == 1)
                {
                    fns = fns.OrderBy(m => new FileInfo(m).Name).ToList <string>();
                }
                else
                {
                    fns = fns.OrderByDescending(m => new FileInfo(m).Name).ToList <string>();
                }

                break;

            case 2:
                if (_sortpropertydirection == 1)
                {
                    fns = fns.OrderBy(m => new FileInfo(m).LastWriteTime).ToList();
                }
                else
                {
                    fns = fns.OrderByDescending(m => new FileInfo(m).LastWriteTime).ToList <string>();
                }

                break;

            case 3:
                if (_sortpropertydirection == 1)
                {
                    fns = fns.OrderBy(m => new FileInfo(m).Extension).ToList <string>();
                }
                else
                {
                    fns = fns.OrderByDescending(m => new FileInfo(m).Extension).ToList <string>();
                }

                break;

            case 4:
                if (_sortpropertydirection == 1)
                {
                    fns = fns.OrderBy(m => new FileInfo(m).Length).ToList <string>();
                }
                else
                {
                    fns = fns.OrderByDescending(m => new FileInfo(m).Length).ToList <string>();
                }

                break;

            case 5:
                List <string> fns_withdata    = fns.Where(m => rep.LoadStoneByFilenameInCurrentFolder(Path.GetFileName(m)) != null).ToList <string>();
                List <string> fns_withoutdata = fns.Where(m => rep.LoadStoneByFilenameInCurrentFolder(Path.GetFileName(m)) == null).ToList <string>();
                if (_sortpropertydirection == 1)
                {
                    fns_withdata = fns_withdata.OrderBy(m => rep.LoadStoneByFilenameInCurrentFolder(Path.GetFileName(m)).GetInfoByTitle("CaratWeight")).ToList <string>();
                }
                else
                {
                    fns_withdata = fns_withdata.OrderByDescending(m => rep.LoadStoneByFilenameInCurrentFolder(Path.GetFileName(m)).GetInfoByTitle("CaratWeight")).ToList <string>();
                }

                fns = fns_withdata.Union(fns_withoutdata).ToList <string>();

                break;

            default:
                break;
            }



            ViewControl.Items.Clear();

            foreach (var file in fns)
            {
                StackPanel stack = new StackPanel();

                Image img = new Image();

                MemoryStream ms  = new MemoryStream();
                BitmapImage  src = new BitmapImage();

                if (Path.GetExtension(file) == ".jpg")
                {
                    FileStream stream = new FileStream(file, FileMode.Open, FileAccess.Read);
                    ms.SetLength(stream.Length);
                    stream.Read(ms.GetBuffer(), 0, (int)stream.Length);

                    ms.Flush();
                    stream.Close();



                    src.BeginInit();
                    src.StreamSource = ms;
                    src.EndInit();
                    img.Source = src;
                }
                else if (Path.GetExtension(file) == ".mp4" || Path.GetExtension(file) == ".wmv")
                {
                    //MediaPlayer mp = new MediaPlayer();
                    //mp.ScrubbingEnabled = true;
                    //mp.Open(new Uri(file,UriKind.Absolute));
                    //mp.Play();
                    //mp.MediaOpened += new EventHandler(mp_MediaOpened);
                    //mp.Position = new TimeSpan(0, 0, 2);
                    //RenderTargetBitmap rtb = new RenderTargetBitmap(640, 480, 1/200, 1/200, PixelFormats.Default);
                    //DrawingVisual dv = new DrawingVisual();
                    //DrawingContext dc = dv.RenderOpen();
                    //dc.DrawVideo(mp, new Rect(0, 0, 640, 480));
                    //dc.Close();
                    //rtb.Render(dv);
                    //img.Source = BitmapFrame.Create(rtb);
                    //mp.Stop();
                    //mp.Close();

                    //MediaPlayer _mediaPlayer = new MediaPlayer();
                    //_mediaPlayer.ScrubbingEnabled = true;
                    //_mediaPlayer.Open(new Uri(file, UriKind.Absolute));
                    //uint[] framePixels;
                    //uint[] previousFramePixels;

                    //framePixels = new uint[640 * 480];
                    //previousFramePixels = new uint[framePixels.Length];

                    //var drawingVisual = new DrawingVisual();
                    //var renderTargetBitmap = new RenderTargetBitmap(640, 480, 96, 96, PixelFormats.Default);
                    //using (var drawingContext = drawingVisual.RenderOpen())
                    //{
                    //    drawingContext.DrawVideo(_mediaPlayer, new Rect(0, 0, 640, 480));
                    //}
                    //renderTargetBitmap.Render(drawingVisual);

                    //// Copy the pixels to the specified location
                    //renderTargetBitmap.CopyPixels(previousFramePixels, 640 * 4, 0);

                    src.BeginInit();
                    src.UriSource = new Uri(@"/GemScopeWPF;component/Media/movieplaceholder.jpg", UriKind.RelativeOrAbsolute);
                    src.EndInit();

                    img.Source = src;
                }



                double[] wh = new double[] { 100, 100 };



                img.Width = wh[0];
                // img.Height = wh[1];


                img.Margin = new Thickness(5);



                TextBlock blk1 = new TextBlock();
                if (Path.GetFileNameWithoutExtension(file).Length > 20)
                {
                    blk1.Text = Path.GetFileNameWithoutExtension(file).Substring(0, 17) + "...";
                }
                else
                {
                    blk1.Text = Path.GetFileNameWithoutExtension(file);
                }

                blk1.Margin        = new Thickness(2, 0, 0, 0);
                blk1.TextAlignment = TextAlignment.Center;
                stack.Children.Add(img);
                stack.Children.Add(blk1);

                stack.Tag = Path.GetFileName(file);



                //   stack.VerticalAlignment = VerticalAlignment.Top;
                //  stack.HorizontalAlignment = HorizontalAlignment.Left;

                // stack.Width = wh[0]+10;
                //  stack.Height = wh[1] + 10;


                stack.MouseDown += new System.Windows.Input.MouseButtonEventHandler(stack_MouseDown);

                stack.MouseRightButtonDown += new MouseButtonEventHandler(stack_MouseRightButtonDown);


                ViewControl.Items.Add(stack);
            }
        }
Пример #10
0
        private static BitmapSource LoadImage(string fileName, string extension, int size, bool forceSize = false)
        {
            switch (extension)
            {
            case ".ico":
                return(IconDecoder(fileName, size).Shrink(new System.Windows.Size(size, size)));

            default:
            {
                Uri uri = new Uri(fileName, UriKind.Absolute);

                int?decodePixelWidth  = null;
                int?decodePixelHeight = null;

                if (!forceSize)
                {
                    // Get the size of the original image.
                    BitmapFrame bitmapFrame = BitmapFrame.Create(uri,
                                                                 BitmapCreateOptions.DelayCreation, BitmapCacheOption.None);
                    double pw = bitmapFrame.PixelWidth;
                    double ph = bitmapFrame.PixelHeight;

                    if (pw > ph)
                    {
                        decodePixelWidth = (int)Math.Min(size * bitmapFrame.DpiX / 96, pw);
                    }
                    else
                    {
                        decodePixelHeight = (int)Math.Min(size * bitmapFrame.DpiY / 96, ph);
                    }
                }

                // Load the thumbnail.
                BitmapImage img = new BitmapImage();
                img.CacheOption = BitmapCacheOption.Default;

                img.BeginInit();

                if (!forceSize)
                {
                    if (decodePixelWidth != null)
                    {
                        img.DecodePixelWidth = decodePixelWidth.Value;
                    }
                    else
                    {
                        img.DecodePixelHeight = decodePixelHeight.Value;
                    }
                }
                else
                {
                    img.DecodePixelWidth = img.DecodePixelHeight = size;
                }

                img.UriSource = uri;
                img.EndInit();

                return(img);
            }
            }
        }
Пример #11
0
        public CSprites()
        {
            Bitmap.Add("Player_0", new List <BitmapImage>());
            Bitmap.Add("Player_1", new List <BitmapImage>());
            Bitmap.Add("Player_2", new List <BitmapImage>());
            Bitmap.Add("Player_3", new List <BitmapImage>());
            Bitmap.Add("PlayerDied", new List <BitmapImage>());
            Bitmap.Add("Brick", new List <BitmapImage>());
            Bitmap.Add("Bomb", new List <BitmapImage>());
            Bitmap.Add("FireDown", new List <BitmapImage>());
            Bitmap.Add("FireLeft", new List <BitmapImage>());
            Bitmap.Add("FireUp", new List <BitmapImage>());
            Bitmap.Add("FireRight", new List <BitmapImage>());
            Bitmap.Add("FireVertical", new List <BitmapImage>());
            Bitmap.Add("FireHorizontal", new List <BitmapImage>());
            Bitmap.Add("FireCentre", new List <BitmapImage>());
            int x = 1, y = 1;

            LoadImage(Bitmap["Player_0"], 3, ref x, ref y);
            LoadImage(Bitmap["Player_1"], 3, ref x, ref y);
            LoadImage(Bitmap["Player_2"], 3, ref x, ref y);
            LoadImage(Bitmap["Player_3"], 3, ref x, ref y);
            x = 117; y = 1;
            LoadImage(Bitmap["PlayerDied"], 6, ref x, ref y);
            x = 81; y = 313;
            LoadImage(Bitmap["Brick"], 7, ref x, ref y);
            x = 117; y = 41;
            LoadImage(Bitmap["Bomb"], 3, ref x, ref y);
            x = 233; y = 41;
            LoadImage(Bitmap["FireUp"], 4, ref x, ref y);
            x = 233; y = 79;
            LoadImage(Bitmap["FireVertical"], 4, ref x, ref y);
            x = 233; y = 117;
            LoadImage(Bitmap["FireDown"], 4, ref x, ref y);
            x = 233; y = 157;
            LoadImage(Bitmap["FireLeft"], 4, ref x, ref y);
            x = 233; y = 195;
            LoadImage(Bitmap["FireHorizontal"], 4, ref x, ref y);
            x = 233; y = 233;
            LoadImage(Bitmap["FireRight"], 4, ref x, ref y);
            x = 233; y = 273;
            LoadImage(Bitmap["FireCentre"], 4, ref x, ref y);
            Bitmap.Add("Enemy_0", new List <BitmapImage>());
            Bitmap.Add("Enemy_1", new List <BitmapImage>());
            Bitmap.Add("Enemy_2", new List <BitmapImage>());
            Bitmap.Add("Enemy_3", new List <BitmapImage>());
            Bitmap.Add("EnemyDied", new List <BitmapImage>());
            x = 1; y = 156;
            LoadImage(Bitmap["Enemy_0"], 3, ref x, ref y);
            LoadImage(Bitmap["Enemy_1"], 3, ref x, ref y);
            LoadImage(Bitmap["Enemy_2"], 3, ref x, ref y);
            LoadImage(Bitmap["Enemy_3"], 3, ref x, ref y);
            x = 0; y = 362;
            LoadImage(Bitmap["EnemyDied"], 6, ref x, ref y);
            EMPTY.BeginInit();
            EMPTY.UriSource  = new Uri(path, UriKind.RelativeOrAbsolute);
            EMPTY.SourceRect = new Int32Rect(0, 0, 1, 1);
            EMPTY.EndInit();

            /*string str = "";
             * FileInfo[] files = new DirectoryInfo(path).GetFiles();
             * for (int i = 0; i < files.Length; i++)
             * {
             *  FileInfo f = files[i];
             *  str += String.Format("{0} {1} ", f.Name, Environment.NewLine);
             * }
             * str += File.Exists(path);
             * MessageBox.Show(str);*/
        }
Пример #12
0
        public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
        {
            int    id     = (int)values[0];
            string iconId = (string)values[1];

            if ((id == 0) || string.IsNullOrWhiteSpace(iconId))
            {
                return(Binding.DoNothing);
            }
            string timePeriod = iconId.Substring(2, 1);
            string img        = "";

            if (id >= 200 && id < 300)
            {
                img = "thunderstorm.png";
            }
            else if (id >= 300 && id < 500)
            {
                img = "drizzle.png";
            }
            else if (id >= 500 && id < 600)
            {
                img = "rain.png";
            }
            else if (id >= 600 && id < 700)
            {
                img = "snow.png";
            }
            else if (id >= 700 && id < 800)
            {
                img = "atmosphere.png";
            }
            else if (id == 800)
            {
                img = (timePeriod == "d") ? "clear_day.png" : "clear_night.png";
            }
            else if (id == 801)
            {
                img = (timePeriod == "d") ? "few_clouds_day.png" : "few_clouds_night.png";
            }
            else if (id == 802 || id == 803)
            {
                img = (timePeriod == "d") ? "broken_clouds_day.png" : "broken_clouds_night.png";
            }
            else if (id == 804)
            {
                img = "overcast_clouds.png";
            }
            else if (id >= 900 && id < 903)
            {
                img = "extreme.png";
            }
            else if (id == 903)
            {
                img = "cold.png";
            }
            else if (id == 904)
            {
                img = "hot.png";
            }
            else if (id == 905 || id >= 951)
            {
                img = "windy.png";
            }
            else if (id == 906)
            {
                img = "hail.png";
            }

            BitmapImage immagine = new BitmapImage();

            immagine.BeginInit();

            immagine.UriSource = new Uri("/Images/" + img, UriKind.RelativeOrAbsolute);

            immagine.EndInit();
            return(immagine);
        }
Пример #13
0
        /// <summary>
        /// Converts IconUrl from PackageItemListViewModel to an image represented by a BitmapSource
        /// </summary>
        /// <param name="values">An array of two elements containing the IconUri and a generator function of PackageReaderBase objects</param>
        /// <param name="targetType">unused</param>
        /// <param name="parameter">A BitmapImage that will be used as the default package icon</param>
        /// <param name="culture">unused</param>
        /// <returns>A BitmapSource with the image</returns>
        /// <remarks>
        /// We bind to a BitmapImage instead of a Uri so that we can control the decode size, since we are displaying 32x32 images, while many of the images are 128x128 or larger.
        /// This leads to a memory savings.
        /// </remarks>
        public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
        {
            if (values == null || values.Length == 0)
            {
                return(null);
            }

            var iconUrl            = values[0] as Uri;
            var defaultPackageIcon = parameter as BitmapSource;

            if (iconUrl == null)
            {
                return(null);
            }

            string cacheKey          = GenerateKeyFromIconUri(iconUrl);
            var    cachedBitmapImage = BitmapImageCache.Get(cacheKey) as BitmapSource;

            if (cachedBitmapImage != null)
            {
                return(cachedBitmapImage);
            }

            // Some people run on networks with internal NuGet feeds, but no access to the package images on the internet.
            // This is meant to detect that kind of case, and stop spamming the network, so the app remains responsive.
            if (ErrorFloodGate.IsOpen)
            {
                return(defaultPackageIcon);
            }

            var iconBitmapImage = new BitmapImage();

            iconBitmapImage.BeginInit();

            BitmapSource imageResult;

            if (IsEmbeddedIconUri(iconUrl))
            {
                // Check if we have enough info to read the icon from the package
                if (values.Length == 2 && values[1] is Func <PackageReaderBase> lazyReader)
                {
                    try
                    {
                        PackageReaderBase reader = lazyReader(); // Always returns a new reader. That avoids using an already disposed one
                        if (reader is PackageArchiveReader par)  // This reader is closed in BitmapImage events
                        {
                            var iconEntryNormalized = PathUtility.StripLeadingDirectorySeparators(
                                Uri.UnescapeDataString(iconUrl.Fragment)
                                .Substring(1));     // Substring skips the '#' in the URI fragment
                            iconBitmapImage.StreamSource = par.GetEntry(iconEntryNormalized).Open();

                            void EmbeddedIcon_DownloadOrDecodeFailed(object sender, ExceptionEventArgs args)
                            {
                                reader.Dispose();
                                CheckForFailedCacheEntry(cacheKey, args);
                            }

                            void EmbeddedIcon_DownloadCompleted(object sender, EventArgs args)
                            {
                                reader.Dispose();
                                IconBitmapImage_DownloadCompleted(sender, args);
                            }

                            iconBitmapImage.DecodeFailed      += EmbeddedIcon_DownloadOrDecodeFailed;
                            iconBitmapImage.DownloadFailed    += EmbeddedIcon_DownloadOrDecodeFailed;
                            iconBitmapImage.DownloadCompleted += EmbeddedIcon_DownloadCompleted;

                            imageResult = FinishImageProcessing(iconBitmapImage, iconUrl, defaultPackageIcon);
                        }
                        else // we cannot use the reader object
                        {
                            reader?.Dispose();
                            AddToCache(cacheKey, defaultPackageIcon);
                            imageResult = defaultPackageIcon;
                        }
                    }
                    catch (Exception)
                    {
                        AddToCache(cacheKey, defaultPackageIcon);
                        imageResult = defaultPackageIcon;
                    }
                }
                else // Identified an embedded icon URI, but we are unable to process it
                {
                    AddToCache(cacheKey, defaultPackageIcon);
                    imageResult = defaultPackageIcon;
                }
            }
            else
            {
                iconBitmapImage.UriSource = iconUrl;

                iconBitmapImage.DecodeFailed      += IconBitmapImage_DownloadOrDecodeFailed;
                iconBitmapImage.DownloadFailed    += IconBitmapImage_DownloadOrDecodeFailed;
                iconBitmapImage.DownloadCompleted += IconBitmapImage_DownloadCompleted;

                imageResult = FinishImageProcessing(iconBitmapImage, iconUrl, defaultPackageIcon);
            }

            return(imageResult);
        }
Пример #14
0
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            // hide the important buttons if not administrator
            if (user.employee_type.Equals("S") is false)
            {
                featureBtn.Visibility = Visibility.Collapsed;
                offerBtn.Visibility   = Visibility.Collapsed;
                closeBtn.Visibility   = Visibility.Collapsed;
            }

            // Add the ID number to the label at the top
            listingIDLabel.Content += item.id.ToString();

            // Add the address information
            listingAddress.Text = item.Address;

            // Add all of the direct features
            featureGridView.Items.Add(new FeatureItem("Asking Price", item.AskingPrice));
            featureGridView.Items.Add(new FeatureItem("Date Listed", item.DateListed));
            featureGridView.Items.Add(new FeatureItem("Date Built", item.YearBuilt));

            if (originalItem.square_footage != null)
            {
                featureGridView.Items.Add(new FeatureItem("Square Footage", originalItem.square_footage.ToString()));
            }
            if (originalItem.lot_size != null)
            {
                featureGridView.Items.Add(new FeatureItem("Lot Size", originalItem.lot_size.ToString()));
            }

            featureGridView.Items.Add(new FeatureItem("Number of Bedrooms", item.Bedrooms.ToString()));
            featureGridView.Items.Add(new FeatureItem("Number of Bathrooms", item.Bathrooms.ToString()));
            featureGridView.Items.Add(new FeatureItem("Number of Stories", item.Stories.ToString()));
            featureGridView.Items.Add(new FeatureItem("Has Garage?", originalItem.has_garage.ToString()));

            // Add the addition features
            using (var context = new Model()) {
                var features = context.Features.SqlQuery("SELECT * FROM Feature WHERE listing_id = @id", new SqlParameter("id", item.id)).ToList <Feature>();

                foreach (Feature f in features)
                {
                    featureGridView.Items.Add(new FeatureItem(f.heading, f.body));
                }
            }

            // Set Display picture
            if (originalItem.display_picture != null)
            {
                using (MemoryStream ms = new MemoryStream(originalItem.display_picture)) {
                    // Read in the Byte Array
                    ms.Position = 0;
                    var img = new BitmapImage();
                    img.BeginInit();
                    img.CacheOption  = BitmapCacheOption.OnLoad;
                    img.StreamSource = ms;
                    img.EndInit();

                    // Display in window
                    listingImage.Source = img;
                }
            }
        }
Пример #15
0
        private async void DisplayMedia(Media media, bool fullRedraw)
        {
            //don't need to update if it's the same as what is currently displayed
            if (media != null && CurrentDispalyMedia != null && CurrentDispalyMedia.Equals(media))
            {
                Logging.Debug(LogOptions.ClassName, "No need to display media, is the same");
                return;
            }
            CurrentDispalyMedia = media;

            //devurl, description, update notes need to be changed if the parent package being displayed changed
            //this would happen only if we are in combobox mode (displaying medias of multiple packages)
            if (ComboBoxItemsInsideMode && media != null && (!CurrentDisplaySP.Equals(media.SelectablePackageParent)))
            {
                fullRedraw       = true;
                CurrentDisplaySP = media.SelectablePackageParent;
            }

            if (fullRedraw)
            {
                ToggleDevUrlList(media, media == null? false : string.IsNullOrWhiteSpace(media.SelectablePackageParent.DevURL));

                //set the name of the window to be the package name
                if (EditorMode)
                {
                    Title = "EDITOR_TEST_MODE";
                }
                else if (ComboBoxItemsInsideMode)
                {
                    Title = string.Format("{0}: {1}", Translations.GetTranslatedString("dropDownItemsInside"), CurrentDisplaySP.NameFormatted);
                }
                else
                {
                    Title = CurrentDisplaySP.NameFormatted;
                }

                //set description
                PreviewDescriptionBox.Text = CurrentDisplaySP.DescriptionFormatted;

                //set update notes
                PreviewUpdatesBox.Text = CurrentDisplaySP.UpdateCommentFormatted;
            }

            //clear media url list and re-build it
            if (MediaIndexer.Children.Count > 0)
            {
                MediaIndexer.Children.Clear();
            }

            //make the linked labels in the link box
            for (int i = 0; i < Medias.Count; i++)
            {
                TextBlock block = new TextBlock();
                block.Inlines.Clear();
                Hyperlink h = new Hyperlink(new Run(i.ToString()))
                {
                    Tag = Medias[i],
                    //dummy URI just to make the request navigate work
                    NavigateUri = new Uri("https://google.com")
                };
                h.RequestNavigate += OnMediaHyperlinkClick;
                block.Inlines.Add(h);
                MediaIndexer.Children.Add(block);
            }

            HandlePlayerDisposal();

            //null the child element and make it again
            MainPreviewBorder.Child = null;
            if (media != null)
            {
                Logging.Debug(LogOptions.ClassName, "Loading preview of MediaType {0}, URL={1}", media.MediaType.ToString(), media.URL);
                Image pictureViewer;
                switch (media.MediaType)
                {
                case MediaType.Unknown:
                default:
                    Logging.Error("Invalid MediaType: {0}", media.MediaType.ToString());
                    return;

                case MediaType.HTML:
                    if (browser != null)
                    {
                        browser.Dispose();
                        browser = null;
                    }
                    browser = new WebBrowser();
                    //https://stackoverflow.com/questions/2585782/displaying-html-from-string-in-wpf-webbrowser-control
                    browser.NavigateToString(media.URL);
                    MainPreviewBorder.Child = browser;
                    break;

                case MediaType.MediaFile:
                    //show progress first
                    MainPreviewBorder.Child = new ProgressBar()
                    {
                        Minimum             = 0,
                        Maximum             = 1,
                        Value               = 0,
                        HorizontalAlignment = HorizontalAlignment.Stretch,
                        VerticalAlignment   = VerticalAlignment.Top,
                        Margin              = new Thickness(0, 20, 0, 0),
                        Height              = 20
                    };
                    using (WebClient client = new WebClient()
                    {
                    })
                    {
                        client.DownloadProgressChanged += Client_DownloadProgressChanged;

                        //now load the media
                        try
                        {
                            byte[] data = await client.DownloadDataTaskAsync(media.URL);

                            MainPreviewBorder.Child = new RelhaxMediaPlayer(media.URL, data);
                        }
                        catch (Exception ex)
                        {
                            Logging.Exception("failed to load audio data");
                            Logging.Exception(ex.ToString());
                            pictureViewer = new Image
                            {
                                ClipToBounds = true
                            };
                            pictureViewer.Source    = CommonUtils.BitmapToImageSource(Properties.Resources.error_loading_picture);
                            MainPreviewBorder.Child = pictureViewer;
                        }
                    }
                    break;

                case MediaType.Picture:
                    //https://docs.microsoft.com/en-us/dotnet/api/system.windows.controls.image?view=netframework-4.7.2
                    pictureViewer = new Image
                    {
                        ClipToBounds = true
                    };
                    MainContentControl.MouseRightButtonDown    += MainContentControl_MouseRightButtonDown;
                    MainContentControl.PreviewMouseDoubleClick += MainContentControl_PreviewMouseDoubleClick;
                    MainPreviewBorder.Child = new ProgressBar()
                    {
                        Minimum             = 0,
                        Maximum             = 1,
                        Value               = 0,
                        HorizontalAlignment = HorizontalAlignment.Stretch,
                        VerticalAlignment   = VerticalAlignment.Top,
                        Margin              = new Thickness(0, 20, 0, 0),
                        Height              = 20
                    };
                    //https://stackoverflow.com/questions/9173904/byte-array-to-image-conversion
                    //https://stackoverflow.com/questions/18134234/how-to-convert-system-io-stream-into-an-image
                    using (WebClient client = new WebClient()
                    {
                    })
                    {
                        client.DownloadProgressChanged += Client_DownloadProgressChanged;
                        try
                        {
                            byte[] image = await client.DownloadDataTaskAsync(media.URL);

                            ImageStream = new MemoryStream(image);
                            BitmapImage bitmapImage = new BitmapImage();
                            bitmapImage.BeginInit();
                            bitmapImage.StreamSource = ImageStream;
                            bitmapImage.EndInit();
                            pictureViewer.Source = bitmapImage;
                        }
                        catch (Exception ex)
                        {
                            Logging.Exception("failed to load picture");
                            Logging.Exception(ex.ToString());
                            pictureViewer.Source = CommonUtils.BitmapToImageSource(Properties.Resources.error_loading_picture);
                        }
                    }
                    //put the zoom border inside the main preview one. already set, might as well use it
                    zoomBorder = new ZoomBorder()
                    {
                        Child = pictureViewer,
                        HorizontalAlignment = HorizontalAlignment.Stretch,
                        VerticalAlignment   = VerticalAlignment.Stretch,
                        BorderThickness     = new Thickness(1.0),
                        BorderBrush         = Brushes.Black,
                        ClipToBounds        = true
                    };
                    zoomBorder.SizeChanged           += ZoomBorder_SizeChanged;
                    MainPreviewBorder.ClipToBounds    = true;
                    MainPreviewBorder.BorderThickness = new Thickness(0.0);
                    MainPreviewBorder.Child           = zoomBorder;
                    break;

                case MediaType.Webpage:
                    if (browser != null)
                    {
                        browser.Dispose();
                        browser = null;
                    }
                    browser = new WebBrowser();
                    //https://stackoverflow.com/questions/2585782/displaying-html-from-string-in-wpf-webbrowser-control
                    browser.Navigate(media.URL);
                    MainPreviewBorder.Child = browser;
                    break;
                }
            }
        }
Пример #16
0
        public void GetBitmap(BitmapFile bitmapFile)
        {
            if (_isworking)
            {
                _nextfile = bitmapFile;
                return;
            }
            _nextfile    = null;
            _isworking   = true;
            _currentfile = bitmapFile;
            _currentfile.RawCodecNeeded = false;
            if (!File.Exists(_currentfile.FileItem.FileName))
            {
                Log.Error("File not found " + _currentfile.FileItem.FileName);
                StaticHelper.Instance.SystemMessage = "File not found " + _currentfile.FileItem.FileName;
            }
            else
            {
                BitmapImage res = null;
                //Metadata.Clear();
                try
                {
                    if (_currentfile.FileItem.IsRaw)
                    {
                        WriteableBitmap writeableBitmap = null;
                        Log.Debug("Loading raw file.");
                        BitmapDecoder bmpDec = BitmapDecoder.Create(new Uri(_currentfile.FileItem.FileName),
                                                                    BitmapCreateOptions.None,
                                                                    BitmapCacheOption.Default);
                        if (bmpDec.CodecInfo != null)
                        {
                            Log.Debug("Raw codec: " + bmpDec.CodecInfo.FriendlyName);
                        }
                        if (bmpDec.Thumbnail != null)
                        {
                            WriteableBitmap bitmap = new WriteableBitmap(bmpDec.Thumbnail);
                            bitmap.Freeze();
                            bitmapFile.DisplayImage = bitmap;
                        }

                        if (ServiceProvider.Settings.LowMemoryUsage)
                        {
                            if (bmpDec.Thumbnail != null)
                            {
                                writeableBitmap = BitmapFactory.ConvertToPbgra32Format(bmpDec.Thumbnail);
                            }
                            else
                            {
                                writeableBitmap = BitmapFactory.ConvertToPbgra32Format(bmpDec.Frames[0]);
                                double dw = 2000 / writeableBitmap.Width;
                                writeableBitmap = writeableBitmap.Resize((int)(writeableBitmap.PixelWidth * dw),
                                                                         (int)(writeableBitmap.PixelHeight * dw),
                                                                         WriteableBitmapExtensions.Interpolation.Bilinear);
                            }
                            bmpDec = null;
                        }
                        else
                        {
                            writeableBitmap = BitmapFactory.ConvertToPbgra32Format(bmpDec.Frames.Single());
                        }
                        GetMetadata(_currentfile, writeableBitmap);
                        Log.Debug("Loading raw file done.");
                    }
                    else
                    {
                        BitmapImage bi = new BitmapImage();
                        // BitmapImage.UriSource must be in a BeginInit/EndInit block.
                        bi.BeginInit();

                        if (ServiceProvider.Settings.LowMemoryUsage)
                        {
                            bi.DecodePixelWidth = 2000;
                        }

                        bi.UriSource = new Uri(_currentfile.FileItem.FileName);
                        bi.EndInit();
                        WriteableBitmap writeableBitmap = BitmapFactory.ConvertToPbgra32Format(bi);
                        GetMetadata(_currentfile, writeableBitmap);
                        Log.Debug("Loading bitmap file done.");
                    }
                }
                catch (FileFormatException)
                {
                    _currentfile.RawCodecNeeded = true;
                    Log.Debug("Raw codec not installed or unknown file format");
                    StaticHelper.Instance.SystemMessage = "Raw codec not installed or unknown file format";
                }
                catch (Exception exception)
                {
                    Log.Error(exception);
                }
                if (_nextfile == null)
                {
                    Thread threadPhoto = new Thread(GetAdditionalData);
                    threadPhoto.Start(_currentfile);
                    _currentfile.OnBitmapLoaded();
                    _currentfile = null;
                    _isworking   = false;
                }
                else
                {
                    _isworking = false;
                    GetBitmap(_nextfile);
                }
            }
        }
Пример #17
0
        private async Task <DriverInfo> GetDriverAsync(int driverId)
        {
            var tokenResponse = await tokenClient.RequestRefreshTokenAsync(ConfigurationManager.AppSettings["refreshToken"]);

            var httpClient = new HttpClient
            {
                BaseAddress = new Uri(ConfigurationManager.AppSettings["userManagementBaseUri"])
            };

            httpClient.SetBearerToken(tokenResponse.AccessToken);

            var httpResponse = await httpClient.GetAsync($"api/Driver/{driverId}");

            var content = httpResponse.Content;

            var driverJson = await content.ReadAsStringAsync();

            var driver = JsonConvert.DeserializeObject <Driver>(driverJson);

            var car = new CarInfo
            {
                Id                = driver.Car.Id,
                Brand             = driver.Car.Brand,
                CarPicture1       = ImageConverter.ConvertImageToImageSource(driver.Car.CarPicture1),
                CarPicture2       = ImageConverter.ConvertImageToImageSource(driver.Car.CarPicture2),
                CarPicture3       = ImageConverter.ConvertImageToImageSource(driver.Car.CarPicture3),
                FuelType          = driver.Car.FuelType,
                HasAirConditioner = driver.Car.HasAirConditioner,
                HasKitchen        = driver.Car.HasKitchen,
                HasMicrophone     = driver.Car.HasMicrophone,
                HasToilet         = driver.Car.HasToilet,
                HasWiFi           = driver.Car.HasWiFi,
                LicensePlate      = driver.Car.LicensePlate,
                NumberOfSeats     = driver.Car.NumberOfSeats
            };

            var driverInfo = new DriverInfo
            {
                Id                     = driver.Id,
                FirstName              = driver.FirstName,
                LastName               = driver.LastName,
                DateOfBirth            = driver.DateOfBirth,
                DrivingLicencePicBack  = ImageConverter.ConvertImageToImageSource(driver.DrivingLicencePicBack),
                DrivingLicencePicFront = ImageConverter.ConvertImageToImageSource(driver.DrivingLicencePicFront),
                KnowledgeOfLanguages   = driver.KnowledgeOfLanguages,
                Email                  = driver.Email,
                Gender                 = driver.Gender,
                NumberOfAppraisers     = driver.NumberOfAppraisers,
                PhoneNumber            = driver.PhoneNumber,
                Rating                 = driver.Rating,
                Car                    = car
            };

            if (driverInfo.Image != null)
            {
                driverInfo.Image = ImageConverter.ConvertImageToImageSource(driver.Image);
            }
            else
            {
                BitmapImage img = new BitmapImage();
                img.BeginInit();
                if (driverInfo.Gender == "Female")
                {
                    img.UriSource = new Uri(@"pack://*****:*****@"pack://application:,,,/Kanch;component/Images/male.jpg");
                }
                img.EndInit();
                driverInfo.Image = img;
            }

            return(driverInfo);
        }
        /// <summary>
        /// Tab 5 Identify voters with face rectangles and voters'name in section 'Identify Voters'
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void IdentifyButton_Click(object sender, RoutedEventArgs e)
        {
            int itemNum       = Tab5PersonGroupIDComboBox.Items.Count;
            int selectedGroup = Tab5PersonGroupIDComboBox.SelectedIndex;

            if (itemNum == 0)
            {
                MessageBox.Show("Please define the person group ID first in page 2");
            }
            if (selectedGroup == -1)
            {
                MessageBox.Show("Please select a group.");
            }
            if (itemNum != 0 && selectedGroup != -1)
            {
                TestFacePhoto.Source = null;
                var openDlg = new Microsoft.Win32.OpenFileDialog();

                openDlg.Filter = "JPEG Image(*.jpg)|*.jpg";
                bool?result = openDlg.ShowDialog(this);

                if (!(bool)result)
                {
                    return;
                }

                string filePath = openDlg.FileName;

                Uri         fileUri      = new Uri(filePath);
                BitmapImage bitmapSource = new BitmapImage();

                bitmapSource.BeginInit();
                bitmapSource.CacheOption = BitmapCacheOption.None;
                bitmapSource.UriSource   = fileUri;
                bitmapSource.EndInit();


                using (Stream s = File.OpenRead(filePath))
                {
                    var faces = await faceServiceClient.DetectAsync(s);

                    var faceRects = faces.Select(face => face.FaceRectangle).ToArray();
                    var faceIds   = faces.Select(face => face.FaceId).ToArray();

                    string personGroupId = Tab5PersonGroupIDComboBox.Text;

                    var results = await faceServiceClient.IdentifyAsync(personGroupId, faceIds);

                    int           i        = 0;
                    FaceRectangle faceRect = null;

                    DrawingVisual  visual         = new DrawingVisual();
                    DrawingContext drawingContext = visual.RenderOpen();
                    drawingContext.DrawImage(bitmapSource,
                                             new Rect(0, 0, bitmapSource.Width, bitmapSource.Height));
                    double dpi          = bitmapSource.DpiX;
                    double resizeFactor = 96 / dpi;

                    foreach (var identifyResult in results)
                    {
                        Console.WriteLine("Identify result of face id: {0}", identifyResult.FaceId);
                        Console.WriteLine("Identify result of length of candidates: {0}", identifyResult.Candidates.Length);

                        faceRect = faceRects[i];


                        ///No candidate indicates that the person has not provided his registered face image to register as a voter.
                        if (identifyResult.Candidates.Length == 0)
                        {
                            ///Draw a face rectangle
                            drawingContext.DrawRectangle(
                                Brushes.Transparent,
                                new Pen(Brushes.Red, 2),
                                new Rect(
                                    faceRect.Left * resizeFactor,
                                    faceRect.Top * resizeFactor,
                                    faceRect.Width * resizeFactor,
                                    faceRect.Height * resizeFactor
                                    )
                                );
                            ///Draw a context with 'Unknow' in 'Ghostwhite' color
                            Point  point = new Point(faceRect.Left * resizeFactor, faceRect.Top * resizeFactor - 10);
                            string text  = "Unknow";
                            System.Windows.Media.FormattedText myText = new System.Windows.Media.FormattedText(
                                text,
                                CultureInfo.GetCultureInfo("en-us"),
                                FlowDirection.LeftToRight,
                                new Typeface("Marlet"),
                                8.0,
                                System.Windows.Media.Brushes.GhostWhite);
                            drawingContext.DrawText(myText, point);
                        }

                        ///The Candidate.Length != 0 means that this person with a bunch of registered face images has been succeed registered into this system
                        if (identifyResult.Candidates.Length != 0)
                        {
                            var candidateId = identifyResult.Candidates[0].PersonId;
                            var person      = await faceServiceClient.GetPersonAsync(personGroupId, candidateId);

                            Console.WriteLine("Identified as {0}", person.Name);

                            ///Draw a face rectangle
                            drawingContext.DrawRectangle(
                                Brushes.Transparent,
                                new Pen(Brushes.Red, 2),
                                new Rect(
                                    faceRect.Left * resizeFactor,
                                    faceRect.Top * resizeFactor,
                                    faceRect.Width * resizeFactor,
                                    faceRect.Height * resizeFactor
                                    )
                                );

                            ///Draw a context with register person's name in 'GreenYellow' colour
                            Point  point = new Point(faceRect.Left * resizeFactor, faceRect.Top * resizeFactor - 10);
                            string text  = person.Name;
                            System.Windows.Media.FormattedText myText = new System.Windows.Media.FormattedText(
                                text,
                                CultureInfo.GetCultureInfo("en-us"),
                                FlowDirection.LeftToRight,
                                new Typeface("Marlet"),
                                10.0,
                                System.Windows.Media.Brushes.GreenYellow);
                            drawingContext.DrawText(myText, point);
                        }
                        i++;
                    }
                    drawingContext.Close();
                    RenderTargetBitmap faceWithRectBitmap = new RenderTargetBitmap(
                        (int)(bitmapSource.PixelWidth * resizeFactor),
                        (int)(bitmapSource.PixelHeight * resizeFactor),
                        96,
                        96,
                        PixelFormats.Pbgra32);

                    faceWithRectBitmap.Render(visual);
                    TestFacePhoto.Source = faceWithRectBitmap;
                }
            }
        }
Пример #19
0
 public static BitmapImage ToBitmapImage(this Bitmap bitmap)
 {
     var bitmapImage = new BitmapImage();
     bitmapImage.BeginInit();
     using (var stream = new MemoryStream())
     {
         bitmap.Save(stream, ImageFormat.Png);
         bitmapImage.StreamSource = stream;
     }
     bitmapImage.EndInit();
     return bitmapImage;
 }
        /// <summary>
        /// Tab 1 Detect Faces and draw rectangles for detected faces in section 'Detect Faces'
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void DetectFacesBrowseButton_Click(object sender, RoutedEventArgs e)
        {
            var openDlg = new Microsoft.Win32.OpenFileDialog();

            openDlg.Filter = "JPEG Image(*.jpg)|*.jpg";
            bool?result = openDlg.ShowDialog(this);

            if (!(bool)result)
            {
                return;
            }

            string filePath = openDlg.FileName;

            Uri         fileUri      = new Uri(filePath);
            BitmapImage bitmapSource = new BitmapImage();

            bitmapSource.BeginInit();
            bitmapSource.CacheOption = BitmapCacheOption.None;
            bitmapSource.UriSource   = fileUri;
            bitmapSource.EndInit();

            FacePhoto.Source = bitmapSource;

            Title = "Detecting...";
            FaceRectangle[] faceRects = await UploadAndDetectFaces(filePath);

            Title = String.Format("Detection Finished. {0} face(s) detected", faceRects.Length);

            if (faceRects.Length > 0)
            {
                DrawingVisual  visual         = new DrawingVisual();
                DrawingContext drawingContext = visual.RenderOpen();
                drawingContext.DrawImage(bitmapSource,
                                         new Rect(0, 0, bitmapSource.Width, bitmapSource.Height));
                double dpi          = bitmapSource.DpiX;
                double resizeFactor = 96 / dpi;

                foreach (var faceRect in faceRects)
                {
                    drawingContext.DrawRectangle(
                        Brushes.Transparent,
                        new Pen(Brushes.Red, 2),
                        new Rect(
                            faceRect.Left * resizeFactor,
                            faceRect.Top * resizeFactor,
                            faceRect.Width * resizeFactor,
                            faceRect.Height * resizeFactor
                            )
                        );
                }

                drawingContext.Close();
                RenderTargetBitmap faceWithRectBitmap = new RenderTargetBitmap(
                    (int)(bitmapSource.PixelWidth * resizeFactor),
                    (int)(bitmapSource.PixelHeight * resizeFactor),
                    96,
                    96,
                    PixelFormats.Pbgra32);

                faceWithRectBitmap.Render(visual);
                FacePhoto.Source = faceWithRectBitmap;
            }
        }
        private async void Image_Click(object sender, RoutedEventArgs e)
        {
            // Create dlg type OpenFileDialog
            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
            // sert default Text
            dlg.DefaultExt = ".jpg";
            dlg.Filter     = "Image files (*.jpg, *.png, *.bmp, *.gif) | *.jpg; *.png; *.bmp; *.gif";

            // show dialog
            // C# 6.0 Question Mark mean null exception -> default constructor
            bool?result = dlg.ShowDialog();

            if (!(bool)result)
            {
                return;
            }
            // Display image
            string filePath = dlg.FileName;

            Uri         fileUri      = new Uri(filePath);
            BitmapImage bitmapSource = new BitmapImage();

            bitmapSource.BeginInit();
            bitmapSource.CacheOption = BitmapCacheOption.None;
            bitmapSource.UriSource   = fileUri;
            bitmapSource.EndInit();

            // upload original photo
            LipstickDisp.Source = bitmapSource;

            using (var fStream = File.OpenRead(filePath))
            {
                try
                {
                    MainWindow mainWindow      = Window.GetWindow(this) as MainWindow;
                    string     subscriptionKey = mainWindow._scenariosControl.SubscriptionKey;
                    string     endpoint        = mainWindow._scenariosControl.SubscriptionEndpoint;

                    lbl_text.Content = "Waitting!";

                    var faceServiceClient = new FaceServiceClient(subscriptionKey, endpoint);
                    ProjectOxford.Face.Contract.Face[] faces = await faceServiceClient.DetectAsync(fStream, false, true, new FaceAttributeType[] { FaceAttributeType.Gender, FaceAttributeType.Age, FaceAttributeType.Smile, FaceAttributeType.Glasses, FaceAttributeType.HeadPose, FaceAttributeType.FacialHair, FaceAttributeType.Emotion, FaceAttributeType.Hair, FaceAttributeType.Makeup, FaceAttributeType.Occlusion, FaceAttributeType.Accessories, FaceAttributeType.Noise, FaceAttributeType.Exposure, FaceAttributeType.Blur });

                    if (faces.Length > 0)
                    {
                        //Drawing around the lip
                        DrawingVisual  visual         = new DrawingVisual();
                        DrawingContext drawingContext = visual.RenderOpen();
                        drawingContext.DrawImage(bitmapSource, new Rect(0, 0, bitmapSource.Width, bitmapSource.Height));
                        double dpi = bitmapSource.DpiX;

                        // Set DPI image
                        double resizeFactor = (dpi == 0) ? 1 : 96 / dpi;

                        foreach (var face in faces)
                        {
                            //face.FaceAttributes.Makeup.LipMakeup.ToString()
                            double UpperLipTop_X    = face.FaceLandmarks.UpperLipTop.X;
                            double UpperLipTop_Y    = face.FaceLandmarks.UpperLipTop.Y;
                            double UpperLipBottom_X = face.FaceLandmarks.UpperLipBottom.X;
                            double UpperLipBottom_Y = face.FaceLandmarks.UpperLipBottom.Y;

                            double UnderLipTop_X    = face.FaceLandmarks.UnderLipTop.X;
                            double UnderLipTop_Y    = face.FaceLandmarks.UnderLipTop.Y;
                            double UnderLipBottom_X = face.FaceLandmarks.UnderLipBottom.X;
                            double UnderLipBottom_Y = face.FaceLandmarks.UnderLipBottom.Y;
                            // lbl_text.Content = faces.Length.ToString() + ' ' + UpperLipTop_X.ToString() + ' ' + UpperLipTop_Y.ToString() + ' ' + UnderLipTop_X.ToString() + ' ' + UnderLipTop_Y.ToString();
                            //lbl_text.Content = face.FaceAttributes.Makeup.LipMakeup.ToString();
                            // Draw a rectangle on the lip
                            drawingContext.DrawRectangle(Brushes.Transparent, new Pen(Brushes.Red, 2),
                                                         new Rect(
                                                             UpperLipTop_X * resizeFactor,
                                                             UpperLipTop_Y * resizeFactor,
                                                             (UpperLipBottom_X - UpperLipTop_X) * resizeFactor,
                                                             (UpperLipBottom_Y - UpperLipTop_Y) * resizeFactor
                                                             )
                                                         );
                            // Loop through the images pixels to reset color.

                            //lbl_text.Content = UpperLipTop_X; //* resizeFactor;
                            //drawingContext.DrawRectangle(Brushes.Red, null,
                            //    new Rect(
                            //        UpperLipTop_X * resizeFactor - 50, UpperLipTop_Y * resizeFactor, 50, 20
                            //    )
                            //);

                            //int i = Int32.Parse((UpperLipTop_X * resizeFactor - 100) * 100);
                            //for (double Y = UpperLipTop_Y * resizeFactor - 100; Y <= UnderLipBottom_Y * resizeFactor + 100; Y++)
                            //{
                            //    for (double X = UpperLipTop_X * resizeFactor - 100; X < UpperLipTop_X * resizeFactor + 100; X++)
                            //    {
                            //        drawingContext.DrawRectangle(Brushes.Red, null, new Rect(Y, X, 1, 1));
                            //    }
                            //}
                            //lbl_text.Content = count.ToString() + ' ' + bitmapSource.Width.ToString() + ' ' + bitmapSource.Height.ToString();
                        }

                        // Close drawing
                        drawingContext.Close();



                        // Display the image with the rectangle around the face
                        RenderTargetBitmap faceWithRectBitmap = new RenderTargetBitmap(
                            (int)(bitmapSource.PixelWidth * resizeFactor),
                            (int)(bitmapSource.PixelHeight * resizeFactor),
                            96, 96, PixelFormats.Pbgra32);

                        faceWithRectBitmap.Render(visual);
                        lipstickDisplay.Source = faceWithRectBitmap;
                    }
                }
                catch (FaceAPIException ex)
                {
                    MainWindow.Log("Response: {0}. {1}", ex.ErrorCode, ex.ErrorMessage);
                    GC.Collect();
                    return;
                }
            }
        }
Пример #22
0
        public void DisplayPhoto(int boatId)
        {
            //Retrieve image blob from database
            using (var context = new BootDB())
            {
                var tableData = (from b in context.Boats
                                 join bi in context.BoatImages
                                 on b.boatId equals bi.boatId
                                 where b.boatId == boatId
                                 select new
                {
                    boatId = b.boatId,
                    boatImageBlob = bi.boatImageBlob
                });

                foreach (var b in tableData)
                {
                    BoatImageData = new BoatImages()
                    {
                        boatImageBlob = b.boatImageBlob
                    };
                }
            }


            if (BoatImageData == null)
            {
                return;
            }
            if (!string.IsNullOrEmpty(BoatImageData.boatImageBlob))
            {
                //Convert Base64 encoded string to Bitmap Image
                var binaryData = Convert.FromBase64String(BoatImageData.boatImageBlob);
                var bitmapImg  = new BitmapImage();
                bitmapImg.BeginInit();
                bitmapImg.StreamSource = new MemoryStream(binaryData);
                bitmapImg.EndInit();

                //Create new image
                var boatPhoto = new Image
                {
                    Width  = 200,
                    Height = 200,
                    Source = bitmapImg,
                };

                var bc             = new BrushConverter();
                var brushAppOrange = (Brush)bc.ConvertFrom("#FF5722");
                brushAppOrange.Freeze();

                //Create new border
                var border1 = new Border
                {
                    Width  = 200,
                    Height = 200,
                    HorizontalAlignment = HorizontalAlignment.Left,
                    VerticalAlignment   = VerticalAlignment.Top,
                    Margin          = new Thickness(50, 120, 0, 0),
                    BorderBrush     = brushAppOrange,
                    BorderThickness = new Thickness(1),
                    Child           = boatPhoto
                };

                //Add border with Image to view
                ViewGrid.Children.Add(border1);
            }
            else //Image Blob is null
            {
                //Reset label margins
                nameWrap.Margin   = new Thickness(50, 113, 0, 610);
                descrWrap.Margin  = new Thickness(50, 153, 0, 580);
                typeWrap.Margin   = new Thickness(50, 193, 0, 545);
                steerWrap.Margin  = new Thickness(50, 223, 0, 511);
                niveauWrap.Margin = new Thickness(50, 253, 0, 476);
            }
        }
Пример #23
0
        private static void OnBase64SourceChanged(DependencyObject sender,
                                                  DependencyPropertyChangedEventArgs e)
        {
            var inlineImage = (InlineImage)sender;

            string val = inlineImage.Base64Source;

            if (string.IsNullOrWhiteSpace(val))
            {
                return;
            }

            var stream = new MemoryStream(Convert.FromBase64String(inlineImage.Base64Source));


            var bitmapImage = new BitmapImage();

            try
            {
                bitmapImage.BeginInit();
                bitmapImage.StreamSource = stream;
                bitmapImage.EndInit();
                bitmapImage.Freeze();
            }
            catch {
                //FlowDocumentPackage.toDispose.Add(new InlineDisposable(() =>
                //{
                //    stream.Dispose();
                //}));
                stream      = new MemoryStream(XResources.EmptyImageData);
                bitmapImage = new BitmapImage();
                bitmapImage.BeginInit();
                bitmapImage.StreamSource = stream;
                bitmapImage.EndInit();
                bitmapImage.Freeze();
            }
            inlineImage.Source = bitmapImage;

            //FlowDocumentPackage.toDispose.Add(new InlineDisposable(() =>
            //{
            //    inlineImage.Source = null;
            //    stream.Dispose();
            //}));

            //var image = new Image
            //{
            //    Source = bitmapImage,
            //    Stretch = inlineImage.Stretch,
            //    StretchDirection = inlineImage.StretchDirection,
            //};

            //if (!double.IsNaN(inlineImage.Width))
            //{
            //    image.Width = inlineImage.Width;
            //}

            //if (!double.IsNaN(inlineImage.Height))
            //{
            //    image.Height = inlineImage.Height;
            //}

            //if (!double.IsNaN(inlineImage.MaxHeight)) {
            //    image.MaxHeight = inlineImage.MaxHeight;
            //}

            //if (!double.IsNaN(inlineImage.MaxWidth)) {
            //    image.MaxWidth = inlineImage.MaxWidth;
            //}

            //inlineImage.Child = image;
        }
Пример #24
0
		/// <summary>
		/// 
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		async void OnLoadMediaBackgroundWorker(object sender, DoWorkEventArgs e)
		{
			var item = e.Argument as TweetListItemData;
			var worker = sender as BackgroundWorker;

			string mediaUrl = string.Empty;

			var media = item.Status.Entities.Media.FirstOrDefault();
			if (media != null)
			{
				var photo = item.Status.Entities.Media.FirstOrDefault();
				if (photo != null)
				{
					mediaUrl = photo.MediaUrl;
				}
			}
			else
			{
				if (UseTumblrApiFlag)
				{
					// Tumblerチェック
					var url = item.Status.Entities.Urls.FirstOrDefault();
					if (url != null)
					{
						mediaUrl = ExcuseTumblrImageUrl(url.ExpandedValue);
					}
				}
			}

			item.MediaUrl = mediaUrl;

			if (!string.IsNullOrEmpty(mediaUrl))
				SaveMediaFile(mediaUrl, item.Status.Id);

			if (!string.IsNullOrEmpty(mediaUrl))
			{
				using (var ioMediaImage = await LoadImageAsync(new Uri(mediaUrl)))
				{

					BitmapImage bi = new BitmapImage();
					RenderOptions.SetBitmapScalingMode(bi, BitmapScalingMode.HighQuality);
					bi.BeginInit();
					bi.CacheOption = BitmapCacheOption.OnLoad;
					bi.StreamSource = ioMediaImage;
					bi.EndInit();
					bi.Freeze();

					DispatcherHelper.UIDispatcher.Invoke(() =>
					{
						var image = new Image();
						image.Source = bi;
						item.PhotoImage = image;
					});
				}
			}

			
			using (var ioProfileImage = await LoadImageAsync(new Uri(item.Status.User.ProfileImageUrl)))
			{
				BitmapImage bi = new BitmapImage();
				RenderOptions.SetBitmapScalingMode(bi, BitmapScalingMode.HighQuality);
				bi.BeginInit();
				bi.CacheOption = BitmapCacheOption.OnLoad;
				bi.StreamSource = ioProfileImage;
				bi.EndInit();
				bi.Freeze();
					
				DispatcherHelper.UIDispatcher.Invoke(() =>
				{
					var image = new Image();
					image.Source = bi;
					item.AvaterImage = image;
				});
				
			}
		}
Пример #25
0
        private void Image4_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            #region Rectangle 4 




            SqlConnection con1 = new SqlConnection(PublicVar.ConnectionString);
            con1.Open();




            #region Find Morabi Name And Morabi Family

            SqlCommand myCommand = new SqlCommand("Select (MorabiName + ' ' + MorabiFamily) from MorabiTable where MorabiID = " + Load4.Text, con1);
            object result = myCommand.ExecuteScalar();
            MorabiNameTXT.Content = Convert.ToString(result).Trim();

            #endregion
            #region Find Morabi Colloctions 
            SqlCommand MorabiFindCommand = new SqlCommand("Select Count(MorabiFind) from Users where MorabiFind = " + Load4.Text, con1);
            object MorabiFindresult = MorabiFindCommand.ExecuteScalar();
            if (Convert.ToString(MorabiFindresult) != "")
            {
                ZirMajmoeTXT.Content = Convert.ToString(MorabiFindresult).Trim();
            }
            else
            {
                ZirMajmoeTXT.Content = "0";
            }
            MorabiIDFound.Content = Load4.Text;
            #endregion
            #region Load Image
            SqlCommand CommandImage = new SqlCommand(
               "SELECT (MorabiImage) FROM MorabiTable where MorabiID = " + Load4.Text, con1);
            SqlDataReader rdr1 = null;
            rdr1 = CommandImage.ExecuteReader();
            while (rdr1.Read())
            {


                if (rdr1 != null)
                {
                    byte[] data = (byte[])rdr1[0];

                    using (System.IO.MemoryStream ms = new System.IO.MemoryStream(data))
                    {
                        var imageSource = new BitmapImage();
                        imageSource.BeginInit();
                        imageSource.StreamSource = ms;
                        imageSource.CacheOption = BitmapCacheOption.OnLoad;
                        imageSource.EndInit();


                        MyImage.Fill = new ImageBrush
                        {
                            ImageSource = imageSource
                        };
                    }
                }

            }
            #endregion





            #endregion
            con1.Close();
        }
Пример #26
0
 /// <summary>
 ///
 /// </summary>
 private static void DownloadImage()
 {
     while (true)
     {
         ImageQueueInfo t = null;
         lock (Stacks)
         {
             if (Stacks.Count > 0)
             {
                 t = Stacks.Dequeue();
             }
         }
         if (t != null)
         {
             Uri         uri   = new Uri(t.url);
             BitmapImage image = null;
             try
             {
                 if ("http".Equals(uri.Scheme, StringComparison.CurrentCultureIgnoreCase))
                 {
                     //如果是HTTP下载文件
                     using (WebClient wc = new WebClient())
                     {
                         using (var ms = new MemoryStream(wc.DownloadData(uri)))
                         {
                             image = new BitmapImage();
                             image.BeginInit();
                             image.CacheOption  = BitmapCacheOption.OnLoad;
                             image.StreamSource = ms;
                             image.EndInit();
                         }
                     }
                 }
                 else if ("file".Equals(uri.Scheme, StringComparison.CurrentCultureIgnoreCase))
                 {
                     if (!File.Exists(t.url))
                     {
                         continue;
                     }
                     using (var fs = new FileStream(t.url, FileMode.Open))
                     {
                         image = new BitmapImage();
                         image.BeginInit();
                         image.CacheOption  = BitmapCacheOption.OnLoad;
                         image.StreamSource = fs;
                         image.EndInit();
                     }
                 }
                 if (image != null)
                 {
                     if (image.CanFreeze)
                     {
                         image.Freeze();
                     }
                     t.image.Dispatcher.BeginInvoke(new Action <ImageQueueInfo, BitmapImage>((i, bmp) =>
                     {
                         OnComplate?.Invoke(i.image, i.url, bmp);
                     }), new object[] { t, image });
                 }
             }
             catch (Exception e)
             {
                 MessageBox.Show(e.Message);
                 continue;
             }
         }
         if (Stacks.Count > 0)
         {
             continue;
         }
         autoEvent.WaitOne();
     }
 }
Пример #27
0
        public NotificationWindow(TrackInfoViewModel trackInfoVm, string coverPictureSource, NotificationPosition position, bool showControls, int maxSecondsVisible) : base()
        {
            this.InitializeComponent();

            this.maxSecondsVisible = maxSecondsVisible;

            int notificationHeight = 66 + 2 * this.notificationShadowSize;
            int notificationWidth  = 286 + 2 * this.notificationShadowSize;

            if (showControls)
            {
                notificationHeight           += 40;
                notificationWidth            += 90;
                this.ControlsPanel.Visibility = Visibility.Visible;
                this.VolumePanel.Visibility   = Visibility.Visible;
            }
            else
            {
                this.ControlsPanel.Visibility = Visibility.Collapsed;
                this.VolumePanel.Visibility   = Visibility.Collapsed;
            }

            if (trackInfoVm != null)
            {
                this.TextBoxTitle.Text  = string.IsNullOrEmpty(trackInfoVm.TrackTitle) ? trackInfoVm.FileName : trackInfoVm.TrackTitle;
                this.TextBoxArtist.Text = trackInfoVm.ArtistName;
            }
            else
            {
                this.TextBoxTitle.Text  = ResourceUtils.GetStringResource("Language_Title");
                this.TextBoxArtist.Text = ResourceUtils.GetStringResource("Language_Artist");
            }

            this.ToolTipTitle.Text  = this.TextBoxTitle.Text;
            this.ToolTipArtist.Text = this.TextBoxArtist.Text;

            if (!string.IsNullOrEmpty(coverPictureSource))
            {
                try
                {
                    BitmapImage coverImage = new BitmapImage();
                    coverImage.BeginInit();
                    coverImage.DecodePixelWidth  = 300; // Needs to be big enough, otherwise the picture is blurry
                    coverImage.DecodePixelHeight = 300; // Needs to be big enough, otherwise the picture is blurry
                    //coverImage.DecodePixelWidth = notificationHeight
                    //coverImage.DecodePixelHeight = notificationHeight
                    coverImage.CacheOption = BitmapCacheOption.OnLoad;
                    coverImage.UriSource   = new Uri(coverPictureSource);
                    coverImage.EndInit();

                    this.CoverPicture.Source = coverImage;
                    this.CloseBorder.Opacity = 1.0;
                }
                catch (Exception)
                {
                    // Swallow
                }
            }
            else
            {
                this.CloseBorder.Opacity = 0.4;
            }


            Dispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle, new Action(() =>
            {
                Rect desktopWorkingArea = System.Windows.SystemParameters.WorkArea;

                // First, set the position
                switch (position)
                {
                case NotificationPosition.BottomLeft:
                    // Bottom left
                    this.Left = desktopWorkingArea.Left + this.notificationMarginFromScreen;
                    this.Top  = desktopWorkingArea.Bottom - notificationHeight - this.notificationMarginFromScreen;
                    break;

                case NotificationPosition.TopLeft:
                    // Top left
                    this.Left = desktopWorkingArea.Left + this.notificationMarginFromScreen;
                    this.Top  = desktopWorkingArea.Top + this.notificationMarginFromScreen;
                    break;

                case NotificationPosition.TopRight:
                    // Top right
                    this.Left = desktopWorkingArea.Right - notificationWidth - this.notificationMarginFromScreen;
                    this.Top  = desktopWorkingArea.Top + this.notificationMarginFromScreen;
                    break;

                case NotificationPosition.BottomRight:
                    // Bottom right
                    this.Left = desktopWorkingArea.Right - notificationWidth - this.notificationMarginFromScreen;
                    this.Top  = desktopWorkingArea.Bottom - notificationHeight - this.notificationMarginFromScreen;
                    break;

                default:
                    break;
                }

                // After setting the position, set the size. The original size op 0px*0px prevents
                // flicker when displaying the popup. Because it briefly appears in the top left
                // corner before getting its desired position.
                this.Width               = notificationWidth;
                this.Height              = notificationHeight;
                this.CoverPicture.Width  = notificationHeight - 2 * this.notificationShadowSize;
                this.CoverPicture.Height = notificationHeight - 2 * this.notificationShadowSize;
                this.CoverTile.Width     = notificationHeight - 2 * this.notificationShadowSize;
                this.CoverTile.Height    = notificationHeight - 2 * this.notificationShadowSize;
            }));

            this.hideTimer.Interval  = TimeSpan.FromSeconds(1);
            this.closeTimer.Interval = TimeSpan.FromSeconds(1);
            this.hideTimer.Tick     += new EventHandler(HideTimer_Tick);
            this.closeTimer.Tick    += new EventHandler(CloseTimer_Tick);
        }
Пример #28
0
        public SeedInformationWindow(Seed seed, AmoebaManager amoebaManager)
        {
            if (seed == null)
            {
                throw new ArgumentNullException(nameof(seed));
            }
            if (amoebaManager == null)
            {
                throw new ArgumentNullException(nameof(amoebaManager));
            }

            _seed          = seed;
            _amoebaManager = amoebaManager;

            InitializeComponent();

            {
                var icon = new BitmapImage();

                icon.BeginInit();
                icon.StreamSource = new FileStream(Path.Combine(_serviceManager.Paths["Icons"], "Amoeba.ico"), FileMode.Open, FileAccess.Read, FileShare.Read);
                icon.EndInit();
                if (icon.CanFreeze)
                {
                    icon.Freeze();
                }

                this.Icon = icon;
            }

            lock (_seed.ThisLock)
            {
                _nameTextBox.Text         = _seed.Name;
                _keywordsTextBox.Text     = string.Join(", ", _seed.Keywords);
                _signatureTextBox.Text    = seed.Certificate?.ToString();
                _creationTimeTextBox.Text = seed.CreationTime.ToLocalTime().ToString(LanguagesManager.Instance.DateTime_StringFormat, System.Globalization.DateTimeFormatInfo.InvariantInfo);
                _lengthTextBox.Text       = string.Format("{0} ({1:#,0} Byte)", NetworkConverter.ToSizeString(_seed.Length), _seed.Length);
            }

            _storeSignatureListView.ItemsSource = _storeSignatureCollection;

            try
            {
                _storeTabItem.Cursor = Cursors.Wait;

                Task.Run(() =>
                {
                    return(this.GetSignature(_seed));
                }).ContinueWith(task =>
                {
                    foreach (var signature in task.Result)
                    {
                        _storeSignatureCollection.Add(signature);
                    }

                    _storeTabItem.Cursor = null;
                }, TaskScheduler.FromCurrentSynchronizationContext());
            }
            catch (Exception)
            {
            }
        }
Пример #29
0
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            DateTime start = DateTime.Now;

            byte[] data = value as byte[];

            if (data == null || data.Length == 0)
            {
                return(null);
            }

            var image = new BitmapImage();

            using (var mem = new MemoryStream(data))
            {
                try
                {
                    mem.Position = 0;
                    image.BeginInit();
                    image.CreateOptions     = BitmapCreateOptions.PreservePixelFormat;
                    image.CacheOption       = BitmapCacheOption.OnLoad;
                    image.DecodePixelHeight = 128;
                    image.DecodePixelWidth  = 128;
                    image.UriSource         = null;
                    image.StreamSource      = mem;
                    image.EndInit();
                }
                catch (Exception e)
                {
                    return(Brushes.White);
                }
            }
            image.Freeze();
            Debug.WriteLine(DateTime.Now - start);
            start = DateTime.Now;

            int minStride = checked (((image.PixelWidth * image.Format.BitsPerPixel) + 7) / 8);

            int minRequiredDestSize = checked ((minStride * (image.PixelHeight - 1)) + minStride);

            data = new byte[minRequiredDestSize];

            image.CopyPixels(data, minStride, 0);

            Debug.WriteLine(DateTime.Now - start);
            start = DateTime.Now;

            List <Color> pixels = new List <Color>(data.Length / 3);

            if (image.Format == PixelFormats.Bgr24)
            {
                for (int i = 0; i < data.Length; i += 3)
                {
                    pixels.Add(Color.FromRgb(data[i + 2], data[i + 1], data[i]));
                }
            }
            else if (image.Format == PixelFormats.Bgr32)
            {
                for (int i = 0; i < data.Length; i += 4)
                {
                    pixels.Add(Color.FromRgb(data[i + 2], data[i + 1], data[i]));
                }
            }
            else if (image.Format == PixelFormats.Rgb24)
            {
                for (int i = 0; i < data.Length; i += 3)
                {
                    pixels.Add(Color.FromRgb(data[i], data[i + 1], data[i + 2]));
                }
            }


            if (pixels.Count != 0)
            {
                Random rand = new Random((int)DateTime.Now.Ticks);
                _clusterSet = new List <ColorCluster>(10);
                for (int i = 0; i < 10; i++)
                {
                    _clusterSet.Add(new ColorCluster(pixels.ElementAt(rand.Next(pixels.Count()))));
                }
                ClusterAnalisis <Color, ColorCluster> helper = new ClusterAnalisis <Color, ColorCluster>(pixels, _clusterSet);
                helper.RunAnalysisAsync(4);
                IEnumerable <ColorCluster> main = _clusterSet.OrderBy(c => c.Count).Skip(8).ToArray();
                helper = new ClusterAnalisis <Color, ColorCluster>(pixels, main);
                helper.RunAnalysisAsync(4);
                _clusterSet = main.ToList();

                Debug.WriteLine(DateTime.Now - start);
                start = DateTime.Now;

                return(new SolidColorBrush(GetMainColor()));
            }
            else
            {
                return(Brushes.White);
            }
        }
Пример #30
0
        private void UIElement_OnDrop(object sender, DragEventArgs e)
        {
            // Check if the currently dragged item is already on the grid
            if (!OnGridCollection.ContainsValue(currentDraggedItem) && !OnGridIds.Contains(currentDraggedItem.Id))
            {
                base.OnDrop(e);
                if (currentDraggedItem != null)
                {
                    //if (((Canvas)sender).Resources["taken"] == null)
                    if (((Canvas)sender).Background.Equals(Brushes.White))
                    {
                        // Create image from currently dragged item
                        BitmapImage logo = new BitmapImage();
                        logo.BeginInit();
                        logo.UriSource = new Uri(currentDraggedItem.Type.IMG_URL, UriKind.RelativeOrAbsolute);
                        logo.EndInit();

                        // Set the target canvas background
                        ((Canvas)sender).Background = new ImageBrush(logo);
                        if (currentDraggedItem.Type.NAME == "IA")
                        {
                            if (currentDraggedItem.Value > 15000)
                            {
                                ((Canvas)(((Canvas)sender).Children[2])).Background = Brushes.Red;
                            }
                            else
                            {
                                ((Canvas)(((Canvas)sender).Children[2])).Background = Brushes.Transparent;
                            }
                        }
                        else
                        {
                            if (currentDraggedItem.Value > 7000)
                            {
                                ((Canvas)(((Canvas)sender).Children[2])).Background = Brushes.Red;
                            }
                            else
                            {
                                ((Canvas)(((Canvas)sender).Children[2])).Background = Brushes.Transparent;
                            }
                        }

                        // Set partial data for the correct TextBlock under the Canvas
                        ((TextBox)((Canvas)sender).Children[1]).Text = currentDraggedItem.ToString();

                        ((Canvas)sender).Resources.Add("taken", true);

                        OnGridIds.Add(currentDraggedItem.Id);
                        OnGridCollection.Add(((Canvas)sender).Name, currentDraggedItem);
                    }

                    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                    // This code (with help of "GetFrameworkElementByName") gets the current selected item in the listview,
                    // extracts the data template of the particular listview item and then gets the control that is the main element of the data template
                    ListViewItem item = ListViewName.ItemContainerGenerator.ContainerFromIndex(ListViewName.SelectedIndex) as ListViewItem;

                    Grid g = null;

                    if (item != null)
                    {
                        ContentPresenter templateParent = GetFrameworkElementByName <ContentPresenter>(item);

                        DataTemplate dataTemplate = ListViewName.ItemTemplate;

                        if (dataTemplate != null && templateParent != null)
                        {
                            g = dataTemplate.FindName("ListViewItemGrid", templateParent) as Grid;
                        }

                        g.Cursor = Cursors.No;
                        ((Canvas)g.Children[1]).Background = Brushes.LightGray;
                        if (!ListOfDisabledGrids.ContainsValue(g))
                        {
                            ListOfDisabledGrids.Remove(((Canvas)sender).Name);      // Since we care only about the grid, we need to delete the grid item with current key
                            ListOfDisabledGrids.Add(((Canvas)sender).Name, g);      // And add it back again with a different key
                        }
                    }
                    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

                    ListViewName.SelectedItem = null;
                    dragging = false;
                }
                e.Handled = true;
            }
        }
Пример #31
0
        /// <summary>
        /// get the google big image and extracted kq tile image by level-X-Y
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void start_lxy_Click(object sender, RoutedEventArgs e)
        {
            int level = 0, x = 0, y = 0;

            if (!(int.TryParse(Signal_L.Text, out level)) || !(int.TryParse(Signal_X.Text, out x)) || !(int.TryParse(Signal_Y.Text, out y)))
            {
                StatusLable.Content = "Try to enter anther valuable L-X-Y.";
                return;
            }
            string func = this.CBOX.SelectionBoxItem as string;

            if (func == "MongoDB部分转KQDB")
            {
                if (level < 0 || level > 15)
                {
                    StatusLable.Content = "Try to enter anther valuable L.";
                    return;
                }

                int maxX = 5 * (int)Math.Pow(2.0, level);
                int maxY = 10 * (int)Math.Pow(2.0, level);

                if (x >= maxX || y >= maxY || x < 0 || y < 0)
                {
                    StatusLable.Content = "Try to enter anther valuable X-Y.";
                    return;
                }
                Envelope range = new Envelope();

                DBTranslateFactory.GetLonLatBoundByRowCol(level, x, y, ref range);
                BigImage bigimage = await DBTranslateFactory.GetBigImageFromGoogleTile("", level + 5, range.MinX, range.MinY, range.MaxX, range.MaxY);

                byte[] bigimg = null;
                if (bigimage != null && bigimage.BigImg != null)
                {
                    var _TargetMemory = new MemoryStream();
                    bigimage.BigImg.Save(_TargetMemory, ImageFormat.Jpeg);
                    bigimage.BigImg.Dispose();
                    bigimage.BigImg = null;
                    bigimg          = _TargetMemory.GetBuffer();
                }
                else
                {
                    StatusLable.Content = "Can not find tile data in google database.";
                    return;
                }

                if (!(bigimg == null))
                {
                    BitmapImage imgSource = new BitmapImage();
                    imgSource.BeginInit();
                    imgSource.StreamSource = new MemoryStream(bigimg);
                    imgSource.EndInit();
                    bigiamgebox.Source = imgSource;
                }

                GoogleLbel.Visibility = Visibility.Visible;

                byte[] image = await DBTranslateFactory.GetKQTileImageBuffer("", level, x, y);

                if (!(image == null))
                {
                    BitmapImage imgSource = new BitmapImage();
                    imgSource.BeginInit();
                    imgSource.StreamSource = new MemoryStream(image);
                    imgSource.EndInit();
                    imagebox.Source = imgSource;
                }
                else
                {
                    StatusLable.Content = "Convert big image to KongQing tile image failed.";
                }
            }

            if (func == "MongoDB提取图片文件")
            {
                string key = string.Format("{0}-{1}-{2}", level, x, y);
                if (DBTranslateFactory.DBReaderHelper != null)
                {
                    try
                    {
                        byte[] buffer = await DBTranslateFactory.DBReaderHelper.GetTiled(key);

                        if (buffer != null)
                        {
                            BitmapImage imgSource = new BitmapImage();
                            imgSource.BeginInit();
                            imgSource.StreamSource = new MemoryStream(buffer);
                            imgSource.EndInit();
                            imagebox.Source = imgSource;
                        }
                        else
                        {
                            StatusLable.Content = "Can not find tile data in google database";
                        }
                    }
                    catch (Exception ex)
                    {
                        StatusLable.Content = ex.Message;
                    }
                }
            }


            imagebox.Visibility    = Visibility.Visible;
            bigiamgebox.Visibility = Visibility.Visible;

            ProgressInfo.Visibility  = Visibility.Hidden;
            ProgressLabel.Visibility = Visibility.Hidden;

            KQLable.Visibility = Visibility.Visible;
        }
Пример #32
0
        // Since we can't save the latest state of the grid because the view always recreates whenever we navigate to it,
        // we manually refresh it's state
        private void SetGrid()
        {
            Dictionary <string, Road> Temp = new Dictionary <string, Road>();

            foreach (var el in OnGridCollection)
            {
                foreach (var r in RoadsObs.Instance.Roads)
                {
                    if (el.Value.Id == r.Id)
                    {
                        Temp.Add(el.Key, el.Value);
                        break;
                    }
                }
            }
            OnGridCollection = Temp;


            foreach (var el in OnGridCollection)
            {
                foreach (Canvas can in ListOfCanvases)
                {
                    if (el.Key == can.Name)
                    {
                        BitmapImage logo = new BitmapImage();
                        logo.BeginInit();
                        logo.UriSource = new Uri(el.Value.Type.IMG_URL, UriKind.RelativeOrAbsolute);
                        logo.EndInit();

                        // Set the target canvas background
                        can.Background = new ImageBrush(logo);

                        if (el.Value.Type.NAME == "IA")
                        {
                            if (el.Value.Value > 15000)
                            {
                                ((Canvas)(can.Children[2])).Background = Brushes.Red;
                            }
                            else
                            {
                                ((Canvas)(can.Children[2])).Background = Brushes.Transparent;
                            }
                        }
                        else
                        {
                            if (el.Value.Value > 7000)
                            {
                                ((Canvas)(can.Children[2])).Background = Brushes.Red;
                            }
                            else
                            {
                                ((Canvas)(can.Children[2])).Background = Brushes.Transparent;
                            }
                        }

                        ((TextBox)can.Children[1]).Text = el.Value.ToString();

                        if (!OnGridIds.Contains(el.Value.Id))
                        {
                            OnGridIds.Add(el.Value.Id);
                        }
                    }
                }
            }
        }
Пример #33
0
        private void SetupHeadlines()
        {
            try
            {
                _bannerChangeTimer?.Stop();

                _headlines = Headlines.Get(_game);

                _bannerBitmaps = new BitmapImage[_headlines.Banner.Length];
                for (var i = 0; i < _headlines.Banner.Length; i++)
                {
                    var imageBytes = _game.DownloadAsLauncher(_headlines.Banner[i].LsbBanner.ToString());

                    using (var stream = new MemoryStream(imageBytes))
                    {
                        var bitmapImage = new BitmapImage();
                        bitmapImage.BeginInit();
                        bitmapImage.StreamSource = stream;
                        bitmapImage.CacheOption  = BitmapCacheOption.OnLoad;
                        bitmapImage.EndInit();
                        bitmapImage.Freeze();

                        _bannerBitmaps[i] = bitmapImage;
                    }
                }

                Dispatcher.BeginInvoke(new Action(() => { BannerImage.Source = _bannerBitmaps[0]; }));

                _bannerChangeTimer = new Timer {
                    Interval = 5000
                };

                _bannerChangeTimer.Elapsed += (o, args) =>
                {
                    if (_currentBannerIndex + 1 > _headlines.Banner.Length - 1)
                    {
                        _currentBannerIndex = 0;
                    }
                    else
                    {
                        _currentBannerIndex++;
                    }

                    Dispatcher.BeginInvoke(new Action(() =>
                    {
                        BannerImage.Source = _bannerBitmaps[_currentBannerIndex];
                    }));
                };

                _bannerChangeTimer.AutoReset = true;
                _bannerChangeTimer.Start();

                Dispatcher.BeginInvoke(new Action(() => { NewsListView.ItemsSource = _headlines.News; }));
            }
            catch (Exception)
            {
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    NewsListView.Items.Add(new News {
                        Title = "Could not download news data.", Tag = "DlError"
                    });
                }));
            }
        }
Пример #34
0
        /// <summary>
        /// 设置条目到剪切板
        /// </summary>
        /// <param name="result"></param>
        public void SetValueToClipboard(ClipModel result)
        {
            IDataObject dataObject;

            if (result.Type == WECHAT_TYPE)
            {
                MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(result.ClipValue));
                dataObject = new DataObject();
                dataObject.SetData(WECHAT_TYPE, ms);
                dataObject.SetData(DataFormats.Text, result.PlainText);
                dataObject.SetData(DataFormats.UnicodeText, result.PlainText);
            }
            else if (result.Type == IMAGE_TYPE)
            {
                byte[]       fileBytes = Convert.FromBase64String(result.ClipValue);
                MemoryStream ms        = new MemoryStream(fileBytes);
                BitmapImage  bitImg    = new BitmapImage();
                bitImg.BeginInit();
                bitImg.StreamSource = ms;
                bitImg.EndInit();


                dataObject = new DataObject();
                dataObject.SetData(DataFormats.Bitmap, bitImg);
                MemoryStream memo  = new MemoryStream(4);
                byte[]       bytes = new byte[] { 5, 0, 0, 0 };
                memo.Write(bytes, 0, bytes.Length);
                dataObject.SetData("Preferred DropEffect", memo);
                if (File.Exists(result.DisplayValue))
                {
                    dataObject.SetData(DataFormats.FileDrop, new string[] { result.DisplayValue });
                }
            }
            else if (result.Type == HTML_TYPE)
            {
                dataObject = new DataObject();
                dataObject.SetData(DataFormats.Html, result.ClipValue);
                dataObject.SetData(DataFormats.Text, result.PlainText);
                dataObject.SetData(DataFormats.UnicodeText, result.PlainText);
            }
            else if (result.Type == QQ_RICH_TYPE)
            {
                MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(result.ClipValue));
                dataObject = new DataObject();
                dataObject.SetData(QQ_RICH_TYPE, ms);
                dataObject.SetData(DataFormats.Text, result.PlainText);
                dataObject.SetData(DataFormats.UnicodeText, result.PlainText);
            }
            else if (result.Type == FILE_TYPE)
            {
                string[] tmp = result.ClipValue.Split(',');
                dataObject = new DataObject(DataFormats.FileDrop, tmp);
                MemoryStream memo  = new MemoryStream(4);
                byte[]       bytes = new byte[] { 5, 0, 0, 0 };
                memo.Write(bytes, 0, bytes.Length);
                dataObject.SetData("Preferred DropEffect", memo);
            }
            else
            {
                dataObject = new DataObject(DataFormats.Text, result.ClipValue);
            }
            try {
                //当有其他进程占用剪切板时,WPF的Clipboard会有BUG,winform的没有,所以暂时用winform的
                //System.Windows.Forms.Clipboard.SetDataObject(dataObject, true);
                Clipboard.SetDataObject(dataObject, true);
            }
            catch (Exception e)
            {
                Trace.WriteLine(e.Message);
            }
        }
Пример #35
0
        private async Task <PhotographerInfo> GetPhotographerAsync(int guideId)
        {
            var tokenResponse = await tokenClient.RequestRefreshTokenAsync(ConfigurationManager.AppSettings["refreshToken"]);

            var httpClient = new HttpClient
            {
                BaseAddress = new Uri(ConfigurationManager.AppSettings["userManagementBaseUri"])
            };

            httpClient.SetBearerToken(tokenResponse.AccessToken);

            var httpResponse = await httpClient.GetAsync($"api/Photographer/{guideId}");

            var content = httpResponse.Content;

            var photographerJson = await content.ReadAsStringAsync();

            var photographer = JsonConvert.DeserializeObject <Photographer>(photographerJson);

            var camera = new CameraInfo
            {
                Id             = photographer.Camera.Id,
                IsProfessional = photographer.Camera.IsProfessional,
                Model          = photographer.Camera.Model
            };

            var photographerInfo = new PhotographerInfo
            {
                Id                    = photographer.Id,
                FirstName             = photographer.FirstName,
                LastName              = photographer.LastName,
                DateOfBirth           = photographer.DateOfBirth,
                KnowledgeOfLanguages  = photographer.KnowledgeOfLanguages,
                Email                 = photographer.Email,
                Gender                = photographer.Gender,
                NumberOfAppraisers    = photographer.NumberOfAppraisers,
                PhoneNumber           = photographer.PhoneNumber,
                Rating                = photographer.Rating,
                WorkExperience        = photographer.WorkExperience,
                Profession            = photographer.Profession,
                HasCameraStabilizator = photographer.HasCameraStabilizator,
                HasDron               = photographer.HasDron,
                HasGopro              = photographer.HasGopro,
                Camera                = camera
            };

            if (photographerInfo.Image != null)
            {
                photographerInfo.Image = ImageConverter.ConvertImageToImageSource(photographer.Image);
            }
            else
            {
                BitmapImage img = new BitmapImage();
                img.BeginInit();
                if (photographerInfo.Gender == "Female")
                {
                    img.UriSource = new Uri(@"pack://*****:*****@"pack://application:,,,/Kanch;component/Images/male.jpg");
                }
                img.EndInit();
                photographerInfo.Image = img;
            }

            return(photographerInfo);
        }
        /// <summary>
        /// Adds an image to the control's image list
        /// </summary>
        /// <param name="img">The image to be added</param>
        /// <param name="arrange">If true, the ArrangePics method is called</param>
        /// <returns>Returns true if the image was successfully added</returns>
        public bool AddImage(ImageData img, bool arrange = true)
        {
            if (this.images.ContainsKey(img) || !File.Exists(img.path))
            {
                return(false);
            }

            Image pic = new Image();

            pic.Stretch             = System.Windows.Media.Stretch.Uniform;
            pic.HorizontalAlignment = HorizontalAlignment.Left;
            pic.VerticalAlignment   = VerticalAlignment.Top;
            pic.Height = this._thumbSize.Height;
            pic.Width  = this._thumbSize.Width;
            pic.Tag    = img.path;

            StringBuilder tags = new StringBuilder();

            foreach (string tag in img.tags)
            {
                if (tags.Length > 0)
                {
                    tags.Append(", ");
                }

                tags.Append(tag);
            }

            pic.ToolTip = String.Format("Path: {0}\nDimensions: {1}x{2}\nSize: {3} MB\nTags: {4}", img.path, img.width, img.height, (double)img.size / 1024.0 / 1024.0, tags.ToString());

            pic.MouseLeftButtonDown += Pic_MouseLeftButtonDown;
            ContextMenu cMenu = new ContextMenu();
            MenuItem    itemEdit = new MenuItem(), itemDelete = new MenuItem();

            itemEdit.Header   = "Edit"; itemEdit.Click += Pic_Edit; itemEdit.Tag = img.path;
            itemDelete.Header = "Delete"; itemDelete.Click += Pic_Delete; itemDelete.Tag = img.path;
            cMenu.Items.Add(itemEdit);
            cMenu.Items.Add(itemDelete);
            pic.ContextMenu = cMenu;

            string thumbnail;

            if (img.thumbnailMD5 == null || !File.Exists(thumbnail = Thumbnails.GetThumbnailPath(img.thumbnailMD5)))
            {
                string md5 = Thumbnails.KeyFromPath(img.path);

                if (md5 == null || !File.Exists(thumbnail = Thumbnails.GetThumbnailPath(md5)))
                {
                    thumbnail = Thumbnails.GetThumbnailPath(Thumbnails.Add(img.path));
                }
            }

            BitmapImage image = new BitmapImage();

            image.BeginInit();
            image.CacheOption = BitmapCacheOption.OnLoad;
            image.UriSource   = new Uri(Path.GetFullPath(thumbnail));
            image.EndInit();
            pic.Source = image;

            this.images.Add(img, pic);
            this.panel.Children.Add(pic);

            if (arrange)
            {
                ArrangePics();
            }

            return(true);
        }
 /// <summary>
 /// Gets a tile from a compact cache.
 /// </summary>
 /// <param name="level">The level.</param>
 /// <param name="row">The row.</param>
 /// <param name="col">The col.</param>
 /// <param name="onComplete">The on complete.</param>
 private void GetCompactTile(int level, int row, int col, Action<ImageSource> onComplete)
 {
     Action<byte[]> complete = delegate(byte[] tileData)
     {
         if (tileData == null)
             onComplete(null);
         else
         {
             BitmapImage bmi = new BitmapImage();
             bmi.BeginInit();
             MemoryStream ms = new MemoryStream(tileData);
             bmi.StreamSource = ms;
             bmi.EndInit();
             onComplete(bmi);
         }
     };
     System.Threading.ThreadPool.QueueUserWorkItem(delegate(object state)
     {
         Action<byte[]> callback = (Action<byte[]>)state;
         var tileData = CacheSource.GetTile(level, row, col, packetSize, TileCacheFilePath);
         Dispatcher.BeginInvoke((Action)delegate() { callback(tileData); });
     }, complete);
 }
Пример #38
0
        /// <summary>
        /// Loads the data from an image stream and returns a new WriteableBitmap.
        /// </summary>
        /// <param name="stream">The stream with the image data.</param>
        /// <returns>A new WriteableBitmap containing the pixel data.</returns>
        public static WriteableBitmap FromStream(Stream stream)
        {
            var bmpi = new BitmapImage();
#if SILVERLIGHT
            bmpi.SetSource(stream);
            bmpi.CreateOptions = BitmapCreateOptions.None;
#elif WPF
            bmpi.BeginInit();
            bmpi.CreateOptions = BitmapCreateOptions.None;
            bmpi.StreamSource = stream;
            bmpi.EndInit();
#endif
            var bmp = new WriteableBitmap(bmpi);
            bmpi.UriSource = null;
            return bmp;
        }