Exemple #1
0
    public void ToPng(string path, Wpf.CartesianChart.GanttChart.GanttExample gantt)
    {
        var encoder = new PngBitmapEncoder();

        EncodeVisual(gantt, path, encoder);
    }
Exemple #2
0
        private void EncryptButton_Click(object sender, RoutedEventArgs e)
        {
            byte[] inputByteArray = ConvertToByteArray(InputTextBox.Text.Length + "<!>" + InputTextBox.Text, Encoding.UTF8);
            Console.WriteLine(InputTextBox.Text.Length + "<!>" + InputTextBox.Text);
            Console.WriteLine(inputByteArray.Length);
            WriteableBitmap writeableBitmap = new WriteableBitmap(bitmap);

            int width  = writeableBitmap.PixelWidth;
            int height = writeableBitmap.PixelHeight;
            var stride = width * 4;

            var pixels = new byte[height * stride];

            writeableBitmap.CopyPixels(pixels, stride, 0);

            int imgByte = 0;

            for (int i = 0; i < inputByteArray.Length; i++)
            {
                for (int j = 7; j >= 0; j--)
                {
                    Boolean bit = (inputByteArray[i] & (1 << j)) != 0;

                    if (!bit)
                    {
                        if (pixels[imgByte] % 2 == 1)
                        {
                            pixels[imgByte]--;
                        }
                    }
                    else
                    {
                        if (pixels[imgByte] % 2 == 0)
                        {
                            pixels[imgByte]++;
                        }
                    }

                    imgByte++;
                }
            }


            /* String output = "";
             * for (int i = 0; i < pixels.Length; i++)
             * {
             *   if ((pixels[i] & 1) == 1)
             *   {
             *       output += "1";
             *   }
             *   else
             *   {
             *       output += "0";
             *   }
             * }
             * byte[] temptab = BinaryStringToByteArray(output);
             *
             * String outputString = Encoding.UTF8.GetString(temptab);
             * Console.WriteLine("wynik: " + outputString);*/

            /*
             * Int32Rect rect = new Int32Rect(0, 0, width, height);
             * writeableBitmap.WritePixels(rect, pixels, stride, 0);
             *
             * ImageInButton.Source = writeableBitmap;
             *
             *
             * bitmap = ConvertWriteableBitmapToBitmapImage(writeableBitmap);*/


            writeableBitmap.WritePixels(new Int32Rect(0, 0, writeableBitmap.PixelWidth, writeableBitmap.PixelHeight),
                                        pixels, writeableBitmap.PixelWidth * writeableBitmap.Format.BitsPerPixel / 8, 0);

            ImageInButton.Source = writeableBitmap;


            bitmap = ConvertWriteableBitmapToBitmapImage(writeableBitmap);



            SaveFileDialog sfd = new SaveFileDialog();

            sfd.Filter = "PNG|*.PNG|BMP|*.BMP|All files (*.*)|*.*";

            if (sfd.ShowDialog() == true)
            {
                if (sfd.FileName.ToLower().Contains("png"))
                {
                    using (FileStream stream5 = new FileStream(sfd.FileName, FileMode.Create))
                    {
                        PngBitmapEncoder encoder5 = new PngBitmapEncoder();
                        encoder5.Frames.Add(BitmapFrame.Create(writeableBitmap));
                        encoder5.Save(stream5);
                    }
                }
                else if (sfd.FileName.ToLower().Contains("bmp"))
                {
                    using (FileStream stream5 = new FileStream(sfd.FileName, FileMode.Create))
                    {
                        BmpBitmapEncoder encoder5 = new BmpBitmapEncoder();
                        encoder5.Frames.Add(BitmapFrame.Create(writeableBitmap));
                        encoder5.Save(stream5);
                    }
                }
            }
        }
Exemple #3
0
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            double totalDolarat = 0;
            double touchDollars = 0, alfaDollars = 0;
            double phone1 = 0, phone2 = 0;
            double savings = 0;
            double jaroor1 = 0;

            DateTime dateSavedImage;

            if (DateTime.Now.Hour < 21)
            {
                dateSavedImage = DateTime.Now.AddDays(-1);
            }
            else
            {
                dateSavedImage = DateTime.Now;
            }

            if (dateSavedImage.DayOfWeek == DayOfWeek.Sunday)
            {
                labelTotal.Foreground = Brushes.DarkGreen;
                labelTotal.FontStyle  = FontStyles.Italic;
            }

            labelDate.Content = string.Format("{0:00}-{1:00}-{2}", dateSavedImage.Day, dateSavedImage.Month, dateSavedImage.Year);

            Task t = Task.Run(() =>
            {
                Excel.Application xlApp      = new Excel.Application();
                Excel.Workbook xlWorkbook    = xlApp.Workbooks.Open(phonesExcelPath);
                Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1];
                Excel.Range xlRange          = xlWorksheet.UsedRange;
                phone2 = xlRange.Cells[25, 4].Value2;

                this.Dispatcher.Invoke(() =>
                {
                    totalDolarat      += phone2;
                    labelTotal.Content = totalDolarat.ToString("C2");
                    status.Content     = "Done";

                    string pathPictureFormat = string.Format("{0}-{1}-{2}", dateSavedImage.Year, dateSavedImage.Month, dateSavedImage.Day);

                    mainGrid.Background = Brushes.White;
                    mainGrid.UpdateLayout();
                    //mainGrid.Measure(new Size(510, 282));
                    //mainGrid.Arrange(new Rect(0, 0, 510, 282));

                    FileStream stream        = new FileStream(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\" + pathPictureFormat + ".png", FileMode.Create);
                    RenderTargetBitmap image = new RenderTargetBitmap(525, 300, 96, 96, PixelFormats.Default);
                    image.Render(mainGrid);

                    BitmapFrame fr = BitmapFrame.Create(image);

                    PngBitmapEncoder encoder = new PngBitmapEncoder();
                    encoder.Frames.Add(fr);
                    encoder.Save(stream);
                    stream.Dispose();
                });

                //cleanup
                GC.Collect();
                GC.WaitForPendingFinalizers();

                //rule of thumb for releasing com objects:
                //  never use two dots, all COM objects must be referenced and released individually
                //  ex: [somthing].[something].[something] is bad

                //release com objects to fully kill excel process from running in the background
                Marshal.ReleaseComObject(xlRange);
                Marshal.ReleaseComObject(xlWorksheet);

                //close and release
                xlWorkbook.Close();
                Marshal.ReleaseComObject(xlWorkbook);

                //quit and release
                xlApp.Quit();
                Marshal.ReleaseComObject(xlApp);
            });

            string          Data = File.ReadAllText(dolaratPath);
            MatchCollection matches;

            matches       = Regex.Matches(Data, @"total   = (\d{1,5}(?:\.\d{1,2})?)", RegexOptions.Singleline);
            totalDolarat  = double.Parse(matches[matches.Count - 1].Groups[1].Value);
            matches       = Regex.Matches(Data, @"(\d{1,4}(?:\.\d{1,2})?)\(MTC\) \+ (\d{1,4}(?:\.\d{1,2})?)\(Alfa\)", RegexOptions.Singleline);
            touchDollars  = double.Parse(matches[matches.Count - 1].Groups[1].Value);
            alfaDollars   = double.Parse(matches[matches.Count - 1].Groups[2].Value);
            totalDolarat -= losses + (touchDollars * touchDifference) + (alfaDollars * alfaDifference);

            Data = File.ReadAllText(phonesTextPath);
            Match mat = Regex.Match(Data, @"\= (\d{3,5}\.?5?)");

            phone1  = double.Parse(mat.Groups[1].Value);
            phone1 /= 1.5;

            Data     = File.ReadAllText(savingPath);
            mat      = Regex.Match(Data, @" (\d{2,4})\+(\d{2,5})\+(\d{2,4})\$");
            savings += double.Parse(mat.Groups[1].Value);
            savings += double.Parse(mat.Groups[2].Value);
            savings += double.Parse(mat.Groups[3].Value);

            //Data = File.ReadAllLines(jaroor1Path).Last();
            //mat = Regex.Match(Data, @"\= (\d{2,4})");
            //jaroor1 = double.Parse(mat.Groups[1].Value);
            //jaroor1 += 40;
            //jaroor1 /= 1.5;


            totalDolarat = totalDolarat + phone1 + savings + jaroor1;

            labelTotal.Content = totalDolarat.ToString("C2");
        }
        static SnapshotDataBase ClipboardDataToSnapshot(IDataObject clipboard, string format, bool isConverted)
        {
            try
            {
                var data = clipboard.GetData(format, false);

                if (data is string)
                {
                    return new SnapshotStringData {
                               Format = format, Data = (string)data, IsConverted = isConverted
                    }
                }
                ;
                if (data is string[])
                {
                    return new SnapshotStringArrayData {
                               Format = format, Data = (string[])data, IsConverted = isConverted
                    }
                }
                ;
                if (data is bool)
                {
                    return new SnapshotBoolData {
                               Format = format, Data = (bool)data, IsConverted = isConverted
                    }
                }
                ;
                if (data is InteropBitmap)
                {
                    var pngStream = new MemoryStream();

                    var encoder = new PngBitmapEncoder();
                    encoder.Frames.Add(BitmapFrame.Create(data as InteropBitmap));
                    encoder.Save(pngStream);
                    return(new SnapshotBitmapData {
                        Format = format, Data = pngStream.ToArray(), IsConverted = isConverted
                    });
                }
                if (data is System.Drawing.Bitmap)
                {
                    var bitmap    = (System.Drawing.Bitmap)data;
                    var pngStream = new MemoryStream();
                    bitmap.Save(pngStream, bitmap.RawFormat);
                    return(new SnapshotBitmapDrawingData {
                        Format = format, Data = pngStream.ToArray(), IsConverted = isConverted
                    });
                }
                if (data is MemoryStream)
                {
                    var mem = ((MemoryStream)data);
                    if (mem.Length > 1024 * 1024 * 10)
                    {
                        return new SnapshotRawData {
                                   Format = format, IsConverted = isConverted
                        }
                    }
                    ;
                    return(new SnapshotRawData {
                        Format = format, Data = mem.ToArray(), IsConverted = isConverted
                    });
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debugger.Break();
            }

            return(new SnapshotNullData {
                Format = format, IsConverted = isConverted
            });
        }
Exemple #5
0
        // https://blogs.msdn.microsoft.com/kirillosenkov/2009/10/12/saving-images-bmp-png-etc-in-wpfsilverlight/
        void SaveToPng(FrameworkElement visual, string fileName)
        {
            var encoder = new PngBitmapEncoder( );

            SaveUsingEncoder(visual, fileName, encoder);
        }
Exemple #6
0
        static void Main(string[] args)
        {
            try
            {
                var options = new Options();
                if (!CommandLine.Parser.Default.ParseArguments(args, options))
                {
                    return;
                }

                var start = DateTime.Now;

                var staticDataFileInfo = new FileInfo(Assembly.GetExecutingAssembly().Location);

                string staticDataFilename = Path.Combine(staticDataFileInfo.DirectoryName, "tiles.xml");

                Console.WriteLine("Reading static data...");

                var world = new World();

                world.StaticData = StaticData.Read(staticDataFilename);

                var objectTypesToHighlight = GetObjectTypesToHighlight(world, options);

                Console.WriteLine("Reading world...");

                world.Read(options.InputFile);

                Console.WriteLine("Read {0} tiles", world.TotalTileCount);

                Console.WriteLine("Writing image data...");

                var pixelFormat = PixelFormats.Bgr32;

                var width      = world.WorldWidthinTiles;
                var height     = world.WorldHeightinTiles;
                var stride     = (width * pixelFormat.BitsPerPixel + 7) / 8;
                var pixels     = new byte[stride * height];
                var maskPixels = new byte[stride * height];

                var writeableBitmap = new WriteableBitmap(width, height, 96, 96, pixelFormat, null);

                world.WritePixelData(pixels, stride);

                Int32Rect rect;

                while (world.UpdatedRectangles.TryDequeue(out rect))
                {
                    var offset = rect.Y * width * 4;

                    writeableBitmap.WritePixels(rect, pixels, stride, offset);
                }

                if (objectTypesToHighlight.Count > 0)
                {
                    Console.WriteLine("Writing selected item mask data...");

                    world.WritePixelData(maskPixels, stride, objectTypesToHighlight);

                    var maskWriteableBitmap = new WriteableBitmap(width, height, 96, 96, pixelFormat, null);

                    while (world.UpdatedRectangles.TryDequeue(out rect))
                    {
                        var offset = rect.Y * width * 4;

                        maskWriteableBitmap.WritePixels(rect, maskPixels, stride, offset);
                    }

                    var destRect = new Rect(0, 0, width, height);
                    var point    = new Point(0, 0);

                    byte alpha = (byte)(255 * 0.75);

                    maskWriteableBitmap.ForEach((x, y, color) =>
                    {
                        if (color == Colors.Black)
                        {
                            return(Color.FromArgb(alpha, color.R, color.G, color.B));
                        }
                        else
                        {
                            return(color);
                        }
                    });

                    writeableBitmap.Blit(destRect, maskWriteableBitmap, destRect, WriteableBitmapExtensions.BlendMode.Alpha);
                }

                Console.WriteLine("Writing image file...");

                using (var stream = new FileStream(options.OutputFile, FileMode.Create))
                {
                    var encoder = new PngBitmapEncoder();
                    encoder.Frames.Add(BitmapFrame.Create(writeableBitmap));
                    encoder.Save(stream);
                    stream.Close();
                }

                var elapsed = DateTime.Now - start;

                world.Status = "Successfully wrote image in " + elapsed;
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
                Console.Error.WriteLine(ex);
            }
        }
Exemple #7
0
        public static IntPtr GenerateHICON(ImageSource image, Size dimensions)
        {
            IntPtr ptr3;

            if (image == null)
            {
                return(IntPtr.Zero);
            }
            BitmapFrame item = image as BitmapFrame;

            if (item != null)
            {
                item = GetBestMatch(item.Decoder.Frames, (int)dimensions.Width, (int)dimensions.Height);
            }
            else
            {
                Rect   rectangle = new Rect(0.0, 0.0, dimensions.Width, dimensions.Height);
                double num       = dimensions.Width / dimensions.Height;
                double num2      = image.Width / image.Height;
                if ((image.Width <= dimensions.Width) && (image.Height <= dimensions.Height))
                {
                    rectangle = new Rect((dimensions.Width - image.Width) / 2.0, (dimensions.Height - image.Height) / 2.0, image.Width, image.Height);
                }
                else if (num > num2)
                {
                    double width = (image.Width / image.Height) * dimensions.Width;
                    rectangle = new Rect((dimensions.Width - width) / 2.0, 0.0, width, dimensions.Height);
                }
                else if (num < num2)
                {
                    double height = (image.Height / image.Width) * dimensions.Height;
                    rectangle = new Rect(0.0, (dimensions.Height - height) / 2.0, dimensions.Width, height);
                }
                DrawingVisual  visual  = new DrawingVisual();
                DrawingContext context = visual.RenderOpen();
                context.DrawImage(image, rectangle);
                context.Close();
                RenderTargetBitmap source = new RenderTargetBitmap((int)dimensions.Width, (int)dimensions.Height, 96.0, 96.0, PixelFormats.Pbgra32);
                source.Render(visual);
                item = BitmapFrame.Create(source);
            }
            using (MemoryStream stream = new MemoryStream())
            {
                BitmapEncoder encoder = new PngBitmapEncoder();
                encoder.Frames.Add(item);
                encoder.Save(stream);
                using (ManagedIStream stream2 = new ManagedIStream(stream))
                {
                    IntPtr zero = IntPtr.Zero;
                    try
                    {
                        IntPtr ptr2;
                        if (Standard.NativeMethods.GdipCreateBitmapFromStream(stream2, out zero) != Standard.Status.Ok)
                        {
                            return(IntPtr.Zero);
                        }
                        if (Standard.NativeMethods.GdipCreateHICONFromBitmap(zero, out ptr2) != Standard.Status.Ok)
                        {
                            return(IntPtr.Zero);
                        }
                        ptr3 = ptr2;
                    }
                    finally
                    {
                        SafeDisposeImage(ref zero);
                    }
                }
            }
            return(ptr3);
        }
        private void _encodeText(object sender, RoutedEventArgs e)
        {
            if (imgInput.Source != null && textBlock.Text != null)
            {
                BitmapImage imgToEncode = imgInput.Source as BitmapImage;
                byte[]      imgInBytes  = imgToByteArray(imgToEncode);

                //Password = "******" == 01000101 01101110 01100011 01101111 01100100 01100101 01100100
                string password     = "******";
                string textToEncode = password + textBlock.Text.ToString();
                byte[] textInBytes  = Encoding.UTF8.GetBytes(textToEncode);

                int offset           = 0;
                int codingNumber     = (int)decodeBitsSlider.Value;
                int codingModulator  = 0;
                int lengthMultiplier = 0;

                switch (codingNumber)
                {
                case 1:
                    codingModulator  = 2;
                    lengthMultiplier = 32;
                    break;

                case 2:
                    codingModulator  = 4;
                    lengthMultiplier = 16;
                    break;

                case 4:
                    codingModulator  = 16;
                    lengthMultiplier = 4;
                    break;

                case 8:
                    codingModulator  = 256;
                    lengthMultiplier = 2;
                    break;
                }

                if (imgInBytes.Length > textInBytes.Length * lengthMultiplier)
                {
                    for (int i = 0; i < textInBytes.Length; i++)
                    {
                        //Skip 4th byte to skip Alpha channel
                        if (offset % 4 == 3)
                        {
                            offset++;
                        }

                        int holdTextByteAsInt = textInBytes[i];
                        if (holdTextByteAsInt != 0)
                        {
                            for (int j = 0; j < 8; j += codingNumber)
                            {
                                int holdImgByteAsInt = imgInBytes[offset];

                                //0 last N bits
                                holdImgByteAsInt -= holdImgByteAsInt % codingModulator;

                                //Add N text bits
                                holdImgByteAsInt  += holdTextByteAsInt % codingModulator;
                                holdTextByteAsInt /= codingModulator;

                                //Replace until 0
                                imgInBytes[offset] = (byte)holdImgByteAsInt;
                                textInBytes[i]     = (byte)holdTextByteAsInt;

                                offset++;
                                //Skip 4th byte to skip Alpha channel
                                if (offset % 4 == 3)
                                {
                                    offset++;
                                }
                            }
                        }
                    }
                    //Set stop byte
                    imgInBytes[offset] = 30;

                    BitmapSource imgToSave = byteArrayToImg(imgToEncode, imgInBytes);
                    imgOutput.Source = imgToSave;

                    //Save image to path of .exe as output.png
                    //C:\Users\Krzysiek\source\repos\steganografia\steganografia\bin\Debug
                    using (var fileStream = new FileStream("output.jpg", FileMode.Create))
                    {
                        BitmapEncoder encoder = new PngBitmapEncoder();
                        encoder.Frames.Add(BitmapFrame.Create(imgToSave));
                        encoder.Save(fileStream);
                    }
                }
                else
                {
                    MessageBox.Show("The text file is too big for this image. Try a bigger encoding number or another image!", "Error!");
                }
            }
            else
            {
                MessageBox.Show("There is no image or text file loaded. Did you forget about those?", "Error!");
            }
        }
Exemple #9
0
        private void ExportToImage_Click(object sender, RoutedEventArgs e)
        {
            if (SelectedPosition >= 0)
            {
                SaveCanvas();
                LoadCanvas();

                if (((FrameworkElement)sender).Tag.ToString() == "OnePng")
                {
                    SaveFileDialog saveFileDialog = new SaveFileDialog();
                    saveFileDialog.Filter   = Strings.ResStrings.Image + " (*.png) | *.png|" + Strings.ResStrings.AllFiles + "| *.*";
                    saveFileDialog.FileName = "GoodTeacher_" + SelectedPosition + ".png";
                    if (saveFileDialog.ShowDialog() == true)
                    {
                        Canvas can = CanvasSaveLoad.LoadSpecificCanvas(data, SelectedPosition);
                        CanvasSaveLoad.ToPresentationMode(can);
                        CanvasSaveLoad.SimulateCanvas(can);
                        BitmapSource bs = (BitmapSource) new ImageSourceConverter().ConvertFrom(CanvasWriter.SaveCanvasToImgSimulateFullPng(can));

                        BitmapEncoder encoder = new PngBitmapEncoder();
                        encoder.Frames.Add(BitmapFrame.Create(bs));

                        using (var fileStream = new System.IO.FileStream(saveFileDialog.FileName, System.IO.FileMode.Create))
                        {
                            encoder.Save(fileStream);
                        }
                        ShowNotification(Strings.ResStrings.Exported);
                    }
                }
                else if (((FrameworkElement)sender).Tag.ToString() == "OneJpg")
                {
                    SaveFileDialog saveFileDialog = new SaveFileDialog();
                    saveFileDialog.Filter   = Strings.ResStrings.Image + " (*.jpg) | *.jpg|" + Strings.ResStrings.AllFiles + "| *.*";
                    saveFileDialog.FileName = "GoodTeacher_" + SelectedPosition + ".jpg";
                    if (saveFileDialog.ShowDialog() == true)
                    {
                        Canvas can = CanvasSaveLoad.LoadSpecificCanvas(data, SelectedPosition);
                        CanvasSaveLoad.ToPresentationMode(can);
                        CanvasSaveLoad.SimulateCanvas(can);
                        BitmapSource bs = (BitmapSource) new ImageSourceConverter().ConvertFrom(CanvasWriter.SaveCanvasToImgSimulateFullJpg(can));

                        BitmapEncoder encoder = new PngBitmapEncoder();
                        encoder.Frames.Add(BitmapFrame.Create(bs));

                        using (var fileStream = new System.IO.FileStream(saveFileDialog.FileName, System.IO.FileMode.Create))
                        {
                            encoder.Save(fileStream);
                        }
                        ShowNotification(Strings.ResStrings.Exported);
                    }
                }
                else if (((FrameworkElement)sender).Tag.ToString() == "AllPng")
                {
                    System.Windows.Forms.FolderBrowserDialog folderBrowserDialog = new System.Windows.Forms.FolderBrowserDialog();
                    folderBrowserDialog.ShowNewFolderButton = true;
                    folderBrowserDialog.Description         = Strings.ResStrings.ExportToAllImages;
                    if (folderBrowserDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                    {
                        for (int i = 0; i < data.pages.Count; i++)
                        {
                            Canvas can = CanvasSaveLoad.LoadSpecificCanvas(data, i);
                            CanvasSaveLoad.ToPresentationMode(can);
                            CanvasSaveLoad.SimulateCanvas(can);
                            BitmapSource bs = (BitmapSource) new ImageSourceConverter().ConvertFrom(CanvasWriter.SaveCanvasToImgSimulateFullPng(can));

                            BitmapEncoder encoder = new PngBitmapEncoder();
                            encoder.Frames.Add(BitmapFrame.Create(bs));

                            if (File.Exists(folderBrowserDialog.SelectedPath + "\\GoodTeacher_" + i + ".png"))
                            {
                                File.Delete(folderBrowserDialog.SelectedPath + "\\GoodTeacher_" + i + ".png");
                            }

                            using (var fileStream = new System.IO.FileStream(folderBrowserDialog.SelectedPath + "\\GoodTeacher_" + i + ".png", System.IO.FileMode.Create))
                            {
                                encoder.Save(fileStream);
                            }
                        }
                        ShowNotification(Strings.ResStrings.Exported);
                    }
                }
                else if (((FrameworkElement)sender).Tag.ToString() == "AllJpg")
                {
                    System.Windows.Forms.FolderBrowserDialog folderBrowserDialog = new System.Windows.Forms.FolderBrowserDialog();
                    folderBrowserDialog.ShowNewFolderButton = true;
                    folderBrowserDialog.Description         = Strings.ResStrings.ExportToAllImages;
                    if (folderBrowserDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                    {
                        for (int i = 0; i < data.pages.Count; i++)
                        {
                            Canvas can = CanvasSaveLoad.LoadSpecificCanvas(data, i);
                            CanvasSaveLoad.ToPresentationMode(can);
                            CanvasSaveLoad.SimulateCanvas(can);
                            BitmapSource bs = (BitmapSource) new ImageSourceConverter().ConvertFrom(CanvasWriter.SaveCanvasToImgSimulateFullJpg(can));

                            BitmapEncoder encoder = new PngBitmapEncoder();
                            encoder.Frames.Add(BitmapFrame.Create(bs));

                            if (File.Exists(folderBrowserDialog.SelectedPath + "\\GoodTeacher_" + i + ".jpg"))
                            {
                                File.Delete(folderBrowserDialog.SelectedPath + "\\GoodTeacher_" + i + ".jpg");
                            }

                            using (var fileStream = new System.IO.FileStream(folderBrowserDialog.SelectedPath + "\\GoodTeacher_" + i + ".jpg", System.IO.FileMode.Create))
                            {
                                encoder.Save(fileStream);
                            }
                        }
                        ShowNotification(Strings.ResStrings.Exported);
                    }
                }
                else if (((FrameworkElement)sender).Tag.ToString() == "OneClipboard")
                {
                    Canvas can = CanvasSaveLoad.LoadSpecificCanvas(data, SelectedPosition);
                    CanvasSaveLoad.ToPresentationMode(can);
                    CanvasSaveLoad.SimulateCanvas(can);
                    BitmapSource bs = (BitmapSource) new ImageSourceConverter().ConvertFrom(CanvasWriter.SaveCanvasToImgSimulateFullPng(can));

                    Clipboard.SetImage(bs);
                    ShowNotification(Strings.ResStrings.CopiedToClipboard);
                }
            }
        }
Exemple #10
0
        /// <summary>
        /// 合成带水印的图片
        /// </summary>
        /// <param name="filePath">原始图片全路径</param>
        /// <param name="watermark">水印内容</param>
        /// <param name="foreground">水印颜色</param>
        /// <param name="rows">水印显示的行数</param>
        /// <param name="columns">水印显示的列数</param>
        /// <param name="fontSize">水印字体大小,该字体大小针对1080p的图片,方法内部会根据图片像素自动设定水印字体大小</param>
        /// <param name="opacity">水印透明度</param>
        /// <param name="angle">水印显示角度</param>
        public static void ScreenshotWithWatermark(string filePath, string watermark, Brush foreground, FontWeight fontWeight, int rows = 3, int columns = 3
                                                   , double fontSize = 36, double opacity = 0.3, double angle = -20)
        {
            BitmapImage bgImage;

            //从流中读取图片,防止出现资源被占用的问题
            using (BinaryReader reader = new BinaryReader(File.Open(filePath, FileMode.Open)))
            {
                FileInfo fi    = new FileInfo(filePath);
                byte[]   bytes = reader.ReadBytes((int)fi.Length);

                bgImage = new BitmapImage();
                bgImage.BeginInit();
                bgImage.StreamSource = new MemoryStream(bytes);
                bgImage.EndInit();
                bgImage.CacheOption = BitmapCacheOption.OnLoad;
            }

            RenderTargetBitmap composeImage = new RenderTargetBitmap(bgImage.PixelWidth, bgImage.PixelHeight, bgImage.DpiX, bgImage.DpiY, PixelFormats.Default);

            fontSize = GetFontSizeByPixel(bgImage.PixelHeight, fontSize);

            //设置水印文字效果:字体、颜色等
            FormattedText signatureTxt = new FormattedText(watermark, CultureInfo.CurrentCulture, FlowDirection.LeftToRight
                                                           , new Typeface(SystemFonts.MessageFontFamily, FontStyles.Normal, fontWeight, FontStretches.Normal), fontSize, foreground);

            DrawingVisual  drawingVisual  = new DrawingVisual();
            DrawingContext drawingContext = drawingVisual.RenderOpen();

            drawingContext.DrawImage(bgImage, new Rect(0, 0, bgImage.Width, bgImage.Height));

            #region 设置水印的旋转角度及透明度,需要在绘制水印文本之前设置,否则不生效
            //x,y为水印旋转的中心点
            double centerX = (bgImage.Width - signatureTxt.Width) / 2;
            double centerY = (bgImage.Height - signatureTxt.Height) / 2;

            //设置水印透明度
            drawingContext.PushOpacity(opacity);
            //设置水印旋转角度
            drawingContext.PushTransform(new RotateTransform(angle, centerX, centerY));
            #endregion

            #region 绘制全屏水印
            double intervalX = bgImage.Width / columns; //水印水平间隔
            double intervalY = bgImage.Height / rows;   //水印垂直间隔

            //水印绘制方向:从上往下,再从左到右
            for (double i = 0; i < bgImage.Width; i += intervalX)
            {
                for (double j = 0; j < bgImage.Height + intervalY; j += intervalY)
                {
                    //奇偶行间隔绘制水印
                    if ((j / intervalY) % 2 == 0)
                    {
                        drawingContext.DrawText(signatureTxt, new Point(i, j));
                    }
                    else
                    {
                        drawingContext.DrawText(signatureTxt, new Point(i + intervalX / 2, j));
                    }
                }
            }
            #endregion

            drawingContext.Close();

            composeImage.Render(drawingVisual);

            PngBitmapEncoder bitmapEncoder = new PngBitmapEncoder();
            bitmapEncoder.Frames.Add(BitmapFrame.Create(composeImage));

            //删除VLC生成的原始截图
            File.Delete(filePath);

            //将合成水印的截图保存到本地
            using (Stream stream = File.OpenWrite(filePath))
            {
                bitmapEncoder.Save(stream);
            }
            bgImage = null;
        }
Exemple #11
0
        public static async Task DownloadReadme(ReadmeService readmeService, string modPath, string readmeUrl, BitmapImage icon)
        {
            var readmeModel = await readmeService.DownloadReadme(readmeUrl);

            File.WriteAllText(Path.Combine(modPath, "README.md"), readmeModel.Readme);

            // if there are images in readme, saving them to cache
            if (readmeModel.Images.Count > 0)
            {
                var cachePath = Path.Combine(modPath, ".cache");
                var indexPath = Path.Combine(cachePath, "index.json");

                // create cache dir if missing
                if (!Directory.Exists(cachePath))
                {
                    Directory.CreateDirectory(cachePath);
                }

                // read existing index
                ReadmeIndex index = new();
                if (File.Exists(indexPath))
                {
                    index = JsonConvert.DeserializeObject <ReadmeIndex>(File.ReadAllText(indexPath));
                }
                index.Source = readmeUrl;

                var previousImages = index.Images.ToDictionary(kv => kv.Key, kv => kv.Value);

                // saving downloaded images to cache
                foreach (var kv in readmeModel.Images)
                {
                    var cacheKey = $"{Guid.NewGuid()}{Path.GetExtension(kv.Key)}";
                    var fileName = Path.Combine(cachePath, cacheKey);
                    File.WriteAllBytes(fileName, kv.Value);
                    index.Images[kv.Key] = cacheKey;
                }

                // save icon
                if (icon != null)
                {
                    var encoder = new PngBitmapEncoder();
                    encoder.Frames.Add(BitmapFrame.Create(icon));

                    var iconPath = Path.Combine(cachePath, "icon.png");
                    using var fs = File.OpenWrite(iconPath);
                    encoder.Save(fs);
                }

                // writing result index
                File.WriteAllText(indexPath, JsonConvert.SerializeObject(index, Formatting.Indented));

                // removing old images
                foreach (var kv in previousImages)
                {
                    if (index.Images.ContainsKey(kv.Key))
                    {
                        continue;
                    }

                    var path = Path.Combine(cachePath, kv.Value);
                    if (File.Exists(path))
                    {
                        File.Delete(path);
                    }
                }
            }
        }
        /// <summary>
        /// Combines the images to one big image.
        /// </summary>
        /// <param name="infos">Tuple containing the image
        /// and text to stitch together.</param>
        /// <returns>Task.</returns>
        private async Task <PngBitmapEncoder> StitchImagesTogether(List <Tuple <Uri, string> > infos)
        {
            BitmapFrame[] frames = new BitmapFrame[infos.Count];
            for (int i = 0; i < frames.Length; i++)
            {
                frames[i] = BitmapDecoder.Create(infos[i].Item1 ?? (SelectedCollageType == CollageType.Albums ? new Uri("pack://application:,,,/Resources/noalbumimage.png")
                                                        : new Uri("pack://application:,,,/Resources/noartistimage.png")),
                                                 BitmapCreateOptions.None, BitmapCacheOption.OnDemand).Frames.First();
            }

            OnStatusUpdated("Downloading images...");
            while (frames.Any(f => f.IsDownloading))
            {
                await Task.Delay(100);
            }

            int imageWidth  = frames[0].PixelWidth;
            int imageHeight = frames[0].PixelHeight;

            int collageSize = 0;

            if (SelectedCollageSize == CollageSize.Custom)
            {
                collageSize = CustomCollageSize;
            }
            else
            {
                collageSize = (int)SelectedCollageSize;
            }

            DrawingVisual dv = new DrawingVisual();

            using (DrawingContext dc = dv.RenderOpen())
            {
                int cnt = 0;
                for (int y = 0; y < collageSize; y++)
                {
                    for (int x = 0; x < collageSize; x++)
                    {
                        dc.DrawImage(frames[cnt], new Rect(x * imageWidth, y * imageHeight, imageWidth, imageHeight));

                        if (!string.IsNullOrEmpty(infos[cnt].Item2))
                        {
                            // create text
                            FormattedText extraText = new FormattedText(infos[cnt].Item2, CultureInfo.GetCultureInfo("en-us"), FlowDirection.LeftToRight, new Typeface("Verdana"), 14, Brushes.Black)
                            {
                                MaxTextWidth  = imageWidth,
                                MaxTextHeight = imageHeight
                            };

                            dc.DrawText(extraText, new Point(x * imageWidth + 1, y * imageHeight + 1));
                            extraText.SetForegroundBrush(Brushes.White);
                            dc.DrawText(extraText, new Point(x * imageWidth, y * imageHeight));
                        }

                        cnt++;
                    }
                }
            }

            // Converts the Visual (DrawingVisual) into a BitmapSource
            RenderTargetBitmap bmp = new RenderTargetBitmap(imageWidth * collageSize, imageHeight * collageSize, 96, 96, PixelFormats.Pbgra32);

            bmp.Render(dv);

            // Creates a PngBitmapEncoder and adds the BitmapSource to the frames of the encoder
            PngBitmapEncoder encoder = new PngBitmapEncoder();

            encoder.Frames.Add(BitmapFrame.Create(bmp));

            return(encoder);
        }
        /// <summary>
        /// Creates and uploads a collage of the top <see cref="SelectedCollageType"/>.
        /// </summary>
        public async void CreateCollage()
        {
            EnableControls = false;

            try
            {
                Collage = null;

                int numCollageItems = 0;
                if (SelectedCollageSize == CollageSize.Custom)
                {
                    numCollageItems = CustomCollageSize * CustomCollageSize;
                }
                else
                {
                    numCollageItems = (int)SelectedCollageSize * (int)SelectedCollageSize;
                }
                PngBitmapEncoder collage = null;
                if (SelectedCollageType == CollageType.Artists)
                {
                    OnStatusUpdated("Fetching top artists...");
                    var response = await _userAPI.GetTopArtists(Username, TimeSpan, 1, numCollageItems);

                    if (response.Success && response.Status == LastResponseStatus.Successful)
                    {
                        collage = await StitchImagesTogether(response.Content.Select(a => new Tuple <Uri, string>(a.MainImage.ExtraLarge, CreateArtistText(a))).ToList());
                    }
                    else
                    {
                        OnStatusUpdated(string.Format("Error while fetching top artists: {0}", response.Status));
                    }
                }
                else if (SelectedCollageType == CollageType.Albums)
                {
                    OnStatusUpdated("Fetching top albums...");
                    var response = await _userAPI.GetTopAlbums(Username, TimeSpan, 1, numCollageItems);

                    if (response.Success && response.Status == LastResponseStatus.Successful)
                    {
                        collage = await StitchImagesTogether(response.Content.Select(a => new Tuple <Uri, string>(a.Images.ExtraLarge, CreateAlbumText(a))).ToList());
                    }
                    else
                    {
                        OnStatusUpdated(string.Format("Error while fetching top albums: {0}", response.Status));
                    }
                }

                using (MemoryStream ms = new MemoryStream())
                {
                    collage.Save(ms);
                    ConvertToBitmapImage(ms);

                    if (UploadToWeb)
                    {
                        await UploadImage(ms);
                    }
                };

                OnStatusUpdated("Successfully created collage");
            }
            catch (Exception ex)
            {
                OnStatusUpdated(string.Format("Fatal error while creating collage: {0}", ex.Message));
            }
            finally
            {
                EnableControls = true;
            }
        }
        ConvertTo(
            ITypeDescriptorContext context,
            System.Globalization.CultureInfo culture,
            object value,
            Type destinationType
            )
        {
            string bitmapName = "bitmap" + m_bitmapId;

            BitmapEncoder encoder = null;

            m_bitmapId++;

            BitmapFrame bmpd = value as BitmapFrame;

            if (bmpd != null)
            {
                BitmapCodecInfo codec = null;

                if (bmpd.Decoder != null)
                {
                    codec = bmpd.Decoder.CodecInfo;
                }

                if (codec != null)
                {
                    encoder = BitmapEncoder.Create(codec.ContainerFormat);
                    string extension = "";

                    if (encoder is BmpBitmapEncoder)
                    {
                        extension = "bmp";
                    }
                    else if (encoder is JpegBitmapEncoder)
                    {
                        extension = "jpg";
                    }
                    else if (encoder is PngBitmapEncoder)
                    {
                        extension = "png";
                    }
                    else if (encoder is TiffBitmapEncoder)
                    {
                        extension = "tif";
                    }
                    else
                    {
                        encoder = null;
                    }

                    if (encoder != null)
                    {
                        bitmapName = bitmapName + '.' + extension;
                    }
                }
            }

            if (encoder == null)
            {
                if (Microsoft.Internal.AlphaFlattener.Utility.NeedPremultiplyAlpha(value as BitmapSource))
                {
                    encoder = new WmpBitmapEncoder();

                    bitmapName = bitmapName + ".wmp";
                }
                else
                {
                    encoder = new PngBitmapEncoder();

                    bitmapName = bitmapName + ".png";
                }
            }

            if (value is BitmapFrame)
            {
                encoder.Frames.Add((BitmapFrame)value);
            }
            else
            {
                encoder.Frames.Add(BitmapFrame.Create((BitmapSource)value));
            }

            int index = m_mainFile.LastIndexOf('.');

            if (index < 0)
            {
                index = m_mainFile.Length;
            }

            string uri = m_mainFile.Substring(0, index) + "_" + bitmapName;

            Stream bitmapStreamDest = new System.IO.FileStream(uri, FileMode.Create, FileAccess.ReadWrite, FileShare.None);

#if DEBUG
            Console.WriteLine("Saving " + uri);
#endif

            encoder.Save(bitmapStreamDest);

            bitmapStreamDest.Close();

            return(new Uri(BaseUriHelper.SiteOfOriginBaseUri, uri));
        }
Exemple #15
0
        public static void RenderChartToImage(Chart elementToRender, GraphableSensor[] sensors, int width, int height, bool renderFullDataSeries, string filename)
        {
            if (elementToRender == null)
            {
                return;
            }
            Debug.WriteLine("Turning on immediate invalidate");
            //Force immediate invalidation
            InvalidationHandler.ForceImmediateInvalidate = true;

            Debug.WriteLine("Creating new chart");
            var clone = new Chart();

            clone.Width = clone.Height = double.NaN;
            clone.HorizontalAlignment = HorizontalAlignment.Stretch;
            clone.VerticalAlignment   = VerticalAlignment.Stretch;
            clone.Margin = new Thickness();

            clone.Title = elementToRender.Title;
            clone.XAxis = new DateTimeAxis {
                Title = "Date"
            };
            clone.YAxis = new LinearAxis {
                Range = (IRange <double>)elementToRender.YAxis.Range, Title = elementToRender.YAxis.Title
            };

            for (var i = 0; i < elementToRender.Series.Count; i++)
            {
                var series = elementToRender.Series[i];
                var sensor = sensors[i];

                if (sensor.Sensor.Name != series.DataSeries.Title)
                {
                    Debug.WriteLine("Mismatched titles! Oh Dear!");
                    continue;
                }

                var lineSeries = new LineSeries
                {
                    LineStroke = ((LineSeries)series).LineStroke,
                    DataSeries =
                        renderFullDataSeries
                                                 ? new DataSeries <DateTime, float>(sensor.Sensor.Name, sensor.DataPoints)
                                                 : series.DataSeries
                };
                clone.Series.Add(lineSeries);
            }

            var size = new Size(width, height);

            Debug.WriteLine("Rendering new chart of size {0}", size);
            clone.Measure(size);
            clone.Arrange(new Rect(size));
            clone.UpdateLayout();

            var renderer = new RenderTargetBitmap(width, height, 96d, 96d, PixelFormats.Pbgra32);

            renderer.Render(clone);

            var pngEncoder = new PngBitmapEncoder();

            pngEncoder.Frames.Add(BitmapFrame.Create(renderer));

            Debug.WriteLine("Saving to file");
            using (var file = File.Create(filename))
            {
                pngEncoder.Save(file);
            }

            Debug.WriteLine("Turning off immediate invalidate");
            //Reset the invalidation handler
            InvalidationHandler.ForceImmediateInvalidate = false;

            EventLogger.LogInfo(null, "Image Exporter", "Saved graph as image to: " + filename);
        }
Exemple #16
0
        private void SliceSelectedImage(System.Windows.Point slicePoint)
        {
            if (this._img == null)
            {
                return;
            }

            var img = this._img;
            var tb  = this.ScaleImage(img);

            var bitmapRotate = ImageProcess.RotateImage(tb, img.RotateAngle);

            var rectRotate = new Rect();

            if (img.RotateAngle == 0d)
            {
                rectRotate = new Rect(img.Left, img.Top, img.ItemWidth, img.ItemHeight);
            }
            else
            {
                var newSize = ImageProcess.RotateSize(img.ItemWidth, img.ItemHeight, img.RotateAngle);
                rectRotate = new Rect(
                    (img.Left + img.ItemWidth / 2) - newSize.Width / 2,
                    (img.Top + img.ItemHeight / 2) - newSize.Height / 2,
                    newSize.Width,
                    newSize.Height);
            }

            var rectangles = new List <Rect>();

            ///      |            |
            ///   1  |      2     |   3
            /// _____|____________|_______
            ///   4  |      5     |   6
            /// _____|____________|_______
            ///   7  |      8     |   9
            ///      |            |

            /// in rect 1,3,7,9
            if ((slicePoint.X <= rectRotate.Left && slicePoint.Y <= rectRotate.Top) ||
                (slicePoint.X >= rectRotate.Left + rectRotate.Width && slicePoint.Y <= rectRotate.Top) ||
                (slicePoint.X <= rectRotate.Left && slicePoint.Y >= rectRotate.Top + rectRotate.Height) ||
                (slicePoint.X >= rectRotate.Left + rectRotate.Width && slicePoint.Y >= rectRotate.Top + rectRotate.Height))
            {
                return;
            }

            /// in rect 2,8
            if ((slicePoint.X > rectRotate.Left && slicePoint.X < rectRotate.Left + rectRotate.Width) &&
                (slicePoint.Y <= rectRotate.Top || slicePoint.Y >= rectRotate.Top + rectRotate.Height))
            {
                if (SliceType != Module.SliceType.Horizontal)
                {
                    rectangles.Add(new Rect(0, 0, slicePoint.X - rectRotate.Left, rectRotate.Height));
                    rectangles.Add(new Rect(slicePoint.X - rectRotate.Left, 0, rectRotate.Width - (slicePoint.X - rectRotate.Left), rectRotate.Height));
                }
            }

            /// in rect 4,6
            if ((slicePoint.X <= rectRotate.Left || slicePoint.X >= rectRotate.Left + rectRotate.Width) &&
                (slicePoint.Y > rectRotate.Top && slicePoint.Y < rectRotate.Top + rectRotate.Height))
            {
                if (SliceType != Module.SliceType.Vertical)
                {
                    rectangles.Add(new Rect(0, 0, rectRotate.Width, slicePoint.Y - rectRotate.Top));
                    rectangles.Add(new Rect(0, slicePoint.Y - rectRotate.Top, rectRotate.Width, rectRotate.Height - (slicePoint.Y - rectRotate.Top)));
                }
            }

            /// in rect 5
            if ((slicePoint.X > rectRotate.Left && slicePoint.X < rectRotate.Left + rectRotate.Width) &&
                (slicePoint.Y > rectRotate.Top && slicePoint.Y < rectRotate.Top + rectRotate.Height))
            {
                if (SliceType == Module.SliceType.Vertical)
                {
                    rectangles.Add(new Rect(0, 0, slicePoint.X - rectRotate.Left, rectRotate.Height));
                    rectangles.Add(new Rect(slicePoint.X - rectRotate.Left, 0, rectRotate.Width - (slicePoint.X - rectRotate.Left), rectRotate.Height));
                }
                else if (SliceType == Module.SliceType.Horizontal)
                {
                    rectangles.Add(new Rect(0, 0, rectRotate.Width, slicePoint.Y - rectRotate.Top));
                    rectangles.Add(new Rect(0, slicePoint.Y - rectRotate.Top, rectRotate.Width, rectRotate.Height - (slicePoint.Y - rectRotate.Top)));
                }
                else if (SliceType == Module.SliceType.Cross)
                {
                    rectangles.Add(new Rect(0, 0, slicePoint.X - rectRotate.Left, slicePoint.Y - rectRotate.Top));
                    rectangles.Add(new Rect(slicePoint.X - rectRotate.Left, 0, rectRotate.Width - (slicePoint.X - rectRotate.Left), slicePoint.Y - rectRotate.Top));
                    rectangles.Add(new Rect(0, slicePoint.Y - rectRotate.Top, slicePoint.X - rectRotate.Left, rectRotate.Height - (slicePoint.Y - rectRotate.Top)));
                    rectangles.Add(new Rect(slicePoint.X - rectRotate.Left, slicePoint.Y - rectRotate.Top, rectRotate.Width - (slicePoint.X - rectRotate.Left), rectRotate.Height - (slicePoint.Y - rectRotate.Top)));
                }
            }

            if (rectangles.Count > 0)
            {
                var source      = bitmapRotate;
                var orignalsize = new Size(source.Width, source.Height);
                var newWidgets  = new List <WidgetViewModBase>();
                foreach (var rect in rectangles)
                {
                    var widget = this._pageEditorViewModel.PageEditorModel.AddWidgetItem2Dom
                                     (Naver.Compass.Service.Document.WidgetType.Image,
                                     Naver.Compass.Service.Document.ShapeType.None,
                                     rectRotate.Left + rect.X,
                                     rectRotate.Top + rect.Y,
                                     Convert.ToInt32(rect.Width),
                                     Convert.ToInt32(rect.Height));
                    var vmItem = new ImageWidgetViewModel(widget);
                    vmItem.IsSelected = true;
                    var cb = new CroppedBitmap(
                        source,
                        new Int32Rect(
                            Convert.ToInt32(rect.X * orignalsize.Width / rectRotate.Width),
                            Convert.ToInt32(rect.Y * orignalsize.Height / rectRotate.Height),
                            Convert.ToInt32(rect.Width * orignalsize.Width / rectRotate.Width),
                            Convert.ToInt32(rect.Height * orignalsize.Height / rectRotate.Height)));
                    var ms      = new MemoryStream();
                    var encoder = new PngBitmapEncoder();
                    encoder.Frames.Add(BitmapFrame.Create(cb));
                    encoder.Save(ms);
                    ms.Seek(0, SeekOrigin.Begin);
                    vmItem.ImportImgSeekLater(ms, false);
                    vmItem.Opacity = img.Opacity;
                    newWidgets.Add(vmItem);
                }
                img.IsSelected = false;
                this._pageEditorViewModel.ReplaceWidget(new List <WidgetViewModBase> {
                    img
                }, newWidgets);
            }
        }
Exemple #17
0
    public static void SaveToPng(this BitmapSource bitmap, string fileName)
    {
        var encoder = new PngBitmapEncoder();

        SaveUsingEncoder(bitmap, fileName, encoder);
    }
Exemple #18
0
        private void CropAndCutSelectedImg()
        {
            if (this._img == null)
            {
                return;
            }

            var img = this._img;
            var tb  = this.ScaleImage(img);

            var bitmapRotate = ImageProcess.RotateImage(tb, img.RotateAngle);

            var rectRotate = new Rect();

            if (img.RotateAngle == 0d)
            {
                rectRotate = new Rect(img.Left, img.Top, img.ItemWidth, img.ItemHeight);
            }
            else
            {
                var newSize = ImageProcess.RotateSize(img.ItemWidth, img.ItemHeight, img.RotateAngle);
                rectRotate = new Rect(
                    (img.Left + img.ItemWidth / 2) - newSize.Width / 2,
                    (img.Top + img.ItemHeight / 2) - newSize.Height / 2,
                    newSize.Width,
                    newSize.Height);
            }

            var rectangleIntersect = GetIntersect(rectRotate);

            ///no intersect area
            if (rectangleIntersect == Rect.Empty)
            {
                return;
            }

            var source      = bitmapRotate;
            var orignalsize = new Size(source.Width, source.Height);

            ///to cut selected area
            var vmcopyItem = MakeCopyImageWidget(source, orignalsize, rectangleIntersect, rectRotate);

            vmcopyItem.IsSelected = false;
            _pageEditorViewModel.CopyWidget(vmcopyItem, true);
            _pageEditorViewModel.DeleteItem(vmcopyItem);

            ///rubber selected area
            var writablebitmap = new WriteableBitmap(source);
            var toRubberRect   = new Int32Rect(
                Convert.ToInt32((rectangleIntersect.Left - rectRotate.Left) * orignalsize.Width / rectRotate.Width),
                Convert.ToInt32((rectangleIntersect.Top - rectRotate.Top) * orignalsize.Height / rectRotate.Height),
                Convert.ToInt32(rectangleIntersect.Width * orignalsize.Width / rectRotate.Width),
                Convert.ToInt32(rectangleIntersect.Height * orignalsize.Height / rectRotate.Height));

            ImageProcess.Rubber(toRubberRect.X, toRubberRect.Y, toRubberRect.Width, toRubberRect.Height, writablebitmap);

            var ms      = new MemoryStream();
            var encoder = new PngBitmapEncoder();

            encoder.Frames.Add(BitmapFrame.Create(writablebitmap));
            encoder.Save(ms);
            ms.Seek(0, SeekOrigin.Begin);

            var widget = this._pageEditorViewModel.PageEditorModel.AddWidgetItem2Dom
                             (Naver.Compass.Service.Document.WidgetType.Image,
                             Naver.Compass.Service.Document.ShapeType.None,
                             rectRotate.Left,
                             rectRotate.Top,
                             Convert.ToInt32(rectRotate.Width),
                             Convert.ToInt32(rectRotate.Height));
            var vmItem = new ImageWidgetViewModel(widget);

            vmItem.IsSelected = true;
            vmItem.ImportImgSeekLater(ms, false);
            vmItem.Opacity = img.Opacity;

            ///replace selected widget with cropped widget
            img.IsSelected = false;
            this._pageEditorViewModel.ReplaceWidget(
                new List <WidgetViewModBase> {
                img
            },
                new List <WidgetViewModBase> {
                vmItem
            });
        }
        internal void SaveWorkspaceAsImage(string path)
        {
            var initialized = false;
            var bounds      = new Rect();

            double minX = 0.0, minY = 0.0;
            var    dragCanvas    = WpfUtilities.ChildOfType <DragCanvas>(this);
            var    childrenCount = VisualTreeHelper.GetChildrenCount(dragCanvas);

            for (int index = 0; index < childrenCount; ++index)
            {
                ContentPresenter contentPresenter = VisualTreeHelper.GetChild(dragCanvas, index) as ContentPresenter;
                if (contentPresenter.Children().Count() < 1)
                {
                    continue;
                }

                var firstChild = VisualTreeHelper.GetChild(contentPresenter, 0);

                switch (firstChild.GetType().Name)
                {
                case "NodeView":
                case "NoteView":
                case "AnnotationView":
                    break;

                // Until we completely removed InfoBubbleView (or fixed its broken
                // size calculation), we will not be including it in our size
                // calculation here. This means that the info bubble, if any, will
                // still go beyond the boundaries of the final PNG file. I would
                // prefer not to add this hack here as it introduces multiple issues
                // (including NaN for Grid inside the view and the fix would be too
                // ugly to type in). Suffice to say that InfoBubbleView is not
                // included in the size calculation for screen capture (work-around
                // should be obvious).
                //
                // case "InfoBubbleView":
                //     child = WpfUtilities.ChildOfType<Grid>(child);
                //     break;

                // We do not take anything other than those above
                // into consideration when the canvas size is measured.
                default:
                    continue;
                }

                // Determine the smallest corner of all given visual elements on the
                // graph. This smallest top-left corner value will be useful in making
                // the offset later on.
                //
                var childBounds = VisualTreeHelper.GetDescendantBounds(contentPresenter as Visual);
                minX          = childBounds.X < minX ? childBounds.X : minX;
                minY          = childBounds.Y < minY ? childBounds.Y : minY;
                childBounds.X = (double)(contentPresenter as Visual).GetValue(Canvas.LeftProperty);
                childBounds.Y = (double)(contentPresenter as Visual).GetValue(Canvas.TopProperty);

                if (initialized)
                {
                    bounds.Union(childBounds);
                }
                else
                {
                    initialized = true;
                    bounds      = childBounds;
                }
            }

            // Nothing found in the canvas, bail out.
            if (!initialized)
            {
                return;
            }

            // Add padding to the edge and make them multiples of two (pad 10px on each side).
            bounds.Width  = 20 + ((((int)Math.Ceiling(bounds.Width)) + 1) & ~0x01);
            bounds.Height = 20 + ((((int)Math.Ceiling(bounds.Height)) + 1) & ~0x01);

            var currentTransformGroup = WorkspaceElements.RenderTransform as TransformGroup;

            WorkspaceElements.RenderTransform = new TranslateTransform(10.0 - bounds.X - minX, 10.0 - bounds.Y - minY);
            WorkspaceElements.UpdateLayout();

            var rtb = new RenderTargetBitmap(((int)bounds.Width),
                                             ((int)bounds.Height), 96, 96, PixelFormats.Default);

            rtb.Render(WorkspaceElements);
            WorkspaceElements.RenderTransform = currentTransformGroup;

            try
            {
                using (var stm = System.IO.File.Create(path))
                {
                    // Encode as PNG format
                    var pngEncoder = new PngBitmapEncoder();
                    pngEncoder.Frames.Add(BitmapFrame.Create(rtb));
                    pngEncoder.Save(stm);
                }
            }
            catch (Exception)
            {
            }
        }
        // https://stackoverflow.com/a/27077188/122048
        private static Cursor ConvertToCursor(UIElement control, Point hotSpot = default(Point))
        {
            // convert FrameworkElement to PNG stream
            using (var pngStream = new MemoryStream())
            {
                control.InvalidateMeasure();
                control.InvalidateArrange();
                control.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));

                var rect = new Rect(0, 0, control.DesiredSize.Width, control.DesiredSize.Height);

                control.Arrange(rect);
                control.UpdateLayout();

                var rtb = new RenderTargetBitmap((int)control.DesiredSize.Width, (int)control.DesiredSize.Height, 96, 96, PixelFormats.Pbgra32);
                rtb.Render(control);

                var png = new PngBitmapEncoder();
                png.Frames.Add(BitmapFrame.Create(rtb));
                png.Save(pngStream);

                // write cursor header info
                using (var cursorStream = new MemoryStream())
                {
                    cursorStream.Write(new byte[2]
                    {
                        0x00,
                        0x00
                    }, 0, 2);                    // ICONDIR: Reserved. Must always be 0.
                    cursorStream.Write(new byte[2]
                    {
                        0x02,
                        0x00
                    }, 0, 2);                    // ICONDIR: Specifies image type: 1 for icon (.ICO) image, 2 for cursor (.CUR) image. Other values are invalid
                    cursorStream.Write(new byte[2]
                    {
                        0x01,
                        0x00
                    }, 0, 2);                    // ICONDIR: Specifies number of images in the file.
                    cursorStream.Write(new byte[1]
                    {
                        (byte)control.DesiredSize.Width
                    }, 0, 1);                    // ICONDIRENTRY: Specifies image width in pixels. Can be any number between 0 and 255. Value 0 means image width is 256 pixels.
                    cursorStream.Write(new byte[1]
                    {
                        (byte)control.DesiredSize.Height
                    }, 0, 1);                    // ICONDIRENTRY: Specifies image height in pixels. Can be any number between 0 and 255. Value 0 means image height is 256 pixels.
                    cursorStream.Write(new byte[1]
                    {
                        0x00
                    }, 0, 1);                    // ICONDIRENTRY: Specifies number of colors in the color palette. Should be 0 if the image does not use a color palette.
                    cursorStream.Write(new byte[1]
                    {
                        0x00
                    }, 0, 1);                    // ICONDIRENTRY: Reserved. Should be 0.
                    cursorStream.Write(new byte[2]
                    {
                        (byte)hotSpot.X,
                        0x00
                    }, 0, 2);                    // ICONDIRENTRY: Specifies the horizontal coordinates of the hotspot in number of pixels from the left.
                    cursorStream.Write(new byte[2]
                    {
                        (byte)hotSpot.Y,
                        0x00
                    }, 0, 2);                    // ICONDIRENTRY: Specifies the vertical coordinates of the hotspot in number of pixels from the top.
                    cursorStream.Write(new byte[4]
                    {
                        // ICONDIRENTRY: Specifies the size of the image's data in bytes
                        (byte)(pngStream.Length & 0x000000FF),
                        (byte)((pngStream.Length & 0x0000FF00) >> 0x08),
                        (byte)((pngStream.Length & 0x00FF0000) >> 0x10),
                        (byte)((pngStream.Length & 0xFF000000) >> 0x18)
                    }, 0, 4);
                    cursorStream.Write(new byte[4]
                    {
                        // ICONDIRENTRY: Specifies the offset of BMP or PNG data from the beginning of the ICO/CUR file
                        0x16,
                        0x00,
                        0x00,
                        0x00
                    }, 0, 4);

                    // copy PNG stream to cursor stream
                    pngStream.Seek(0, SeekOrigin.Begin);
                    pngStream.CopyTo(cursorStream);

                    // return cursor stream
                    cursorStream.Seek(0, SeekOrigin.Begin);
                    return(new Cursor(cursorStream));
                }
            }
        }
Exemple #21
0
        private void SavePB_Click(object sender, RoutedEventArgs e)
        {
            if (VM.SaveAsFile)
            {
                if (VM.Filename.Length == 0)
                {
                    System.Windows.MessageBox.Show("Filename cannot be empty.",
                                                   "Enter a Filename", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }

                string path = VM.Location + "\\" + VM.Filename + ".png";

                if (File.Exists(path))
                {
                    MessageBoxResult result =
                        System.Windows.MessageBox.Show("File already exists.  Do you want to OverWrite it?",
                                                       "File Already Exists",
                                                       MessageBoxButton.YesNo, MessageBoxImage.Question);

                    if (result == MessageBoxResult.No)
                    {
                        return;
                    }
                }

                using (FileStream stream = new FileStream(path, FileMode.Create))
                {
                    PngBitmapEncoder encoder = new PngBitmapEncoder();
                    encoder.Frames.Add(BitmapFrame.Create(m_bitmap.Clone()));
                    encoder.Save(stream);
                    stream.Close();
                }
            }
            else
            {
                if (VM.Description.Length == 0)
                {
                    System.Windows.MessageBox.Show("Description cannot be empty for the  Reference Image.",
                                                   "Enter a Description", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }

                // save as reference image in database
                WaveguideDB wgDB = new WaveguideDB();

                ReferenceImageContainer refCont = new ReferenceImageContainer();

                refCont.CompressionAlgorithm = GlobalVars.CompressionAlgorithm;
                refCont.Depth         = 2;
                refCont.Height        = m_height;
                refCont.Width         = m_width;
                refCont.ImageData     = m_imageData;
                refCont.MaxPixelValue = GlobalVars.MaxPixelValue;
                refCont.NumBytes      = m_imageData.Length * 2;
                refCont.TimeStamp     = DateTime.Now;
                refCont.Description   = VM.Description;
                refCont.Type          = VM.Type;

                bool alreadyExists;

                bool success = wgDB.ReferenceImageTypeAlreadyExists(VM.Type, out alreadyExists);
                if (success)
                {
                    if (!alreadyExists)
                    {
                        success = wgDB.InsertReferenceImage(ref refCont);

                        if (!success)
                        {
                            System.Windows.MessageBox.Show("Failed to insert Reference Image: " + wgDB.GetLastErrorMsg(),
                                                           "Database Error", MessageBoxButton.OK, MessageBoxImage.Error);
                            return;
                        }
                    }
                    else
                    {
                        string sMessageBoxText = "This reference already exists for: " + VM.Type.ToString() +
                                                 ".  Do you want to replace it?";
                        string sCaption = "Reference Image Already Exists For This Type";

                        MessageBoxButton btnMessageBox = MessageBoxButton.YesNo;
                        MessageBoxImage  icnMessageBox = MessageBoxImage.Warning;

                        MessageBoxResult rsltMessageBox = System.Windows.MessageBox.Show(sMessageBoxText, sCaption, btnMessageBox, icnMessageBox);

                        switch (rsltMessageBox)
                        {
                        case MessageBoxResult.Yes:
                            // delete the existing reference image
                            success = wgDB.ClearReferenceImageType(VM.Type);
                            if (success)
                            {
                                // insert the new reference image
                                success = wgDB.InsertReferenceImage(ref refCont);

                                if (!success)
                                {
                                    System.Windows.MessageBox.Show("Failed to insert Reference Image: " + wgDB.GetLastErrorMsg(),
                                                                   "Database Error", MessageBoxButton.OK, MessageBoxImage.Error);
                                }
                            }
                            else
                            {
                                System.Windows.MessageBox.Show("Failed to clear Reference Image: " + wgDB.GetLastErrorMsg(),
                                                               "Database Error", MessageBoxButton.OK, MessageBoxImage.Error);
                            }

                            break;

                        case MessageBoxResult.No:
                            // do nothing
                            return;
                        }
                    }
                }
            }

            Close();
        }
Exemple #22
0
        //所有btn点击事件
        private void btn_click(object sender, RoutedEventArgs e)
        {
            Button btn = e.Source as Button;

            switch (btn.Content)
            {
            case "退出":
                bIsTimeToDie = true;
                writelog("成功退出!");
                zkfp2.Terminate();
                System.Environment.Exit(0);
                break;

            case "查看日志":
                System.Diagnostics.Process.Start("notepad.exe", rootpath + "\\Finger.log");
                break;

            case "帮助":
                MessageBox.Show("请联系管理员:jovy-rtt");
                break;

            case "采集":
                IsRegister = true;
                info.Text  = "请用相同的指纹按压3次!";
                break;

            case "识别":
                bIdentify = true;
                info.Text = "请按压指纹识别器!";
                break;

            case "登记/更新":
                foreach (var item in infos)
                {
                    if (iFid - 1 == item.id)
                    {
                        item.name  = name.Text;
                        item.phone = phone.Text;
                        item.age   = Age.Text;
                        if (Sex.IsChecked == null || Sex.IsChecked == false)
                        {
                            item.sex = "女";
                        }
                        else
                        {
                            item.sex = "男";
                        }
                        item.finger = Cbox.Text;
                    }
                }
                writelog("id为:" + (iFid - 1).ToString() + " 的指纹信息已登记/更新!");
                break;

            case "打开":

                OpenFileDialog obj = new OpenFileDialog();
                if (obj.ShowDialog() == true)
                {
                    filepath = obj.FileName;
                }
                BitmapImage bimg = new BitmapImage(new Uri(filepath));
                img.Source = bimg;
                break;

            case "保存":
                SaveFileDialog save = new SaveFileDialog();
                save.Filter           = "Image Files (*.bmp, *.png, *.jpg)|*.bmp;*.png;*.jpg | All Files | *.*";
                save.RestoreDirectory = true;
                if (save.ShowDialog() == true)
                {
                    var encoder = new PngBitmapEncoder();
                    encoder.Frames.Add(BitmapFrame.Create((BitmapSource)this.img.Source));
                    using (FileStream stream = new FileStream(save.FileName, FileMode.Create))
                        encoder.Save(stream);
                }
                break;

            default:
                //MessageBox.Show("该控件并未注册点击事件,请先注册!");
                break;
            }
        }
Exemple #23
0
        public static void ExportImageFile(string svgText, int width, int height, ExportFormat exportFormat, float scaleFactor, string filePath)
        {
            if (string.IsNullOrWhiteSpace(svgText))
            {
                throw new ArgumentNullException("svgText");
            }

            if (width <= 0 || (exportFormat != ExportFormat.SVG && width > MaxBitmapDimension))
            {
                throw new ArgumentOutOfRangeException("width");
            }

            if (height <= 0 || (exportFormat != ExportFormat.SVG && height > MaxBitmapDimension))
            {
                throw new ArgumentOutOfRangeException("height");
            }

            if (scaleFactor <= 0 || (exportFormat != ExportFormat.SVG && scaleFactor > GetMaxScaleFactor(width, height)))
            {
                throw new ArgumentOutOfRangeException("scaleFactor");
            }

            if (string.IsNullOrWhiteSpace(filePath))
            {
                throw new ArgumentNullException("filePath");
            }

            string directoryPath = Path.GetDirectoryName(filePath);

            if (!Directory.Exists(directoryPath))
            {
                Directory.CreateDirectory(directoryPath);
            }

            using (FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write))
            {
                if (exportFormat == ExportFormat.SVG)
                {
                    StreamWriter sw = new StreamWriter(fs);
                    sw.Write(svgText);
                    sw.Flush();
                }
                else
                {
                    BitmapEncoder encoder = null;

                    Background background = Background.None;

                    if (exportFormat == ExportFormat.PNG)
                    {
                        encoder = new PngBitmapEncoder();
                    }
                    else if (exportFormat == ExportFormat.GIF)
                    {
                        encoder = new GifBitmapEncoder();
                    }
                    else if (exportFormat == ExportFormat.JPG)
                    {
                        encoder    = new JpegBitmapEncoder();
                        background = Background.White;
                    }

                    BitmapImage    bmpImage      = SvgTextToBitmapImage(svgText, width, height, ImageFormat.Png, background, scaleFactor);
                    BitmapMetadata frameMetadata = GetExportMetadata(exportFormat);

                    BitmapFrame frame = BitmapFrame.Create(bmpImage, null, frameMetadata, null);

                    encoder.Frames.Add(frame);
                    encoder.Save(fs);
                }
            }
        }
        private static void WriteObj(Int32Rect[][] tiles, BitmapSource[][][] imagedata, ConvertOptions options)
        {
            var positions = new Dictionary <Vector3, int>();
            var normals   = new Dictionary <Vector3, int>();
            var uvs       = new Dictionary <Vector2, int>();

            var normal = new Vector3(0, 0, 1);

            var xcount = (options.ImageWidth.Value + options.TileWidth - 1) / options.TileWidth;
            var ycount = (options.ImageHeight.Value + options.TileHeight - 1) / options.TileHeight;

            var folder   = Path.GetDirectoryName(options.InputFileName);
            var filename = Path.GetFileNameWithoutExtension(options.InputFileName);

            var mtl = new ObjMaterialFile();
            var obj = new ObjFile();

            obj.MaterialLibraries.Add($"{filename}.mtl");

            for (var y = 0; y < ycount; y++)
            {
                for (var x = 0; x < xcount; x++)
                {
                    var tile    = tiles[y][x];
                    var texture = imagedata[0][y][x];
                    var encoder = new PngBitmapEncoder();
                    encoder.Frames.Add(BitmapFrame.Create(texture));
                    var matname = $"{filename}_{y:D3}_{x:D3}";
                    using (var outfile = File.Open(Path.Combine(folder, $"{matname}.png"), FileMode.Create, FileAccess.Write, FileShare.None))
                    {
                        encoder.Save(outfile);
                    }

                    var material = new ObjMaterial(matname);
                    material.DiffuseMap = new ObjMaterialMap($"{matname}.png");
                    mtl.Materials.Add(material);
                    var face = new ObjFace();
                    face.MaterialName = matname;

                    face.Vertices.Add(new ObjTriplet(
                                          positions.AddUniqueIndex(new Vector3(tile.X, -(tile.Y), 0)),
                                          uvs.AddUniqueIndex(new Vector2(0, (float)tile.Height / texture.PixelHeight)),
                                          normals.AddUniqueIndex(normal)
                                          ));
                    face.Vertices.Add(new ObjTriplet(
                                          positions.AddUniqueIndex(new Vector3(tile.X + tile.Width, -(tile.Y), 0)),
                                          uvs.AddUniqueIndex(new Vector2((float)tile.Width / texture.PixelWidth, (float)tile.Height / texture.PixelHeight)),
                                          normals.AddUniqueIndex(normal)
                                          ));
                    face.Vertices.Add(new ObjTriplet(
                                          positions.AddUniqueIndex(new Vector3(tile.X + tile.Width, -(tile.Y + tile.Height), 0)),
                                          uvs.AddUniqueIndex(new Vector2((float)tile.Width / texture.PixelWidth, 0)),
                                          normals.AddUniqueIndex(normal)
                                          ));
                    face.Vertices.Add(new ObjTriplet(
                                          positions.AddUniqueIndex(new Vector3(tile.X, -(tile.Y + tile.Height), 0)),
                                          uvs.AddUniqueIndex(new Vector2(0, 0)),
                                          normals.AddUniqueIndex(normal)
                                          ));

                    obj.Faces.Add(face);
                }
            }

            (from x in positions orderby x.Value select x.Key).ToList().ForEach(x => obj.Vertices.Add(x.ToObjVertex()));
            (from x in normals orderby x.Value select x.Key).ToList().ForEach(x => obj.VertexNormals.Add(x.ToObjVector3()));
            (from x in uvs orderby x.Value select x.Key).ToList().ForEach(x => obj.TextureVertices.Add(x.ToObjVector3()));

            mtl.WriteTo(Path.Combine(folder, $"{filename}.mtl"));
            obj.WriteTo(Path.Combine(folder, $"{filename}.obj"));
        }
Exemple #25
0
        public static IntPtr GenerateHICON(ImageSource image, Size dimensions)
        {
            if (image == null)
            {
                return(IntPtr.Zero);
            }

            // If we're getting this from a ".ico" resource, then it comes through as a BitmapFrame.
            // We can use leverage this as a shortcut to get the right 16x16 representation
            // because DrawImage doesn't do that for us.
            var bf = image as BitmapFrame;

            if (bf != null)
            {
                bf = GetBestMatch(bf.Decoder.Frames, (int)dimensions.Width, (int)dimensions.Height);
            }
            else
            {
                // Constrain the dimensions based on the aspect ratio.
                var drawingDimensions = new Rect(0, 0, dimensions.Width, dimensions.Height);

                // There's no reason to assume that the requested image dimensions are square.
                double renderRatio = dimensions.Width / dimensions.Height;
                double aspectRatio = image.Width / image.Height;

                // If it's smaller than the requested size, then place it in the middle and pad the image.
                if (image.Width <= dimensions.Width && image.Height <= dimensions.Height)
                {
                    drawingDimensions = new Rect((dimensions.Width - image.Width) / 2, (dimensions.Height - image.Height) / 2, image.Width, image.Height);
                }
                else if (renderRatio > aspectRatio)
                {
                    double scaledRenderWidth = (image.Width / image.Height) * dimensions.Width;
                    drawingDimensions = new Rect((dimensions.Width - scaledRenderWidth) / 2, 0, scaledRenderWidth, dimensions.Height);
                }
                else if (renderRatio < aspectRatio)
                {
                    double scaledRenderHeight = (image.Height / image.Width) * dimensions.Height;
                    drawingDimensions = new Rect(0, (dimensions.Height - scaledRenderHeight) / 2, dimensions.Width, scaledRenderHeight);
                }

                var            dv = new DrawingVisual();
                DrawingContext dc = dv.RenderOpen();
                dc.DrawImage(image, drawingDimensions);
                dc.Close();

                var bmp = new RenderTargetBitmap((int)dimensions.Width, (int)dimensions.Height, 96, 96, PixelFormats.Pbgra32);
                bmp.Render(dv);
                bf = BitmapFrame.Create(bmp);
            }

            // Using GDI+ to convert to an HICON.
            // I'd rather not duplicate their code.
            using (MemoryStream memstm = new MemoryStream())
            {
                BitmapEncoder enc = new PngBitmapEncoder();
                enc.Frames.Add(bf);
                enc.Save(memstm);

                using (var istm = new ManagedIStream(memstm))
                {
                    // We are not bubbling out GDI+ errors when creating the native image fails.
                    IntPtr bitmap = IntPtr.Zero;
                    try
                    {
                        Status gpStatus = NativeMethods.GdipCreateBitmapFromStream(istm, out bitmap);
                        if (Status.Ok != gpStatus)
                        {
                            return(IntPtr.Zero);
                        }

                        IntPtr hicon;
                        gpStatus = NativeMethods.GdipCreateHICONFromBitmap(bitmap, out hicon);
                        if (Status.Ok != gpStatus)
                        {
                            return(IntPtr.Zero);
                        }

                        // Caller is responsible for freeing this.
                        return(hicon);
                    }
                    finally
                    {
                        Utility.SafeDisposeImage(ref bitmap);
                    }
                }
            }
        }
Exemple #26
0
        private bool InsertFrames(bool after)
        {
            try
            {
                #region Actual List

                var    actualFrame = ActualList[0].Path.SourceFrom();
                double oldWidth    = actualFrame.Width;
                double oldHeight   = actualFrame.Height;
                //var scale = Math.Round(actualFrame.DpiX, MidpointRounding.AwayFromZero) / 96d;

                //If the canvas size changed.
                if (Math.Abs(RightCanvas.ActualWidth - oldWidth) > 0.1 || Math.Abs(RightCanvas.ActualHeight - oldHeight) > 0.1 ||
                    Math.Abs(RightImage.ActualWidth - oldWidth) > 0.1 || Math.Abs(RightImage.ActualHeight - oldHeight) > 0.1)
                {
                    StartProgress(ActualList.Count, FindResource("Editor.UpdatingFrames").ToString());

                    //Saves the state before resizing the images.
                    ActionStack.SaveState(ActionStack.EditAction.ImageAndProperties, ActualList, Util.Other.CreateIndexList2(0, ActualList.Count));

                    foreach (var frameInfo in ActualList)
                    {
                        #region Resize Images

                        // Draws the images into a DrawingVisual component
                        var drawingVisual = new DrawingVisual();
                        using (var context = drawingVisual.RenderOpen())
                        {
                            //The back canvas.
                            context.DrawRectangle(new SolidColorBrush(UserSettings.All.InsertFillColor), null,
                                                  new Rect(new Point(0, 0), new Point(Math.Round(RightCanvas.ActualWidth, MidpointRounding.AwayFromZero), Math.Round(RightCanvas.ActualHeight, MidpointRounding.AwayFromZero))));

                            var topPoint  = Dispatcher.Invoke(() => Canvas.GetTop(RightImage));
                            var leftPoint = Dispatcher.Invoke(() => Canvas.GetLeft(RightImage));

                            //The image.
                            context.DrawImage(frameInfo.Path.SourceFrom(), new Rect(leftPoint, topPoint, RightImage.ActualWidth, RightImage.ActualHeight));

                            //context.DrawText(new FormattedText("Hi!", CultureInfo.InvariantCulture, FlowDirection.LeftToRight, new Typeface("Segoe UI"), 32, Brushes.Black), new Point(0, 0));
                        }

                        //var bmp = new RenderTargetBitmap((int)(RightCanvas.ActualWidth), (int)(RightCanvas.ActualHeight), actualFrame.DpiX, actualFrame.DpiX, PixelFormats.Pbgra32);

                        // Converts the Visual (DrawingVisual) into a BitmapSource
                        var bmp = new RenderTargetBitmap((int)Math.Round(RightCanvas.ActualWidth * (actualFrame.DpiX / 96d), MidpointRounding.AwayFromZero),
                                                         (int)Math.Round(RightCanvas.ActualHeight * (actualFrame.DpiY / 96d), MidpointRounding.AwayFromZero), actualFrame.DpiX, actualFrame.DpiX, PixelFormats.Pbgra32);
                        bmp.Render(drawingVisual);

                        #endregion

                        #region Save

                        //Creates a PngBitmapEncoder and adds the BitmapSource to the frames of the encoder
                        var encoder = new PngBitmapEncoder();
                        encoder.Frames.Add(BitmapFrame.Create(bmp));

                        // Saves the image into a file using the encoder
                        using (Stream stream = File.Create(frameInfo.Path))
                            encoder.Save(stream);

                        #endregion

                        if (_isCancelled)
                        {
                            return(false);
                        }

                        UpdateProgress(ActualList.IndexOf(frameInfo));
                    }
                }

                #endregion

                #region New List

                var newFrame = NewList[0].Path.SourceFrom();
                oldWidth  = newFrame.Width;
                oldHeight = newFrame.Height;
                //scale = Math.Round(newFrame.DpiX, MidpointRounding.AwayFromZero) / 96d;

                StartProgress(ActualList.Count, FindResource("Editor.ImportingFrames").ToString());

                var folder       = Path.GetDirectoryName(ActualList[0].Path);
                var insertFolder = Path.GetDirectoryName(NewList[0].Path);

                //If the canvas size changed.
                if (Math.Abs(LeftCanvas.ActualWidth - oldWidth) > 0.1 || Math.Abs(LeftCanvas.ActualHeight - oldHeight) > 0.1 ||
                    Math.Abs(LeftImage.ActualWidth - oldWidth) > 0.1 || Math.Abs(LeftImage.ActualHeight - oldHeight) > 0.1)
                {
                    foreach (var frameInfo in NewList)
                    {
                        #region Resize Images

                        //Draws the images into a DrawingVisual component.
                        var drawingVisual = new DrawingVisual();
                        using (var context = drawingVisual.RenderOpen())
                        {
                            //The back canvas.
                            context.DrawRectangle(new SolidColorBrush(UserSettings.All.InsertFillColor), null,
                                                  new Rect(new Point(0, 0), new Point(Math.Round(RightCanvas.ActualWidth, MidpointRounding.AwayFromZero),
                                                                                      Math.Round(RightCanvas.ActualHeight, MidpointRounding.AwayFromZero))));

                            var topPoint  = Dispatcher.Invoke(() => Canvas.GetTop(LeftImage));
                            var leftPoint = Dispatcher.Invoke(() => Canvas.GetLeft(LeftImage));

                            //The front image.
                            context.DrawImage(frameInfo.Path.SourceFrom(), new Rect(leftPoint, topPoint, LeftImage.ActualWidth, LeftImage.ActualHeight));
                        }

                        //Converts the Visual (DrawingVisual) into a BitmapSource. Using the actual frame dpi.
                        //var bmp = new RenderTargetBitmap((int)(LeftCanvas.ActualWidth * scale), (int)(LeftCanvas.ActualHeight * scale), actualFrame.DpiX, actualFrame.DpiX, PixelFormats.Pbgra32);
                        var bmp = new RenderTargetBitmap((int)Math.Round(LeftCanvas.ActualWidth * (newFrame.DpiX / 96d), MidpointRounding.AwayFromZero),
                                                         (int)Math.Round(LeftCanvas.ActualHeight * (newFrame.DpiY / 96d), MidpointRounding.AwayFromZero), newFrame.DpiX, newFrame.DpiX, PixelFormats.Pbgra32);
                        bmp.Render(drawingVisual);

                        #endregion

                        #region Save

                        //Creates a PngBitmapEncoder and adds the BitmapSource to the frames of the encoder.
                        var encoder = new PngBitmapEncoder();
                        encoder.Frames.Add(BitmapFrame.Create(bmp));

                        File.Delete(frameInfo.Path);

                        var fileName = Path.Combine(folder, $"{_insertIndex}-{NewList.IndexOf(frameInfo)} {DateTime.Now:hh-mm-ss}.png");

                        //Saves the image into a file using the encoder.
                        using (Stream stream = File.Create(fileName))
                            encoder.Save(stream);

                        frameInfo.Path = fileName;

                        #endregion

                        if (_isCancelled)
                        {
                            return(false);
                        }

                        UpdateProgress(NewList.IndexOf(frameInfo));
                    }
                }
                else
                {
                    foreach (var frameInfo in NewList)
                    {
                        #region Move

                        var fileName = Path.Combine(folder, $"{_insertIndex}-{NewList.IndexOf(frameInfo)} {DateTime.Now.ToString("hh-mm-ss")}.png");

                        File.Move(frameInfo.Path, fileName);

                        frameInfo.Path = fileName;

                        #endregion

                        if (_isCancelled)
                        {
                            return(false);
                        }

                        UpdateProgress(NewList.IndexOf(frameInfo));
                    }
                }

                Directory.Delete(insertFolder, true);

                #endregion

                if (_isCancelled)
                {
                    return(false);
                }

                #region Merge the Lists

                if (after)
                {
                    _insertIndex++;
                }

                //Saves the state before inserting the images.
                ActionStack.SaveState(ActionStack.EditAction.Add, _insertIndex, NewList.Count);

                ActualList.InsertRange(_insertIndex, NewList);

                #endregion

                return(true);
            }
            catch (Exception ex)
            {
                LogWriter.Log(ex, "Insert Error");
                Dispatcher.Invoke(() => Dialog.Ok("Insert Error", "Something Wrong Happened", ex.Message));

                return(false);
            }
        }
        private void btnInsertar_Click(object sender, RoutedEventArgs e)
        {
            //Si todos los campos necesarios estan rellenos  seguimos con la insercion
            if (tbDni.Text != "" && tbNombre.Text != "" && tbApellidos.Text != "" && tbTelefono.Text != "" &&
                tbDireccion.Text != "" && dpFechaNacimiento.Text != "" && dpFechaAlta.Text != "")
            {
                //Si el filepath esta vacio es por que no quiere hacer una foto y ponemos la del avatar
                if (filePath == "")
                {
                    filePath = @"C:\Users\Portatil\Documents\GitHub\EscuelaMusica\EscuelaSanJuan\imagenesPersonas\avatar.png";
                }
                else
                {
                    //Si el filepath esta lleno es por que quiere insertar una foto
                    try
                    {
                        filePath += tbDni.Text + ".jpg";
                        var encoder = new PngBitmapEncoder();
                        encoder.Frames.Add(BitmapFrame.Create((BitmapSource)imagen2.Source));
                        using (FileStream stream = new FileStream(filePath, FileMode.Create))
                            encoder.Save(stream);
                    }
                    catch (System.ArgumentNullException)
                    {
                        filePath = @"C:\Users\Portatil\Documents\GitHub\EscuelaMusica\EscuelaSanJuan\imagenesPersonas\avatar.png";
                    }
                }

                int inserciones = negocio.insertarEmpleado(new Empleado(tbDni.Text.ToLower(),
                                                                        tbNombre.Text.ToLower(),
                                                                        tbApellidos.Text.ToLower(),
                                                                        dpFechaNacimiento.SelectedDate.Value.Date,
                                                                        dpFechaAlta.SelectedDate.Value.Date,
                                                                        tbTelefono.Text.ToLower(),
                                                                        tbDireccion.Text.ToLower(),
                                                                        filePath,
                                                                        true));

                if (inserciones > 0)
                {
                    tbDni.Text       = "";
                    tbNombre.Text    = "";
                    tbApellidos.Text = "";
                    //Reiniciamos el dataPicker de la fecha del nacimiento
                    dpFechaNacimiento.SelectedDate = null;
                    dpFechaNacimiento.DisplayDate  = DateTime.Today;
                    //Reiniciamos el dataPicker de la fecha del alta
                    dpFechaAlta.SelectedDate = null;
                    dpFechaAlta.DisplayDate  = DateTime.Today;
                    tbTelefono.Text          = "";
                    tbDireccion.Text         = "";
                    filePath       = "";
                    imagen2.Source = null;

                    MandarMensaje("Empelado Insertado");
                }
                else
                {
                    MandarMensaje("El Empleado ya existe");
                }
            }
            else
            {
                //Salta en el caso de que falte algun dato necesario
                if (tbDni.Text == "")
                {
                    MandarMensaje("Inserte el Dni porfavor");
                    tbDni.Focus();
                }
                else if (tbNombre.Text == "")
                {
                    MandarMensaje("Inserte el Nombre porfavor");
                    tbNombre.Focus();
                }
                else if (tbApellidos.Text == "")
                {
                    MandarMensaje("Inserte el Apellido porfavor");
                    tbApellidos.Focus();
                }
                else if (tbTelefono.Text == "")
                {
                    MandarMensaje("Inserte el Telefono porfavor");
                    tbTelefono.Focus();
                }
                else if (tbDireccion.Text == "")
                {
                    MandarMensaje("Inserte la Direccion porfavor");
                    tbDireccion.Focus();
                }
                else if (dpFechaNacimiento.Text == "")
                {
                    MandarMensaje("Inserte la Fecha de nacimiento porfavor");
                    dpFechaNacimiento.Focus();
                }
                else if (dpFechaAlta.Text == "")
                {
                    MandarMensaje("Inserte la Fecha de alta porfavor");
                    dpFechaAlta.Focus();
                }
            }
        }
Exemple #28
0
        private bool InsertFrames(bool after, double screenScale)
        {
            try
            {
                //Sizes.
                var left  = NewList[0].Path.SourceFrom();
                var right = CurrentList[0].Path.SourceFrom();

                //The image should be displayed based on the scale of the project.
                var scaleLeft  = left.DpiX / 96d;
                var scaleRight = right.DpiX / 96d; //Math.Round(right.DpiX / 96d, 2);

                var scaleDiffLeft  = screenScale / scaleLeft;
                var scaleDiffRight = screenScale / scaleRight;

                #region Current frames

                //If the canvas size changed.
                if (Math.Abs(RightCanvas.ActualWidth - _rightWidth) > 0.1 || Math.Abs(RightCanvas.ActualHeight - _rightHeight) > 0.1 ||
                    Math.Abs(RightImage.ActualWidth - _rightWidth) > 0.1 || Math.Abs(RightImage.ActualHeight - _rightHeight) > 0.1)
                {
                    StartProgress(CurrentList.Count, FindResource("S.Editor.UpdatingFrames").ToString());

                    //Saves the state before resizing the images.
                    ActionStack.SaveState(ActionStack.EditAction.ImageAndProperties, CurrentList, Util.Other.ListOfIndexes(0, CurrentList.Count));

                    foreach (var frameInfo in CurrentList)
                    {
                        #region Resize Images

                        //Draws the images into a DrawingVisual component.
                        var drawingVisual = new DrawingVisual();
                        using (var context = drawingVisual.RenderOpen())
                        {
                            //The back canvas.
                            context.DrawRectangle(new SolidColorBrush(UserSettings.All.InsertFillColor), null,
                                                  new Rect(new Point(0, 0), new Point(Math.Round(RightCanvas.ActualWidth, MidpointRounding.AwayFromZero), Math.Round(RightCanvas.ActualHeight, MidpointRounding.AwayFromZero))));

                            var topPoint  = Dispatcher.Invoke(() => Canvas.GetTop(RightImage)) * scaleDiffRight;
                            var leftPoint = Dispatcher.Invoke(() => Canvas.GetLeft(RightImage)) * scaleDiffRight;

                            //The image.
                            context.DrawImage(frameInfo.Path.SourceFrom(), new Rect(leftPoint, topPoint, RightImage.ActualWidth * scaleDiffRight, RightImage.ActualHeight * scaleDiffRight));
                            //context.DrawText(new FormattedText("Hi!", CultureInfo.InvariantCulture, FlowDirection.LeftToRight, new Typeface("Segoe UI"), 32, Brushes.Black), new Point(0, 0));
                        }

                        //Converts the Visual (DrawingVisual) into a BitmapSource.
                        var bmp = new RenderTargetBitmap((int)Math.Round(RightCanvas.ActualWidth * screenScale, MidpointRounding.AwayFromZero),
                                                         (int)Math.Round(RightCanvas.ActualHeight * screenScale, MidpointRounding.AwayFromZero), right.DpiX, right.DpiX, PixelFormats.Pbgra32);
                        bmp.Render(drawingVisual);

                        #endregion

                        #region Save

                        //Creates a PngBitmapEncoder and adds the BitmapSource to the frames of the encoder
                        var encoder = new PngBitmapEncoder();
                        encoder.Frames.Add(BitmapFrame.Create(bmp));

                        //Saves the image into a file using the encoder
                        using (Stream stream = File.Create(frameInfo.Path))
                            encoder.Save(stream);

                        #endregion

                        if (_isCancelled)
                        {
                            return(false);
                        }

                        UpdateProgress(CurrentList.IndexOf(frameInfo));
                    }
                }

                #endregion

                #region New frames

                StartProgress(CurrentList.Count, FindResource("S.Editor.ImportingFrames").ToString());

                var folder       = Path.GetDirectoryName(CurrentList[0].Path);
                var insertFolder = Path.GetDirectoryName(NewList[0].Path);

                //If the canvas size changed.
                if (Math.Abs(LeftCanvas.ActualWidth - _leftWidth) > 0.1 || Math.Abs(LeftCanvas.ActualHeight - _leftHeight) > 0.1 ||
                    Math.Abs(LeftImage.ActualWidth - _leftWidth) > 0.1 || Math.Abs(LeftImage.ActualHeight - _leftHeight) > 0.1 || Math.Abs(left.DpiX - right.DpiX) > 0.1)
                {
                    foreach (var frameInfo in NewList)
                    {
                        #region Resize Images

                        //Draws the images into a DrawingVisual component.
                        var drawingVisual = new DrawingVisual();
                        using (var context = drawingVisual.RenderOpen())
                        {
                            //The back canvas.
                            context.DrawRectangle(new SolidColorBrush(UserSettings.All.InsertFillColor), null,
                                                  new Rect(new Point(0, 0), new Point(Math.Round(RightCanvas.ActualWidth * scaleDiffRight, MidpointRounding.AwayFromZero),
                                                                                      Math.Round(RightCanvas.ActualHeight * scaleDiffRight, MidpointRounding.AwayFromZero))));

                            var topPoint  = Dispatcher.Invoke(() => Canvas.GetTop(LeftImage)) * scaleDiffRight;
                            var leftPoint = Dispatcher.Invoke(() => Canvas.GetLeft(LeftImage)) * scaleDiffRight;

                            //The front image.
                            context.DrawImage(frameInfo.Path.SourceFrom(), new Rect(leftPoint, topPoint, LeftImage.ActualWidth * scaleDiffRight, LeftImage.ActualHeight * scaleDiffRight)); // * scaleDiffLeft
                        }

                        //Converts the Visual (DrawingVisual) into a BitmapSource. Using the actual frame dpi.
                        var bmp = new RenderTargetBitmap((int)Math.Round(LeftCanvas.ActualWidth * screenScale, MidpointRounding.AwayFromZero),
                                                         (int)Math.Round(LeftCanvas.ActualHeight * screenScale, MidpointRounding.AwayFromZero), right.DpiX, right.DpiX, PixelFormats.Pbgra32);
                        bmp.Render(drawingVisual);

                        #endregion

                        #region Save

                        //Creates a PngBitmapEncoder and adds the BitmapSource to the frames of the encoder.
                        var encoder = new PngBitmapEncoder();
                        encoder.Frames.Add(BitmapFrame.Create(bmp));

                        File.Delete(frameInfo.Path);

                        var fileName = Path.Combine(folder, $"{_insertIndex}-{NewList.IndexOf(frameInfo)} {DateTime.Now:hh-mm-ss}.png");

                        //Saves the image into a file using the encoder.
                        using (Stream stream = File.Create(fileName))
                            encoder.Save(stream);

                        frameInfo.Path = fileName;

                        #endregion

                        if (_isCancelled)
                        {
                            return(false);
                        }

                        UpdateProgress(NewList.IndexOf(frameInfo));
                    }
                }
                else
                {
                    foreach (var frameInfo in NewList)
                    {
                        #region Move

                        var fileName = Path.Combine(folder, $"{_insertIndex}-{NewList.IndexOf(frameInfo)} {DateTime.Now:hh-mm-ss}.png");

                        File.Move(frameInfo.Path, fileName);

                        frameInfo.Path = fileName;

                        #endregion

                        if (_isCancelled)
                        {
                            return(false);
                        }

                        UpdateProgress(NewList.IndexOf(frameInfo));
                    }
                }

                Directory.Delete(insertFolder, true);

                #endregion

                if (_isCancelled)
                {
                    return(false);
                }

                #region Merge the lists

                if (after)
                {
                    _insertIndex++;
                }

                //Saves the state before inserting the images. This was removed because it was causing a crash when applying undo twice.
                //ActionStack.SaveState(ActionStack.EditAction.Add, _insertIndex, NewList.Count);

                CurrentList.InsertRange(_insertIndex, NewList);

                #endregion

                return(true);
            }
            catch (Exception ex)
            {
                LogWriter.Log(ex, "Insert Error");
                Dispatcher.Invoke(() => ErrorDialog.Ok("Insert Error", "Something Wrong Happened", ex.Message, ex));

                return(false);
            }
        }
Exemple #29
0
        /// <summary>
        /// Saves an image loaded from clipboard to disk OR if base64 is checked
        /// creates the base64 content.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Button_SaveImage(object sender, RoutedEventArgs e)
        {
            string imagePath = null;

            var bitmapSource = ImagePreview.Source as BitmapSource;

            if (bitmapSource == null)
            {
                MessageBox.Show("Unable to convert bitmap source.", "Bitmap conversion error",
                                MessageBoxButton.OK,
                                MessageBoxImage.Warning);
                return;
            }

            using (var bitMap = WindowUtilities.BitmapSourceToBitmap(bitmapSource))
            {
                imagePath = AddinManager.Current.RaiseOnSaveImage(bitMap);

                if (PasteAsBase64Content)
                {
                    Base64EncodeImage(bitMap);
                    IsMemoryImage = false;
                    return;
                }
            }

            if (!string.IsNullOrEmpty(imagePath))
            {
                TextImage.Text = imagePath;
                IsMemoryImage  = false;
                return;
            }


            string initialFolder = null;

            if (!string.IsNullOrEmpty(Document.Filename) && Document.Filename != "untitled")
            {
                initialFolder = Path.GetDirectoryName(Document.Filename);
            }

            var sd = new SaveFileDialog
            {
                Filter           = "Image files (*.png;*.jpg;*.gif;)|*.png;*.jpg;*.jpeg;*.gif|All Files (*.*)|*.*",
                FilterIndex      = 1,
                Title            = "Save Image from Clipboard as",
                InitialDirectory = initialFolder,
                CheckFileExists  = false,
                OverwritePrompt  = true,
                CheckPathExists  = true,
                RestoreDirectory = true
            };
            var result = sd.ShowDialog();

            if (result != null && result.Value)
            {
                imagePath = sd.FileName;

                try
                {
                    var ext = Path.GetExtension(imagePath)?.ToLower();

                    using (var fileStream = new FileStream(imagePath, FileMode.Create))
                    {
                        BitmapEncoder encoder = null;
                        if (ext == ".png")
                        {
                            encoder = new PngBitmapEncoder();
                        }
                        else if (ext == ".jpg")
                        {
                            encoder = new JpegBitmapEncoder();
                        }
                        else if (ext == ".gif")
                        {
                            encoder = new GifBitmapEncoder();
                        }

                        encoder.Frames.Add(BitmapFrame.Create(ImagePreview.Source as BitmapSource));
                        encoder.Save(fileStream);

                        if (ext == ".png")
                        {
                            mmFileUtils.OptimizePngImage(sd.FileName, 5); // async
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Couldn't copy file to new location: \r\n" + ex.Message, mmApp.ApplicationName);
                    return;
                }

                string relPath = Path.GetDirectoryName(sd.FileName);
                if (initialFolder != null)
                {
                    try
                    {
                        relPath = FileUtils.GetRelativePath(sd.FileName, initialFolder);
                    }
                    catch (Exception ex)
                    {
                        mmApp.Log($"Failed to get relative path.\r\nFile: {sd.FileName}, Path: {imagePath}", ex);
                    }
                    imagePath = relPath;
                }

                if (imagePath.Contains(":\\"))
                {
                    imagePath = "file:///" + imagePath;
                }

                imagePath = imagePath.Replace("\\", "/");

                this.Image    = imagePath;
                IsMemoryImage = false;
            }
        }
Exemple #30
0
        /// <summary>
        /// Fetch thumbnail image from slack. Automatically picks largest available or hides thumbnail if none.
        /// </summary>
        /// <param name="selected"></param>
        private async void GetPreview(ResponseFile selected)
        {
            if (selected == null)
            {
                PreviewBrowser.Visibility   = Visibility.Hidden;
                PreviewThumbnail.Visibility = Visibility.Hidden;
                return;
            }

            Uri imgUrl;

            if (selected.thumb_480 != null)
            {
                imgUrl = new Uri(selected.thumb_480);
            }
            else if (selected.thumb_360 != null)
            {
                imgUrl = new Uri(selected.thumb_360);
            }
            else if (selected.thumb_160 != null)
            {
                imgUrl = new Uri(selected.thumb_160);
            }
            else
            {
                PreviewThumbnail.Visibility = Visibility.Hidden;
                if (selected.preview != null)
                {
                    PreviewBrowser.Visibility = Visibility.Visible;
                    PreviewBrowser.NavigateToString(selected.preview);
                }
                else
                {
                    PreviewBrowser.Visibility = Visibility.Hidden;
                }
                return;
            }

            var request_data = new NameValueCollection();

            request_data.Add("Content-Type", "application/x-www-form-urlencoded");
            request_data.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36");

            var webclient = new WebClient();

            webclient.Encoding = Encoding.UTF8;
            webclient.Proxy    = WebRequest.DefaultWebProxy;
            webclient.Headers.Add(HttpRequestHeader.Authorization, "Bearer " + Oauth_Value);

            try
            {
                var imageData = await webclient.DownloadDataTaskAsync(imgUrl);

                var bitmapImage = new BitmapImage {
                    CacheOption = BitmapCacheOption.Default
                };
                var encoder = new PngBitmapEncoder();
                bitmapImage.BeginInit();
                bitmapImage.StreamSource = new MemoryStream(imageData);
                bitmapImage.EndInit();

                PreviewBrowser.Visibility   = Visibility.Hidden;
                PreviewThumbnail.Visibility = Visibility.Visible;
                PreviewThumbnail.Source     = bitmapImage;
            }
            catch
            {
                PreviewBrowser.Visibility   = Visibility.Hidden;
                PreviewThumbnail.Visibility = Visibility.Hidden;
            }

            webclient.Dispose();
        }