/// <summary> /// Gets the pixel depth (in bits per pixel, bpp) of the specified frame /// </summary> /// <param name="frame">The frame to get BPP for</param> /// <returns>The number of bits per pixel in the frame</returns> static int GetFramePixelDepth (BitmapFrame frame) { if (frame.Decoder.CodecInfo.ContainerFormat == new Guid("{a3a860c4-338f-4c17-919a-fba4b5628f21}") && frame.Thumbnail != null) { // Windows Icon format, original pixel depth is in the thumbnail return frame.Thumbnail.Format.BitsPerPixel; } // Other formats, just assume the frame has the correct BPP info return frame.Format.BitsPerPixel; }
protected override void RebuildUI() { if (DataSource == null) { return; } if (Plotter == null) { return; } if (Palette == null) { return; } int width = DataSource.Width; int height = DataSource.Height; fieldWrapper = new UniformField2DWrapper(DataSource.Data); var coordinate = SectionCoordinate; var minMaxLength = DataSource.GetMinMaxLength(); PointCollection points = new PointCollection(width + 2); var palette = Palette; int[] pixels = new int[width]; for (int ix = 0; ix < width; ix++) { double x = ix; var value = fieldWrapper.GetVector(x / width, coordinate / width); double length = value.Length; if (length.IsNaN()) { length = minMaxLength.Min; } double ratio = (length - minMaxLength.Min) / minMaxLength.GetLength(); if (ratio < 0) { ratio = 0; } if (ratio > 1) { ratio = 1; } points.Add(new Point(x, 1 - ratio)); var color = palette.GetColor(ratio); pixels[ix] = color.ToArgb(); } points.Add(new Point(width, 1)); points.Add(new Point(0, 1)); polygon.Points = points; var paletteBmp = BitmapFrame.Create(width, 1, 96, 96, PixelFormats.Bgra32, null, pixels, (width * PixelFormats.Bgra32.BitsPerPixel + 7) / 8); var brush = new ImageBrush(paletteBmp); polygon.Fill = brush; }
public string SaveBitmapSourceToAzureBlobStorage(BitmapSource image, string connectionStringName, string blobName = null) { var blobConnection = AzureConfiguration.Current.ConnectionStrings .FirstOrDefault(cs => cs.Name.ToLower() == connectionStringName.ToLower()); if (blobConnection == null) { ErrorMessage = "Invalid configuration string."; return(null); } try { CloudStorageAccount storageAccount = CloudStorageAccount.Parse(blobConnection.ConnectionString); // Create the blob client. CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); // Retrieve a reference to a container. CloudBlobContainer container = blobClient.GetContainerReference(blobConnection.ContainerName); // Create the container if it doesn't already exist. container.CreateIfNotExists(); container.SetPermissions(new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob }); var extension = Path.GetExtension(blobName).Replace(".", "").ToLower(); BitmapEncoder encoder; if (extension == "jpg" || extension == "jpeg") { encoder = new JpegBitmapEncoder(); } else if (extension == "gif") { encoder = new GifBitmapEncoder(); } else if (extension == ".bmp") { encoder = new BmpBitmapEncoder(); } else { encoder = new PngBitmapEncoder(); } encoder.Frames.Add(BitmapFrame.Create(image)); bool result; using (var ms = new MemoryStream()) { encoder.Save(ms); ms.Flush(); ms.Position = 0; result = UploadStream(ms, blobName, container); } if (!result) { return(null); } var blob = container.GetBlockBlobReference(blobName); return(blob.Uri.ToString()); } catch (Exception ex) { ErrorMessage = ex.GetBaseException().Message; } return(null); }
private void CreateAndShowMainWindow() { // Create the application's main window mainWindow = new Window(); mainWindow.Title = "TIFF Imaging Sample"; ScrollViewer mySV = new ScrollViewer(); //<Snippet4> int width = 128; int height = width; int stride = width / 8; byte[] pixels = new byte[height * stride]; // Define the image palette BitmapPalette myPalette = BitmapPalettes.WebPalette; // Creates a new empty image with the pre-defined palette //<Snippet2> BitmapSource image = BitmapSource.Create( width, height, 96, 96, PixelFormats.Indexed1, myPalette, pixels, stride); //</Snippet2> //<Snippet3> FileStream stream = new FileStream("new.tif", FileMode.Create); TiffBitmapEncoder encoder = new TiffBitmapEncoder(); TextBlock myTextBlock = new TextBlock(); myTextBlock.Text = "Codec Author is: " + encoder.CodecInfo.Author.ToString(); encoder.Compression = TiffCompressOption.Zip; encoder.Frames.Add(BitmapFrame.Create(image)); encoder.Save(stream); //</Snippet3> //</Snippet4> //<Snippet1> // Open a Stream and decode a TIFF image Stream imageStreamSource = new FileStream("tulipfarm.tif", FileMode.Open, FileAccess.Read, FileShare.Read); TiffBitmapDecoder decoder = new TiffBitmapDecoder(imageStreamSource, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default); BitmapSource bitmapSource = decoder.Frames[0]; // Draw the Image Image myImage = new Image(); myImage.Source = bitmapSource; myImage.Stretch = Stretch.None; myImage.Margin = new Thickness(20); //</Snippet1> //<Snippet5> // Open a Uri and decode a TIFF image Uri myUri = new Uri("tulipfarm.tif", UriKind.RelativeOrAbsolute); TiffBitmapDecoder decoder2 = new TiffBitmapDecoder(myUri, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default); BitmapSource bitmapSource2 = decoder2.Frames[0]; // Draw the Image Image myImage2 = new Image(); myImage2.Source = bitmapSource2; myImage2.Stretch = Stretch.None; myImage2.Margin = new Thickness(20); //</Snippet5> // Define a StackPanel to host the decoded TIFF images StackPanel myStackPanel = new StackPanel(); myStackPanel.Orientation = Orientation.Vertical; myStackPanel.VerticalAlignment = VerticalAlignment.Stretch; myStackPanel.HorizontalAlignment = HorizontalAlignment.Stretch; // Add the Image and TextBlock to the parent Grid myStackPanel.Children.Add(myImage); myStackPanel.Children.Add(myImage2); myStackPanel.Children.Add(myTextBlock); // Add the StackPanel as the Content of the Parent Window Object mySV.Content = myStackPanel; mainWindow.Content = mySV; mainWindow.Show(); }
/// <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)) { if (bitMap == null) { return; } 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; string documentFolder = null; if (!string.IsNullOrEmpty(Document.Filename) && Document.Filename != "untitled") { documentFolder = Path.GetDirectoryName(Document.Filename); if (!string.IsNullOrEmpty(Document.LastImageFolder)) { initialFolder = Document.LastImageFolder; } else { initialFolder = documentFolder; } } 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(); if (ext == ".jpg" || ext == ".jpeg") { ImageUtils.SaveJpeg(bitMap, imagePath, mmApp.Configuration.JpegImageCompressionLevel); } else { using (var fileStream = new FileStream(imagePath, FileMode.Create)) { BitmapEncoder encoder = null; if (ext == ".png") { encoder = new PngBitmapEncoder(); } else if (ext == ".gif") { encoder = new GifBitmapEncoder(); } encoder.Frames.Add(BitmapFrame.Create(ImagePreview.Source as BitmapSource)); encoder.Save(fileStream); if (ext == ".png" || ext == ".jpeg") { mmFileUtils.OptimizeImage(sd.FileName); // async } } } } catch (Exception ex) { MessageBox.Show("Couldn't save file: \r\n" + ex.Message, mmApp.ApplicationName); return; } string relPath = Path.GetDirectoryName(sd.FileName); Document.LastImageFolder = relPath; if (documentFolder != null) { try { relPath = FileUtils.GetRelativePath(sd.FileName, documentFolder); } 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("\\", "/"); Image = imagePath; IsMemoryImage = false; } } }
private void Timer_Elapsed(object sender, ElapsedEventArgs e) { Dispatcher.BeginInvoke((Action)(() => { //foreach (FieldInfo type in typeof(DataFormats).GetFields()) //{ // if (Clipboard.GetDataObject().GetDataPresent(type.GetValue("") as string)) // { // Console.WriteLine(type.GetValue("") as string); // } //} try { transfareData IDataTranfare = new transfareData(); foreach (string _supported in supportedFormats) { if (!Clipboard.GetDataObject().GetDataPresent(_supported)) { continue; } if (_supported == DataFormats.Bitmap) { Image image = new Image(); System.Windows.Interop.InteropBitmap interopBitmap = (System.Windows.Interop.InteropBitmap)Clipboard.GetImage(); image.Source = interopBitmap; IDataTranfare.copyValue = image; BitmapFrame interopBitmap1 = CreateResizedImage(interopBitmap, Math.Min(interopBitmap.PixelWidth, 100), Math.Min(interopBitmap.PixelHeight, 100), 0); Image image2 = new Image(); image2.Source = interopBitmap1; IDataTranfare.contentValue = image2; Int32Rect rect = new Int32Rect(0, 0, interopBitmap1.PixelWidth, interopBitmap1.PixelHeight); int stride = interopBitmap1.PixelWidth * (interopBitmap1.Format.BitsPerPixel + 7) / 8; int arrayLength = stride * interopBitmap1.PixelHeight; int[] arr = new int[arrayLength]; interopBitmap1.CopyPixels(rect, arr, stride, 0); unchecked { int sum = 0; for (int i = 0; i < arr.Length; i++) { sum += arr[i]; } IDataTranfare.savedValue = sum / arr.Length; } } else if (_supported == DataFormats.Text) { IDataTranfare.copyValue = Clipboard.GetText().Replace("\n", "").Replace("\r", ""); IDataTranfare.savedValue = IDataTranfare.copyValue; IDataTranfare.contentValue = IDataTranfare.copyValue; } IDataTranfare.format = _supported; break; } if (OLD_IData.Contains(IDataTranfare.savedValue) || IDataTranfare.format == null) { return; } OLD_IData.Add(IDataTranfare.savedValue); ListBOX.Items.Insert(0, new itemElement(ListBOX, OLD_IData, IDataTranfare)); } catch (Exception err) { Console.WriteLine(err); } })); }
static internal ImageSource GetImageSourceFromResource(string resourceName) { return(BitmapFrame.Create(typeof(QueryCompletionData).Assembly.GetManifestResourceStream(typeof(QueryCompletionData).Namespace + "." + resourceName))); }
private void Encode(List <FrameInfo> listFrames, int id, Parameters param, CancellationTokenSource tokenSource) { var processing = FindResource("Encoder.Processing").ToString(); try { switch (param.Type) { case Export.Gif: #region Gif var gifParam = (GifParameters)param; #region Cut/Paint Unchanged Pixels if (gifParam.DetectUnchangedPixels && (gifParam.EncoderType == GifEncoderType.Legacy || gifParam.EncoderType == GifEncoderType.ScreenToGif)) { Update(id, 0, FindResource("Encoder.Analyzing").ToString()); if (gifParam.DummyColor.HasValue) { var color = Color.FromArgb(gifParam.DummyColor.Value.R, gifParam.DummyColor.Value.G, gifParam.DummyColor.Value.B); listFrames = ImageMethods.PaintTransparentAndCut(listFrames, color, id, tokenSource); } else { listFrames = ImageMethods.CutUnchanged(listFrames, id, tokenSource); } } #endregion switch (gifParam.EncoderType) { case GifEncoderType.ScreenToGif: #region Improved encoding using (var stream = new MemoryStream()) { using (var encoder = new GifFile(stream, gifParam.RepeatCount)) { encoder.UseGlobalColorTable = gifParam.UseGlobalColorTable; encoder.TransparentColor = gifParam.DummyColor; encoder.MaximumNumberColor = gifParam.MaximumNumberColors; for (var i = 0; i < listFrames.Count; i++) { if (!listFrames[i].HasArea && gifParam.DetectUnchangedPixels) { continue; } if (listFrames[i].Delay == 0) { listFrames[i].Delay = 10; } encoder.AddFrame(listFrames[i].Path, listFrames[i].Rect, listFrames[i].Delay); Update(id, i, string.Format(processing, i)); #region Cancellation if (tokenSource.Token.IsCancellationRequested) { SetStatus(Status.Canceled, id); break; } #endregion } } try { using (var fileStream = new FileStream(gifParam.Filename, FileMode.Create, FileAccess.Write, FileShare.None, 4096)) { stream.WriteTo(fileStream); } if (gifParam.SaveToClipboard) { CopyToClipboard(gifParam.Filename); } } catch (Exception ex) { SetStatus(Status.Error, id); LogWriter.Log(ex, "Improved Encoding"); } } #endregion break; case GifEncoderType.Legacy: #region Legacy Encoding using (var encoder = new AnimatedGifEncoder()) { if (gifParam.DummyColor.HasValue) { var color = Color.FromArgb(gifParam.DummyColor.Value.R, gifParam.DummyColor.Value.G, gifParam.DummyColor.Value.B); encoder.SetTransparent(color); encoder.SetDispose(1); //Undraw Method, "Leave". } encoder.Start(gifParam.Filename); encoder.SetQuality(gifParam.Quality); encoder.SetRepeat(gifParam.RepeatCount); var numImage = 0; foreach (var frame in listFrames) { #region Cancellation if (tokenSource.Token.IsCancellationRequested) { SetStatus(Status.Canceled, id); break; } #endregion if (!frame.HasArea && gifParam.DetectUnchangedPixels) { continue; } var bitmapAux = new Bitmap(frame.Path); encoder.SetDelay(frame.Delay); encoder.AddFrame(bitmapAux, frame.Rect.X, frame.Rect.Y); bitmapAux.Dispose(); Update(id, numImage, string.Format(processing, numImage)); numImage++; } } if (gifParam.SaveToClipboard) { CopyToClipboard(gifParam.Filename); } #endregion break; case GifEncoderType.PaintNet: #region paint.NET encoding using (var stream = new MemoryStream()) { using (var encoder = new GifEncoder(stream, null, null, gifParam.RepeatCount)) { for (var i = 0; i < listFrames.Count; i++) { var bitmapAux = new Bitmap(listFrames[i].Path); encoder.AddFrame(bitmapAux, 0, 0, TimeSpan.FromMilliseconds(listFrames[i].Delay)); bitmapAux.Dispose(); Update(id, i, string.Format(processing, i)); #region Cancellation if (tokenSource.Token.IsCancellationRequested) { SetStatus(Status.Canceled, id); break; } #endregion } } stream.Position = 0; try { using (var fileStream = new FileStream(gifParam.Filename, FileMode.Create, FileAccess.Write, FileShare.None, Constants.BufferSize, false)) { stream.WriteTo(fileStream); } if (gifParam.SaveToClipboard) { CopyToClipboard(gifParam.Filename); } } catch (Exception ex) { SetStatus(Status.Error, id); LogWriter.Log(ex, "Encoding with paint.Net."); } } #endregion break; default: throw new Exception("Undefined Gif encoder type"); } #endregion break; case Export.Video: #region Video var videoParam = (VideoParameters)param; switch (videoParam.VideoEncoder) { case VideoEncoderType.AviStandalone: #region Avi Standalone var image = listFrames[0].Path.SourceFrom(); if (File.Exists(videoParam.Filename)) { File.Delete(videoParam.Filename); } //1000 / listFrames[0].Delay using (var aviWriter = new AviWriter(videoParam.Filename, videoParam.Framerate, image.PixelWidth, image.PixelHeight, videoParam.Quality)) { var numImage = 0; foreach (var frame in listFrames) { using (var outStream = new MemoryStream()) { var bitImage = frame.Path.SourceFrom(); var enc = new BmpBitmapEncoder(); enc.Frames.Add(BitmapFrame.Create(bitImage)); enc.Save(outStream); outStream.Flush(); using (var bitmap = new Bitmap(outStream)) aviWriter.AddFrame(bitmap, videoParam.FlipVideo); } //aviWriter.AddFrame(new BitmapImage(new Uri(frame.Path))); Update(id, numImage, string.Format(processing, numImage)); numImage++; #region Cancellation if (tokenSource.Token.IsCancellationRequested) { SetStatus(Status.Canceled, id); break; } #endregion } } #endregion break; case VideoEncoderType.Ffmpg: #region Video using FFmpeg SetStatus(Status.Encoding, id, null, true); if (!Util.Other.IsFfmpegPresent()) { throw new ApplicationException("FFmpeg not present."); } videoParam.Command = string.Format(videoParam.Command, Path.Combine(Path.GetDirectoryName(listFrames[0].Path), "%d.png"), videoParam.ExtraParameters.Replace("{H}", param.Height.ToString()).Replace("{W}", param.Width.ToString()), videoParam.Framerate, param.Filename); var process = new ProcessStartInfo(UserSettings.All.FfmpegLocation) { Arguments = videoParam.Command, CreateNoWindow = true, ErrorDialog = false, UseShellExecute = false, RedirectStandardError = true }; var pro = Process.Start(process); var str = pro.StandardError.ReadToEnd(); var fileInfo = new FileInfo(param.Filename); if (!fileInfo.Exists || fileInfo.Length == 0) { throw new Exception("Error while encoding with FFmpeg.", new Exception(str)); } #endregion break; default: throw new Exception("Undefined video encoder"); } #endregion break; default: throw new ArgumentOutOfRangeException(nameof(param)); } if (!tokenSource.Token.IsCancellationRequested) { SetStatus(Status.Completed, id, param.Filename); } } catch (Exception ex) { LogWriter.Log(ex, "Encode"); SetStatus(Status.Error, id, null, false, ex); } finally { #region Delete Encoder Folder try { var encoderFolder = Path.GetDirectoryName(listFrames[0].Path); if (!string.IsNullOrEmpty(encoderFolder)) { if (Directory.Exists(encoderFolder)) { Directory.Delete(encoderFolder, true); } } } catch (Exception ex) { LogWriter.Log(ex, "Cleaning the Encode folder"); } #endregion GC.Collect(); } }
private void Start() { System.Globalization.CultureInfo.CurrentCulture = System.Globalization.CultureInfo.InvariantCulture; ShopUtils.CreateFiles(); productList = ShopUtils.DeserializeProducts(ShopUtils.GetFilePath("Products.json")); couponList = Coupon.DeserializeCoupons(); #region Custom brushes // declare a brushconverter to convert a hex color code string to a Brush color BrushConverter brushConverter = new System.Windows.Media.BrushConverter(); Brush backgroundBrush = (Brush)brushConverter.ConvertFromString("#2F3136"); listBoxBrush = (Brush)brushConverter.ConvertFromString("#36393F"); textBoxBrush = (Brush)brushConverter.ConvertFromString("#40444B"); #endregion // Window options Title = "Sortimenthanteraren"; Width = 1100; Height = 600; WindowStartupLocation = WindowStartupLocation.CenterScreen; // Changes the Window icon Uri iconUri = new Uri("Images/Ica.png", UriKind.RelativeOrAbsolute); this.Icon = BitmapFrame.Create(iconUri); // Scrolling ScrollViewer root = new ScrollViewer(); root.VerticalScrollBarVisibility = ScrollBarVisibility.Auto; Content = root; // Main grid Grid mainGrid = new Grid(); root.Content = mainGrid; mainGrid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto }); mainGrid.RowDefinitions.Add(new RowDefinition()); // first column contains a stackpanel with buttons which determines what grid to create, the second column contains a class field grid "buttonClickGrid" which is the parent grid for the eventhandlers nested grids mainGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto }); mainGrid.ColumnDefinitions.Add(new ColumnDefinition()); mainGrid.Background = backgroundBrush; // Window heading, always visible TextBlock headingTextBlock = ShopUtils.CreateTextBlock("Sortimenthanteraren", 18, TextAlignment.Center); mainGrid.Children.Add(headingTextBlock); Grid.SetRow(headingTextBlock, 0); Grid.SetColumnSpan(headingTextBlock, 2); StackPanel buttonPanel = new StackPanel { VerticalAlignment = VerticalAlignment.Top }; mainGrid.Children.Add(buttonPanel); Grid.SetColumn(buttonPanel, 0); Grid.SetRow(buttonPanel, 1); // using a empty class field grid to be able to add nested grids from the eventhandlers buttonClickGrid = new Grid(); mainGrid.Children.Add(buttonClickGrid); Grid.SetRow(buttonClickGrid, 1); Grid.SetColumn(buttonClickGrid, 1); // each button declares a new grid which is added as buttonClickGrid's only child to display a menu to add/edit/remove coupons and products Button editProductButton = ShopUtils.CreateButton("Ändra produkter"); editProductButton.Padding = new Thickness(10); buttonPanel.Children.Add(editProductButton); editProductButton.Click += CreateEditProductGrid; Button addProductButton = ShopUtils.CreateButton("Lägg till produkt"); addProductButton.Padding = new Thickness(10); buttonPanel.Children.Add(addProductButton); addProductButton.Click += CreateAddProductGrid; Button EditCouponsButton = ShopUtils.CreateButton("Lägg till/Ändra kuponger"); EditCouponsButton.Padding = new Thickness(10); buttonPanel.Children.Add(EditCouponsButton); EditCouponsButton.Click += CreateEditCouponsGrid; }
public void deseneazaForme() { stackPanel.Children.Clear(); categorii = ReflectionDAO.createListOfObjects("select * from CategoriiProdus", "CategoriiProdus"); if (categorieProdusValue == "Toate") { produse = ReflectionDAO.createListOfObjects("select * from Produs", "Produs"); } else { produse = ReflectionDAO.createListOfObjects("select * from Produs where categorie = '" + categorieProdusValue + "'", "Produs"); } nrProduse = produse.Count(); canvas = new Canvas[nrProduse]; categorie = new Label[nrProduse]; dateProdus = new Label[nrProduse]; descriere = new TextBox[nrProduse]; detaliu = new Label[nrProduse]; btnProdus = new Button[nrProduse]; index = 0; int height = 15; for (int i = 0; i < nrProduse; i++) { if (categorieProdusValue == "Toate" || ((Produs)produse[i]).Categorie == categorieProdusValue) { canvas[i] = new Canvas(); stackPanel.Children.Add(canvas[i]); canvas[i].Width = 800; canvas[i].Height = 100; canvas[i].Margin = new Thickness(15, height, 0, 0); //height += 100 + 15; canvas[i].Background = new SolidColorBrush(Color.FromRgb(252, 228, 200)); canvas[i].Visibility = Visibility.Visible; canvas[i].HorizontalAlignment = HorizontalAlignment.Left; canvas[i].VerticalAlignment = VerticalAlignment.Top; //label categorie categorie[i] = new Label(); canvas[i].Children.Add(categorie[i]); categorie[i].Width = 125; categorie[i].Margin = new Thickness(20, 37, 0, 0); categorie[i].Foreground = new SolidColorBrush(Color.FromRgb(179, 68, 38)); categorie[i].FontFamily = new FontFamily("Times New Roman"); categorie[i].FontSize = 14; categorie[i].Content = ((Produs)produse[i]).Categorie.ToString(); categorie[i].HorizontalContentAlignment = HorizontalAlignment.Center; //bara verticala Border b = new Border(); canvas[i].Children.Add(b); b.Height = 80; b.Width = 3; b.BorderThickness = new Thickness(2); b.BorderBrush = new SolidColorBrush(Color.FromRgb(179, 68, 38)); b.Margin = new Thickness(150, 10, 0, 0); //date produs dateProdus[i] = new Label(); canvas[i].Children.Add(dateProdus[i]); dateProdus[i].Margin = new Thickness(170, 10, 0, 0); dateProdus[i].Foreground = new SolidColorBrush(Color.FromRgb(179, 68, 38)); dateProdus[i].FontFamily = new FontFamily("Times New Roman"); dateProdus[i].FontSize = 14; dateProdus[i].Content = ((Produs)produse[i]).Nume.ToString(); dateProdus[i].FontWeight = FontWeights.Bold; //descriere produs descriere[i] = new TextBox(); canvas[i].Children.Add(descriere[i]); descriere[i].Margin = new Thickness(170, 35, 0, 0); descriere[i].Background = new SolidColorBrush(Color.FromArgb(0, 0, 0, 0)); descriere[i].Foreground = new SolidColorBrush(Color.FromRgb(179, 68, 38)); descriere[i].BorderThickness = new Thickness(0); descriere[i].Width = 290; descriere[i].Height = 55; descriere[i].Text = "(" + ((Produs)produse[i]).Descriere.ToString() + ")"; descriere[i].HorizontalAlignment = HorizontalAlignment.Stretch; descriere[i].VerticalAlignment = VerticalAlignment.Stretch; descriere[i].TextWrapping = TextWrapping.Wrap; //detaliu detaliu[i] = new Label(); canvas[i].Children.Add(detaliu[i]); detaliu[i].Width = 125; detaliu[i].Margin = new Thickness(500, 38, 0, 0); detaliu[i].Foreground = new SolidColorBrush(Color.FromRgb(179, 68, 38)); detaliu[i].FontFamily = new FontFamily("Times New Roman"); detaliu[i].FontSize = 14; detaliu[i].Content = ((Produs)produse[i]).Gramaj.ToString() + " grame, " + ((Produs)produse[i]).Pret.ToString() + " lei"; //buton modificari cont btnProdus[i] = new Button(); canvas[i].Children.Add(btnProdus[i]); btnProdus[i].Margin = new Thickness(700, 10, 0, 0); btnProdus[i].Width = btnProdus[i].Height = 80; btnProdus[i].Style = this.Resources["btnGlass"] as Style; btnProdus[i].BorderThickness = new Thickness(4); btnProdus[i].BorderBrush = new SolidColorBrush(Color.FromRgb(179, 68, 38)); btnProdus[i].Name = "btnProdus" + i.ToString(); btnProdus[i].Click += produs_Click; Uri resourceUri = new Uri("Resources/settings.png", UriKind.Relative); StreamResourceInfo streamInfo = Application.GetResourceStream(resourceUri); BitmapFrame temp = BitmapFrame.Create(streamInfo.Stream); var brush = new ImageBrush(); brush.ImageSource = temp; btnProdus[i].Background = brush; btnProdus[i].Cursor = Cursors.Hand; btnProdus[i].ToolTip = "Modificare date produs"; btnProdus[i].Name = "btnProdus" + i.ToString(); //btnCumparaturi[i].Click += istoricCumparaturi_Click; } } }
private void saveImageAsFile(System.Drawing.Image img) { string extension = readExtension(savePathTxt.Text); switch (extension) { case ".jpeg": var JPEGenc = new JpegBitmapEncoder(); JPEGenc.Frames.Add(BitmapFrame.Create(ImageProc.ImgToBmpSource(img))); using (var stream = new FileStream(savePathTxt.Text, FileMode.Create, FileAccess.Write)) { JPEGenc.Save(stream); } break; case ".jpg": var JPGenc = new JpegBitmapEncoder(); JPGenc.Frames.Add(BitmapFrame.Create(ImageProc.ImgToBmpSource(img))); using (var stream = new FileStream(savePathTxt.Text, FileMode.Create, FileAccess.Write)) { JPGenc.Save(stream); } break; case ".png": var PNGenc = new PngBitmapEncoder(); PNGenc.Frames.Add(BitmapFrame.Create(ImageProc.ImgToBmpSource(img))); using (var stream = new FileStream(savePathTxt.Text, FileMode.Create, FileAccess.Write)) { PNGenc.Save(stream); } break; case ".tif": var TIFenc = new TiffBitmapEncoder(); // get TIFF compression type if (tifTypeCBX.SelectedIndex == 0) { TIFenc.Compression = TiffCompressOption.Ccitt3; } if (tifTypeCBX.SelectedIndex == 1) { TIFenc.Compression = TiffCompressOption.Ccitt4; } if (tifTypeCBX.SelectedIndex == 2) { TIFenc.Compression = TiffCompressOption.Lzw; } if (tifTypeCBX.SelectedIndex == 3) { TIFenc.Compression = TiffCompressOption.None; } if (tifTypeCBX.SelectedIndex == 4) { TIFenc.Compression = TiffCompressOption.Rle; } if (tifTypeCBX.SelectedIndex == 5) { TIFenc.Compression = TiffCompressOption.Zip; } TIFenc.Frames.Add(BitmapFrame.Create(ImageProc.ImgToBmpSource(img))); using (var stream = new FileStream(savePathTxt.Text, FileMode.Create, FileAccess.Write)) { TIFenc.Save(stream); } break; case ".tiff": var TIFFenc = new TiffBitmapEncoder(); // get TIFF compression type if (tifTypeCBX.SelectedIndex == 0) { TIFFenc.Compression = TiffCompressOption.Ccitt3; } if (tifTypeCBX.SelectedIndex == 1) { TIFFenc.Compression = TiffCompressOption.Ccitt4; } if (tifTypeCBX.SelectedIndex == 2) { TIFFenc.Compression = TiffCompressOption.Lzw; } if (tifTypeCBX.SelectedIndex == 3) { TIFFenc.Compression = TiffCompressOption.None; } if (tifTypeCBX.SelectedIndex == 4) { TIFFenc.Compression = TiffCompressOption.Rle; } if (tifTypeCBX.SelectedIndex == 5) { TIFFenc.Compression = TiffCompressOption.Zip; } TIFFenc.Frames.Add(BitmapFrame.Create(ImageProc.ImgToBmpSource(img))); using (var stream = new FileStream(savePathTxt.Text, FileMode.Create, FileAccess.Write)) { TIFFenc.Save(stream); } break; } }
/// <summary> /// Gets color profile from BitmapFrame. /// </summary> /// <param name="bitmapFrame">BitmapFrame</param> /// <returns>Color profile</returns> private static ColorContext GetColorProfile(BitmapFrame bitmapFrame) { return((bitmapFrame.ColorContexts?.Count > 0) ? bitmapFrame.ColorContexts.First() : new ColorContext(PixelFormats.Bgra32)); }
private static BitmapSource LoadImage(string fileName, string extension, int size, bool forceSize = false) { switch (extension) { case ".ico": return(IconDecoder(fileName, size).Shrink(new System.Windows.Size(size, size))); default: { Uri uri = new Uri(fileName, UriKind.Absolute); int?decodePixelWidth = null; int?decodePixelHeight = null; if (!forceSize) { // Get the size of the original image. BitmapFrame bitmapFrame = BitmapFrame.Create(uri, BitmapCreateOptions.DelayCreation, BitmapCacheOption.None); double pw = bitmapFrame.PixelWidth; double ph = bitmapFrame.PixelHeight; if (pw > ph) { decodePixelWidth = (int)Math.Min(size * bitmapFrame.DpiX / 96, pw); } else { decodePixelHeight = (int)Math.Min(size * bitmapFrame.DpiY / 96, ph); } } // Load the thumbnail. BitmapImage img = new BitmapImage(); img.CacheOption = BitmapCacheOption.Default; img.BeginInit(); if (!forceSize) { if (decodePixelWidth != null) { img.DecodePixelWidth = decodePixelWidth.Value; } else { img.DecodePixelHeight = decodePixelHeight.Value; } } else { img.DecodePixelWidth = img.DecodePixelHeight = size; } img.UriSource = uri; img.EndInit(); return(img); } } }
/// <summary> /// Método que genera un reporte pdf de las transacciones del almacén pasado como parámetro. Comprueba /// que este seleccionado un almacén y que el almacén tenga transacciones registradas. /// </summary> /// <param name="a">Almacén del que realizar el reporte</param> private void GenerarReporte(Almacen a) { if (a != null) // debe seleccionarse un almacen { MovimientosVM m = new MovimientosVM(); // Comprobamos todas las transacciones existentes y las que contengan el almacen pasado // las dividimos en dos listas: transacciones de entrada y transacciones de salida List <Transaccion> transaccions = m.ListaTransacciones.ToList(); List <Transaccion> transaccionesEntrada = new List <Transaccion>(); List <Transaccion> transaccionesSalida = new List <Transaccion>(); foreach (Transaccion t in transaccions) { if (t.AlmacenN.Equals(a.Id)) { transaccionesEntrada.Add(t); } if (t.AlmacenV.Equals(a.Id)) { transaccionesSalida.Add(t); } } // Si existen transaccioness ya sean de entrada o salida if (transaccionesSalida.Count != 0 || transaccionesEntrada.Count != 0) { // Abrimeos el explorador de archivos // Indicamos donde vamos a guardar el documento System.Windows.Forms.SaveFileDialog saveFileDialog = new System.Windows.Forms.SaveFileDialog(); // filtar por ficheros pdf saveFileDialog.Filter = "PDF Files| *.pdf"; saveFileDialog.Title = (string)Application.Current.FindResource("guardarFichero"); saveFileDialog.ShowDialog(); try { if (saveFileDialog.FileName != "") // elegimos un fichero { // crear documento A4 con margenes Document doc = new Document(PageSize.A4, 50f, 50f, 60f, 50f); // indicamos donde guardar el documento PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(saveFileDialog.FileName, FileMode.Create)); writer.PageEvent = new PageEventHelper(); // título y el autor del fichero doc.AddTitle(saveFileDialog.FileName); doc.AddCreator(Usuario.InstanciaUser.User); // Abrimos el archivo doc.Open(); //Fuentes iTextSharp.text.Font font = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 11, iTextSharp.text.Font.NORMAL, BaseColor.BLACK); iTextSharp.text.Font fontTitulo = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 15, iTextSharp.text.Font.BOLD, BaseColor.BLACK); iTextSharp.text.Font fontSub = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 12, iTextSharp.text.Font.BOLD, BaseColor.BLACK); iTextSharp.text.Font fontCellHeaders = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.UNDEFINED, 11, iTextSharp.text.Font.BOLD, BaseColor.BLACK); //Titulo string mensaje = (string)Application.Current.FindResource("TRANSACCIONES"); doc.Add(new Paragraph(mensaje + " - " + a.Nombre, fontTitulo)); doc.Add(new Paragraph(new Chunk(new iTextSharp.text.pdf.draw.LineSeparator(2.0F, 65.3F, BaseColor.GRAY, Element.ALIGN_LEFT, 1)))); // Imagen try { string currentAssemblyPath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location); System.Windows.Media.Imaging.BitmapImage bitMapImagen = new System.Windows.Media.Imaging.BitmapImage(new Uri(String.Format("file:///{0}/KarmaIcon.png", currentAssemblyPath))); System.Drawing.Bitmap imagen; using (MemoryStream outStream = new MemoryStream()) { BitmapEncoder enc = new BmpBitmapEncoder(); enc.Frames.Add(BitmapFrame.Create(bitMapImagen)); enc.Save(outStream); System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(outStream); imagen = new System.Drawing.Bitmap(bitmap); } iTextSharp.text.Image jpg = iTextSharp.text.Image.GetInstance((System.Drawing.Image)imagen, BaseColor.BLACK); jpg.ScaleToFit(180f, 130f); //escalar jpg.SpacingBefore = 10f; jpg.SpacingAfter = 1f; jpg.SetAbsolutePosition(370, 715); doc.Add(jpg); } catch (Exception ex) { FicheroLog.Instance.EscribirFichero(ex.Message); } //Fecha - Autor Paragraph p = new Paragraph(DateTime.Now.ToLongDateString() + " | " + Usuario.InstanciaUser.User, font); p.Alignment = Element.ALIGN_LEFT; doc.Add(p); doc.Add(Chunk.NEWLINE); doc.Add(Chunk.NEWLINE); doc.Add(Chunk.NEWLINE); doc.Add(Chunk.NEWLINE); doc.Add(new Paragraph(new Chunk(new iTextSharp.text.pdf.draw.LineSeparator(2.0F, 100.0F, BaseColor.GRAY, Element.ALIGN_LEFT, 1)))); //TABLA SALIDAS int columnas = 4; PdfPTable tablaS = new PdfPTable(columnas); tablaS.TotalWidth = 495f; tablaS.LockedWidth = true; tablaS.DefaultCell.Padding = 5f; // titulo salidas mensaje = (string)Application.Current.FindResource("SALIDAS"); doc.Add(new Paragraph(mensaje, fontSub)); doc.Add(Chunk.NEWLINE); if (transaccionesSalida.Count != 0) // si hay transacciones { // Escribimos los titulos de las columnas mensaje = (string)Application.Current.FindResource("AlmacenDestino"); tablaS.AddCell(new Phrase(mensaje, fontCellHeaders)); mensaje = (string)Application.Current.FindResource("Fecha"); tablaS.AddCell(new Phrase(mensaje, fontCellHeaders)); mensaje = (string)Application.Current.FindResource("Producto"); tablaS.AddCell(new Phrase(mensaje, fontCellHeaders)); mensaje = (string)Application.Current.FindResource("Unidades"); tablaS.AddCell(new Phrase(mensaje, fontCellHeaders)); foreach (Transaccion t in transaccionesSalida) // por cada transaccion en las lista la añadimos a la tabla { tablaS.AddCell(new Phrase(t.AlmacenN, font)); tablaS.AddCell(new Phrase(t.Fecha.ToShortDateString(), font)); tablaS.AddCell(new Phrase(t.Producto, font)); tablaS.AddCell(new Phrase(t.Unidades.ToString(), font)); } } // añadir tabla de salidas al documento doc.Add(tablaS); doc.Add(Chunk.NEWLINE); doc.Add(Chunk.NEWLINE); doc.Add(Chunk.NEWLINE); doc.Add(Chunk.NEWLINE); doc.Add(Chunk.NEWLINE); //TABLA ENTRADAS PdfPTable tablaE = new PdfPTable(columnas); tablaE.TotalWidth = 495f; tablaE.LockedWidth = true; tablaE.DefaultCell.Padding = 5f; // titulo entradas mensaje = (string)Application.Current.FindResource("ENTRADAS"); doc.Add(new Paragraph(mensaje, fontSub)); doc.Add(Chunk.NEWLINE); if (transaccionesEntrada.Count != 0)// si hay transacciones { // Escribimos los titulos de las columnas mensaje = (string)Application.Current.FindResource("AlmacenOrigen"); tablaE.AddCell(new Phrase(mensaje, fontCellHeaders)); mensaje = (string)Application.Current.FindResource("Fecha"); tablaE.AddCell(new Phrase(mensaje, fontCellHeaders)); mensaje = (string)Application.Current.FindResource("Producto"); tablaE.AddCell(new Phrase(mensaje, fontCellHeaders)); mensaje = (string)Application.Current.FindResource("Unidades"); tablaE.AddCell(new Phrase(mensaje, fontCellHeaders)); foreach (Transaccion t in transaccionesEntrada) // por cada transaccion en las lista la añadimos a la tabla { tablaE.AddCell(new Phrase(t.AlmacenV, font)); tablaE.AddCell(new Phrase(t.Fecha.ToShortDateString(), font)); tablaE.AddCell(new Phrase(t.Producto, font)); tablaE.AddCell(new Phrase(t.Unidades.ToString(), font)); } } // añadir al documento doc.Add(tablaE); doc.Add(Chunk.NEWLINE); // cerrar doc.Close(); writer.Close(); // mensaje del reporte se ha creado correctamente mensajeBox = (string)Application.Current.FindResource("reporteAlmacen"); cabeceraInfo = (string)Application.Current.FindResource("informacion"); MessageBox.Show(mensajeBox, cabeceraInfo, MessageBoxButton.OK, MessageBoxImage.Information); } } catch (Exception e)// error al escribir el reporte { mensajeBox = (string)Application.Current.FindResource("reporteAbierto"); cabeceraInfo = (string)Application.Current.FindResource("error"); MessageBox.Show(mensajeBox, cabeceraInfo, MessageBoxButton.OK, MessageBoxImage.Error); FicheroLog.Instance.EscribirFichero(e.Message); } } else // no hay transacciones asociadas al almacen pasado { mensajeBox = (string)Application.Current.FindResource("almacenNoReporte"); MessageBox.Show(mensajeBox, cabeceraInfo, MessageBoxButton.OK, MessageBoxImage.Information); } } else // si no se ha seleccionado un almacen { mensajeBox = (string)Application.Current.FindResource("seleccionarAlmacenReporte"); MessageBox.Show(mensajeBox, cabeceraInfo, MessageBoxButton.OK, MessageBoxImage.Information); } }
public string[] GetExifDataStrings(string pathToImage) { Properties prop = new Properties(); string[] exif = new string[prop.ExifArraySize]; FileInfo info = new FileInfo(pathToImage); using (FileStream fileStream = new FileStream(pathToImage, FileMode.Open)) { BitmapSource img = BitmapFrame.Create(fileStream); BitmapMetadata metadata = (BitmapMetadata)img.Metadata; if (pathToImage.Contains("png")) { for (byte i = 0; i < 4; i++) { exif[i] = "Empty"; } } else { if (metadata.Title == null) { exif[0] = "Empty"; } else { exif[0] = metadata.Title.ToString(); } // check camera creator from metadata if (metadata.CameraManufacturer == null) { exif[1] = "Empty"; } else { exif[1] = metadata.CameraManufacturer.ToString(); } // check camera model from metadata if (metadata.CameraModel == null) { exif[2] = "Empty"; } else { exif[2] = metadata.CameraModel.ToString(); } // check file data maken from metadata if (metadata.DateTaken == null) { exif[3] = "Empty"; } else { exif[3] = metadata.DateTaken.ToString(); } } exif[4] = img.PixelWidth.ToString(); exif[5] = img.PixelHeight.ToString(); // convert file size from byte to Kbyte double KB = (double)info.Length / 1024; exif[6] = Math.Round(KB, 2).ToString(); // save filename exif[7] = info.Name.ToString(); } return(exif); }
private static BitmapDecoder GetDecoder(BitmapSource image, out GifFile gifFile) { gifFile = null; BitmapDecoder decoder = null; Stream stream = null; Uri uri = null; BitmapCreateOptions createOptions = BitmapCreateOptions.None; var bmp = image as BitmapImage; if (bmp != null) { createOptions = bmp.CreateOptions; if (bmp.StreamSource != null) { stream = bmp.StreamSource; } else if (bmp.UriSource != null) { uri = bmp.UriSource; if (bmp.BaseUri != null && !uri.IsAbsoluteUri) { uri = new Uri(bmp.BaseUri, uri); } } } else { BitmapFrame frame = image as BitmapFrame; if (frame != null) { decoder = frame.Decoder; Uri.TryCreate(frame.BaseUri, frame.ToString(), out uri); } } if (decoder == null) { if (stream != null) { stream.Position = 0; decoder = BitmapDecoder.Create(stream, createOptions, BitmapCacheOption.OnLoad); } else if (uri != null && uri.IsAbsoluteUri) { decoder = BitmapDecoder.Create(uri, createOptions, BitmapCacheOption.OnLoad); } } if (decoder is GifBitmapDecoder && !CanReadNativeMetadata(decoder)) { if (stream != null) { stream.Position = 0; gifFile = GifFile.ReadGifFile(stream, true); } else if (uri != null) { gifFile = DecodeGifFile(uri); } else { throw new InvalidOperationException("Can't get URI or Stream from the source. AnimatedSource should be either a BitmapImage, or a BitmapFrame constructed from a URI."); } } if (decoder == null) { throw new InvalidOperationException("Can't get a decoder from the source. AnimatedSource should be either a BitmapImage or a BitmapFrame."); } return(decoder); }
/// <summary> /// Images from any format supported by Microsoft Windows Imaging Component (WIC) to JPEG. /// </summary> /// <remarks> /// .heic files are supported if the Windows HEIC and HEIF codecs are installed. /// Metadata is preserved. /// </remarks> public static void ConvertToJpeg(string srcFilename, string dstFilename) { // First, copy out all of the writable metadata properties var metadata = new Dictionary <Interop.PropertyKey, object>(); using (var ps = WinShell.PropertyStore.Open(srcFilename)) { int count = ps.Count; for (int i = 0; i < count; ++i) { var key = ps.GetAt(i); if (ps.IsPropertyWriteable(key)) { metadata.Add(key, ps.GetValue(key)); } } } // Set the rotation transformation appropriately var rotation = Rotation.Rotate0; bool flipHorizontal = false; bool flipVertical = false; if (metadata.ContainsKey(PropertyKeys.Orientation)) { switch ((ushort)metadata[PropertyKeys.Orientation]) { case 2: // FlipHorizontal flipHorizontal = true; break; case 3: // Rotated 180 rotation = Rotation.Rotate180; break; case 4: // FlipVertical flipVertical = true; break; case 6: // Rotated 270 rotation = Rotation.Rotate90; break; case 8: // Rotated 90 rotation = Rotation.Rotate270; break; } metadata[PropertyKeys.Orientation] = (ushort)1; } // Convert the image try { using (var stream = new FileStream(srcFilename, FileMode.Open, FileAccess.Read, FileShare.Read)) { var decoder = BitmapDecoder.Create(stream, BitmapCreateOptions.None, BitmapCacheOption.Default); BitmapFrame frame = decoder.Frames[0]; // If rotating, then strip any thumbnail if (rotation != Rotation.Rotate0 || flipHorizontal || flipVertical) { frame = BitmapFrame.Create((BitmapSource)frame, null, (BitmapMetadata)frame.Metadata, frame.ColorContexts); } // Encode to JPEG using (var dstStream = new FileStream(dstFilename, FileMode.CreateNew, FileAccess.Write, FileShare.None)) { var encoder = new JpegBitmapEncoder(); encoder.Rotation = rotation; encoder.FlipHorizontal = flipHorizontal; encoder.FlipVertical = flipVertical; encoder.Frames.Add(frame); encoder.Save(dstStream); } } } catch (Exception err) { throw new ApplicationException($"Failed to convert image {srcFilename}.", err); } // Update the metadata using (var ps = WinShell.PropertyStore.Open(dstFilename, true)) { foreach (var pair in metadata) { if (ps.IsPropertyWriteable(pair.Key)) // Might have been writeable at the source format but not on the destination { ps.SetValue(pair.Key, pair.Value); } } ps.Commit(); } }
private void SetImageSource(UserAvatarModel context, IUserIdentity userIdentity) { if (TeamCodingPackage.Current.Settings.UserSettings.UserTabDisplay == UserSettings.UserDisplaySetting.Avatar) { if (userIdentity.ImageBytes != null) { using (var MS = new MemoryStream(userIdentity.ImageBytes)) { var bitmap = new BitmapImage(); bitmap.BeginInit(); bitmap.StreamSource = MS; bitmap.CacheOption = BitmapCacheOption.OnLoad; bitmap.EndInit(); context.AvatarImageSource = UrlImages[userIdentity.ImageUrl] = bitmap; } } else if (userIdentity.ImageUrl != null) { if (UrlImages.ContainsKey(userIdentity.ImageUrl)) { context.AvatarImageSource = UrlImages[userIdentity.ImageUrl]; } else { ThreadHelper.JoinableTaskFactory.RunAsync(async() => { try { var request = await TeamCodingPackage.Current.HttpClient.GetAsync(userIdentity.ImageUrl); if (!request.IsSuccessStatusCode) { return; } var imageStream = await request.Content.ReadAsStreamAsync(); context.AvatarImageSource = UrlImages[userIdentity.ImageUrl] = BitmapFrame.Create(imageStream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad); } catch (Exception ex) when(!System.Diagnostics.Debugger.IsAttached) { TeamCodingPackage.Current.Logger.WriteError(ex); } }); } } } else { context.AvatarImageSource = null; } }
public MainWindow() { InitializeComponent(); Uri iconUri = new Uri(@"D:\Hackathon_Live_Project\exit0\source\app\Logo.png", UriKind.RelativeOrAbsolute); this.Icon = BitmapFrame.Create(iconUri); // Create grabber. _grabber = new FrameGrabber <LiveCameraResult>(); // Set up a listener for when the client receives a new frame. _grabber.NewFrameProvided += (s, e) => { if (_mode == AppMode.EmotionsWithClientFaceDetect) { // Local face detection. var rects = _localFaceDetector.DetectMultiScale(e.Frame.Image); // Attach faces to frame. e.Frame.UserData = rects; } // The callback may occur on a different thread, so we must use the // MainWindow.Dispatcher when manipulating the UI. this.Dispatcher.BeginInvoke((Action)(() => { // Display the image in the left pane. LeftImage.Source = e.Frame.Image.ToBitmapSource(); // If we're fusing client-side face detection with remote analysis, show the // new frame now with the most recent analysis available. if (_fuseClientRemoteResults) { RightImage.Source = VisualizeResult(e.Frame); } })); // See if auto-stop should be triggered. if (Properties.Settings.Default.AutoStopEnabled && (DateTime.Now - _startTime) > Properties.Settings.Default.AutoStopTime) { _grabber.StopProcessingAsync(); } }; // Set up a listener for when the client receives a new result from an API call. _grabber.NewResultAvailable += (s, e) => { this.Dispatcher.BeginInvoke((Action)(() => { if (e.TimedOut) { MessageArea.Text = "API call timed out."; } else if (e.Exception != null) { string apiName = ""; string message = e.Exception.Message; var faceEx = e.Exception as FaceAPIException; var emotionEx = e.Exception as Microsoft.ProjectOxford.Common.ClientException; var visionEx = e.Exception as Microsoft.ProjectOxford.Vision.ClientException; if (faceEx != null) { apiName = "Face"; message = faceEx.ErrorMessage; } else if (emotionEx != null) { apiName = "Emotion"; message = emotionEx.Error.Message; } else if (visionEx != null) { apiName = "Computer Vision"; message = visionEx.Error.Message; } MessageArea.Text = string.Format("{0} API call failed on frame {1}. Exception: {2}", apiName, e.Frame.Metadata.Index, message); } else { _latestResultsToDisplay = e.Analysis; // Display the image and visualization in the right pane. if (!_fuseClientRemoteResults) { RightImage.Source = VisualizeResult(e.Frame); } } })); }; // Create local face detector. _localFaceDetector.Load("Data/haarcascade_frontalface_alt2.xml"); Task.Run(() => this.LoadPersonGroup()).Wait(); }
private static BitmapDecoder GetDecoder(BitmapSource image, out GifFile gifFile) { gifFile = null; BitmapDecoder decoder = null; Stream stream = null; Uri uri = null; BitmapCreateOptions createOptions = BitmapCreateOptions.None; var bmp = image as BitmapImage; if (bmp != null) { createOptions = bmp.CreateOptions; if (bmp.StreamSource != null) { stream = bmp.StreamSource; } else if (bmp.UriSource != null) { uri = bmp.UriSource; if (bmp.BaseUri != null && !uri.IsAbsoluteUri) { uri = new Uri(bmp.BaseUri, uri); } } } else { BitmapFrame frame = image as BitmapFrame; if (frame != null) { decoder = frame.Decoder; Uri.TryCreate(frame.BaseUri, frame.ToString(), out uri); } } if (decoder == null) { if (stream != null) { stream.Position = 0; decoder = BitmapDecoder.Create(stream, createOptions, BitmapCacheOption.OnLoad); } else if (uri != null && uri.IsAbsoluteUri) { decoder = BitmapDecoder.Create(uri, createOptions, BitmapCacheOption.OnLoad); } } if (decoder is GifBitmapDecoder && !CanReadNativeMetadata(decoder)) { if (stream != null) { stream.Position = 0; gifFile = GifFile.ReadGifFile(stream, true); } else if (uri != null) { gifFile = DecodeGifFile(uri); } } return(decoder); }
public Photo(string path) { _path = path; _source = new Uri(path); _image = BitmapFrame.Create(_source); }
private void SetImageGIFSource() { if (null != _Bitmap) { ImageAnimator.StopAnimate(_Bitmap, OnFrameChanged); _Bitmap = null; } if (String.IsNullOrEmpty(GIFSource)) { //Turn off if GIF set to null or empty Source = null; InvalidateVisual(); return; } if (File.Exists(GIFSource)) { _Bitmap = (Bitmap)System.Drawing.Image.FromFile(GIFSource); } else { //My code bool isImageFound = false; try { BitmapImage logo = new BitmapImage(); logo.BeginInit(); logo.UriSource = new Uri(@"pack://application:,,,/" + Assembly.GetExecutingAssembly().GetName().Name + ";component/" + GIFSource, UriKind.Absolute); logo.EndInit(); var encoder = new PngBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(logo)); var stream = new MemoryStream(); encoder.Save(stream); stream.Flush(); var image = new System.Drawing.Bitmap(stream); _Bitmap = image; isImageFound = true; } catch (Exception ex) { Console.WriteLine(ex.Message); } if (!isImageFound) { //Support looking for embedded resources Assembly assemblyToSearch = Assembly.GetAssembly(GetType()); _Bitmap = GetBitmapResourceFromAssembly(assemblyToSearch); if (null == _Bitmap) { assemblyToSearch = Assembly.GetCallingAssembly(); _Bitmap = GetBitmapResourceFromAssembly(assemblyToSearch); if (null == _Bitmap) { assemblyToSearch = Assembly.GetEntryAssembly(); _Bitmap = GetBitmapResourceFromAssembly(assemblyToSearch); if (null == _Bitmap) { throw new FileNotFoundException("GIF Source was not found.", GIFSource); } } } } } if (PlayAnimation) { ImageAnimator.Animate(_Bitmap, OnFrameChanged); } }
void InitGameBoard() { //Set the Height and Width of this program this.Height = 713; this.Width = 533; //Set Title and Icon this.Title = "Chinese Chess"; this.Icon = BitmapFrame.Create(new Uri("pack://*****:*****@"pack://application:,,,/src/img/board.png"))); //Init the first infoLine textInfoLine0.Text = "Welcome!"; //Set the InfoLine's Default Text textInfoLine0.FontSize = 20; //It's FontSize textInfoLine0.HorizontalAlignment = HorizontalAlignment.Center; //Set it as the center of the Horizontal infoStackPanel.Children.Add(textInfoLine0); //Add it to the stackPanel //And the second one, same as above textInfoLine1.Text = "Waiting..."; textInfoLine1.FontSize = 18; textInfoLine1.VerticalAlignment = VerticalAlignment.Center; textInfoLine1.HorizontalAlignment = HorizontalAlignment.Center; textInfoLine1.TextAlignment = TextAlignment.Center; infoStackPanel.Children.Add(textInfoLine1); //Set two buttons var infoStyle = FindResource("infoButtonStyle") as Style; //Find the pre-written style in xaml leftButton.Content = "CLOSE"; //Default Text leftButton.FontSize = 16; leftButton.Style = infoStyle; //Set the Style of this button leftButton.Height = 40; //It's Height and width leftButton.Width = 80; leftButton.VerticalAlignment = VerticalAlignment.Center; //In the Center of the space leftButton.HorizontalAlignment = HorizontalAlignment.Center; leftButton.Click += new RoutedEventHandler(left_button_Click); //Add a Event Grid.SetColumn(leftButton, 0); //Set it should be the left of the infoGrid rightButton.Content = "START"; rightButton.FontSize = 16; rightButton.Style = infoStyle; rightButton.Height = 40; rightButton.Width = 80; rightButton.VerticalAlignment = VerticalAlignment.Center; rightButton.HorizontalAlignment = HorizontalAlignment.Center; rightButton.Click += new RoutedEventHandler(right_button_Click); Grid.SetColumn(rightButton, 2); infoGrid.Children.Add(leftButton); infoGrid.Children.Add(rightButton); this.Content = mainWindow;//Set the content to the mainGrid. }
private void CreateAndShowMainWindow() { // Create the application's main window _mainWindow = new Window { Title = "BMP Imaging Sample" }; var mySv = new ScrollViewer(); var width = 128; var height = width; var stride = width / 8; var pixels = new byte[height * stride]; // Try creating a new image with a custom palette. var colors = new List <Color> { Colors.Red, Colors.Blue, Colors.Green }; var myPalette = new BitmapPalette(colors); // Creates a new empty image with the pre-defined palette var image = BitmapSource.Create( width, height, 96, 96, PixelFormats.Indexed1, myPalette, pixels, stride); var stream = new FileStream("new.bmp", FileMode.Create); var encoder = new BmpBitmapEncoder(); var myTextBlock = new TextBlock { Text = "Codec Author is: " + encoder.CodecInfo.Author }; encoder.Frames.Add(BitmapFrame.Create(image)); encoder.Save(stream); // Open a Stream and decode a BMP image Stream imageStreamSource = new FileStream("tulipfarm.bmp", FileMode.Open, FileAccess.Read, FileShare.Read); var decoder = new BmpBitmapDecoder(imageStreamSource, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default); BitmapSource bitmapSource = decoder.Frames[0]; // Draw the Image var myImage = new Image { Source = bitmapSource, Stretch = Stretch.None, Margin = new Thickness(20) }; // Open a Uri and decode a BMP image var myUri = new Uri("tulipfarm.bmp", UriKind.RelativeOrAbsolute); var decoder2 = new BmpBitmapDecoder(myUri, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default); BitmapSource bitmapSource2 = decoder2.Frames[0]; // Draw the Image var myImage2 = new Image { Source = bitmapSource2, Stretch = Stretch.None, Margin = new Thickness(20) }; // Define a StackPanel to host the decoded BMP images var myStackPanel = new StackPanel { Orientation = Orientation.Vertical, VerticalAlignment = VerticalAlignment.Stretch, HorizontalAlignment = HorizontalAlignment.Stretch }; // Add the Image and TextBlock to the parent Grid myStackPanel.Children.Add(myImage); myStackPanel.Children.Add(myImage2); myStackPanel.Children.Add(myTextBlock); // Add the StackPanel as the Content of the Parent Window Object mySv.Content = myStackPanel; _mainWindow.Content = mySv; _mainWindow.Show(); }
private void CaptureScreen(Point point) { // 座標変換 var start = PointToScreen(_position); var end = PointToScreen(point); // キャプチャエリアの取得 var x = start.X < end.X ? (int)start.X : (int)end.X; var y = start.Y < end.Y ? (int)start.Y : (int)end.Y; var width = (int)Math.Abs(end.X - start.X); var height = (int)Math.Abs(end.Y - start.Y); if (width == 0 || height == 0) { return; } // スクリーンイメージの取得 using (var bmp = new System.Drawing.Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format24bppRgb)) using (var graph = System.Drawing.Graphics.FromImage(bmp)) { // 画面をコピーする graph.CopyFromScreen(new System.Drawing.Point(x, y), new System.Drawing.Point(), bmp.Size); // イメージの保存 string folder = epubDirectory.Replace(".epub", "") + "\\LearningRecord"; if (!Directory.Exists(folder)) { Directory.CreateDirectory(folder); } string searchPageName = pagePath.Replace(epubDirectory + "\\OEBPS\\", ""); searchPageName = searchPageName.Replace("image\\", ""); //保存先に左ページ.右ページ.pngが何枚保存されているか調べる string[] files = System.IO.Directory.GetFiles(folder, searchPageName + "*" + ".png", System.IO.SearchOption.TopDirectoryOnly); int j = 0; foreach (string f in files) { //MessageBox.Show(f); epubImage[j] = f; j++; } string k = null; if (j < 100) { k = "0" + j; if (j < 10) { k = "0" + k; } } //すでに保存されている枚数に応じて番号をつけて保存 bmp.Save(System.IO.Path.Combine(folder, searchPageName + "_" + k + ".png"), System.Drawing.Imaging.ImageFormat.Png); savedFilePath = folder + "\\" + searchPageName + "_" + k + ".png"; } //「おくる」ボタンをクリックしていた場合は、クリップボードにコピー if (needToClip) { MemoryStream data = new MemoryStream(File.ReadAllBytes(savedFilePath)); WriteableBitmap bmpim = new WriteableBitmap(BitmapFrame.Create(data)); data.Close(); Clipboard.SetImage(bmpim); bool a = File.Exists(savedFilePath); //File.Delete(savedFilePath); //DinoMainWindow dinoMain = new DinoMainWindow(); //dinoMain.Show(); //dinoMain.pasteClipBorad(subjectName, unitName, savedFilePath); } }
/// <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); }
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) { var child = VisualTreeHelper.GetChild(dragCanvas, index); var firstChild = VisualTreeHelper.GetChild(child, 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(child as Visual); minX = childBounds.X < minX ? childBounds.X : minX; minY = childBounds.Y < minY ? childBounds.Y : minY; childBounds.X = (double)(child as Visual).GetValue(Canvas.LeftProperty); childBounds.Y = (double)(child 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) { } }
private void SendClipboard() { if (Clipboard.ContainsText()) { var clipText = Clipboard.GetText(); TaskbarManager.Instance.SetProgressState(TaskbarProgressBarState.Indeterminate); new Thread(() => { App.ViewModel.API.SendMessage("clip", "Clipboard Text", "", clipText); FlashProgress(TaskbarProgressBarState.Normal); }).Start(); } else if (Clipboard.ContainsImage()) { try { TaskbarManager.Instance.SetProgressState(TaskbarProgressBarState.Indeterminate); var clipimg = Clipboard.GetImage(); string path = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "S2WP7_" + new Random().Next(0, int.MaxValue) + "_Clipboard"); if (Settings.Get("Clipboard_PNG", true)) { path += ".png"; } else { path += ".jpg"; } using (FileStream stream = new FileStream(path, FileMode.Create)) { BitmapEncoder encoder; if (Settings.Get("Clipboard_PNG", true)) { encoder = new PngBitmapEncoder(); (encoder as PngBitmapEncoder).Interlace = PngInterlaceOption.On; } else { encoder = new JpegBitmapEncoder(); (encoder as JpegBitmapEncoder).QualityLevel = Settings.Get("JpegQuality", 95); } encoder.Frames.Add(BitmapFrame.Create(clipimg)); encoder.Save(stream); } Trace.WriteLine("Image saved at: " + path); var t = new Thread(() => { try { Uploader.UploadFile(path, ret => { if (ret.URL == null) { Trace.WriteLine("*** URL is null"); FlashProgress(TaskbarProgressBarState.Error); } else { App.ViewModel.API.SendMessage("img", "Clipboard Image", ret.URL, ""); FlashProgress(TaskbarProgressBarState.Normal); } }, () => { FlashProgress(TaskbarProgressBarState.Paused); }); } catch (Exception ex) { FlashProgress(TaskbarProgressBarState.Error); Trace.WriteLine("Error uploading file: " + ex); } }); t.SetApartmentState(ApartmentState.STA); t.Start(); } catch (Exception ex) { Trace.WriteLine("Error saving image:" + ex); } } else if (Clipboard.ContainsFileDropList()) { UploadFileList(GetFilesFromDropList(Clipboard.GetFileDropList())); } else { FlashProgress(TaskbarProgressBarState.Error); Trace.WriteLine("Clipboard content is not valid"); } }
private void SetupComponents() { #region FlipViewPersona Image[] aFlipViewAvatarArray = new Image[28]; for (int i = 0; i < 28; i++) { ImageSource source = BitmapFrame.Create( new Uri("pack://application:,,,/OfflineServer;component/images/NFSW_Avatars/Avatar_" + i.ToString() + ".png", UriKind.Absolute), BitmapCreateOptions.DelayCreation, BitmapCacheOption.OnDemand); source.Freeze(); Image avatarImage = new Image() { HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center, Source = source }; aFlipViewAvatarArray[i] = avatarImage; } FlipViewPersonaImage.ItemsSource = aFlipViewAvatarArray; Binding indexBind = new Binding() { Path = new PropertyPath("ActivePersona.IconIndex"), UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged, Mode = BindingMode.TwoWay, Delay = 1000, Source = Access.CurrentSession }; BindingOperations.SetBinding(FlipViewPersonaImage, FlipView.SelectedIndexProperty, indexBind); #endregion #region MetroTile -> Random Persona Info tRandomPersonaInfo_Tick(null, null); RandomPersonaInfo.Tick += new EventHandler(tRandomPersonaInfo_Tick); RandomPersonaInfo.Interval = new TimeSpan(0, 0, 10); RandomPersonaInfo.Start(); #endregion #region carDialog Binding lBindSelect = new Binding() { Path = new PropertyPath("language.Select"), Mode = BindingMode.OneWay, Source = Access.dataAccess.appSettings.uiSettings }; Binding lBindCancel = new Binding() { Path = new PropertyPath("language.Cancel"), Mode = BindingMode.OneWay, Source = Access.dataAccess.appSettings.uiSettings }; Binding lBindSelectCar = new Binding() { Path = new PropertyPath("language.AddACarText"), Mode = BindingMode.OneWay, Source = Access.dataAccess.appSettings.uiSettings }; ComboBox carComboBox = new ComboBox(); carComboBox.SetValue(Canvas.LeftProperty, 5d); carComboBox.SetValue(Canvas.TopProperty, 20d); carComboBox.Width = 297d; carComboBox.ItemsSource = CarDefinitions.physicsProfileHashNormal.Values; carComboBox.SelectedIndex = 0; Button selectButton = new Button(); selectButton.SetValue(Canvas.LeftProperty, 148d); selectButton.SetValue(Canvas.TopProperty, 54d); selectButton.Width = 80d; selectButton.Click += (object sender, RoutedEventArgs routedEventArgs) => { selectButton.IsEnabled = false; CarEntity carEntity = new CarEntity(); carEntity.baseCarId = CarDefinitions.baseCarId.FirstOrDefault(key => key.Value == carComboBox.SelectedItem.ToString()).Key; carEntity.carClassHash = CarClass.getHashFromCarClass("E"); carEntity.durability = 100; carEntity.heatLevel = 1; carEntity.paints = new List <CustomPaintTrans>().SerializeObject(); carEntity.performanceParts = new List <PerformancePartTrans>().SerializeObject(); carEntity.physicsProfileHash = CarDefinitions.physicsProfileHashNormal.FirstOrDefault(key => key.Value == carComboBox.SelectedItem.ToString()).Key; carEntity.rating = 123; carEntity.resalePrice = 0; carEntity.skillModParts = new List <SkillModPartTrans>().SerializeObject(); carEntity.vinyls = new List <CustomVinylTrans>().SerializeObject(); carEntity.visualParts = new List <VisualPartTrans>().SerializeObject(); PersonaManagement.addCar(carEntity); DialogManager.HideMetroDialogAsync(this, carDialog); selectButton.IsEnabled = true; }; Button cancelButton = new Button(); cancelButton.SetValue(Canvas.LeftProperty, 233d); cancelButton.SetValue(Canvas.TopProperty, 54d); cancelButton.Width = 70d; cancelButton.Click += (object sender, RoutedEventArgs routedEventArgs) => { DialogManager.HideMetroDialogAsync(this, carDialog); }; Canvas canvas = new Canvas(); canvas.Children.Add(carComboBox); canvas.Children.Add(selectButton); canvas.Children.Add(cancelButton); carDialog = new CustomDialog(); carDialog.Height = 200d; carDialog.Content = canvas; // internationalization BindingOperations.SetBinding(carDialog, CustomDialog.TitleProperty, lBindSelectCar); BindingOperations.SetBinding(selectButton, Button.ContentProperty, lBindSelect); BindingOperations.SetBinding(cancelButton, Button.ContentProperty, lBindCancel); #endregion #region nfswDialog TextBlock text = new TextBlock(); text.HorizontalAlignment = HorizontalAlignment.Center; text.VerticalAlignment = VerticalAlignment.Center; text.TextAlignment = TextAlignment.Center; text.FontSize = 32d; text.MaxWidth = 480d; Viewbox viewBox = new Viewbox(); viewBox.StretchDirection = StretchDirection.DownOnly; viewBox.Width = 480d; viewBox.Child = text; nfswDialog = new CustomDialog(); nfswDialog.Height = 200d; nfswDialog.Width = 520d; nfswDialog.HorizontalContentAlignment = HorizontalAlignment.Center; nfswDialog.VerticalContentAlignment = VerticalAlignment.Center; nfswDialog.Content = viewBox; Binding bindTag = new Binding() { Path = new PropertyPath("Tag"), Mode = BindingMode.OneWay, Source = nfswDialog }; BindingOperations.SetBinding(text, TextBlock.TextProperty, bindTag); #endregion }
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 { SafeDisposeImage(ref bitmap); } } } }
void Present() { if (tracer.LastRenderImage == null || tracer.LastRenderImage.Values == null) { return; } bmp.Dispatcher.Invoke(new Action(() => { Stopwatch sw = Stopwatch.StartNew(); bmp.Lock(); unsafe { if (scaleColorRange) { double maxLen = 0; for (int y = 0; y < tracer.ViewportSize.height; y++) { for (int x = 0; x < tracer.ViewportSize.width; x++) { double len = tracer.LastRenderImage.Values [x, y].Length; if (len > maxLen) { maxLen = len; } } } double maxLenInv = 1 / maxLen; for (int y = 0; y < tracer.ViewportSize.height; y++) { for (int x = 0; x < tracer.ViewportSize.width; x++) { double3 color = tracer.LastRenderImage.Values [x, y] * maxLenInv * 255; int r = Math.Max(0, Math.Min(255, ( int )color.r)); int g = Math.Max(0, Math.Min(255, ( int )color.g)); int b = Math.Max(0, Math.Min(255, ( int )color.b)); int intColor = b | (g << 8) | (r << 16); *((( int * )bmp.BackBuffer) + y * tracer.ViewportSize.width + x) = intColor; } } } else { for (int y = 0; y < tracer.ViewportSize.height; y++) { for (int x = 0; x < tracer.ViewportSize.width; x++) { double3 color = tracer.LastRenderImage.Values [x, y] * 255; int r = Math.Max(0, Math.Min(255, color.r.PreciseRound())); int g = Math.Max(0, Math.Min(255, color.g.PreciseRound())); int b = Math.Max(0, Math.Min(255, color.b.PreciseRound())); int intColor = b | (g << 8) | (r << 16); *((( int * )bmp.BackBuffer) + y * tracer.ViewportSize.width + x) = intColor; } } } } bmp.AddDirtyRect(new Int32Rect(0, 0, tracer.ViewportSize.width, tracer.ViewportSize.height)); bmp.Unlock(); sw.Stop(); Console.WriteLine("Present time: {0}", sw.Elapsed); lastPresentTime = sw.Elapsed; if (continuousRendering || renderTask.IsCompleted) { if (!IO.Directory.Exists("renders")) { IO.Directory.CreateDirectory("renders"); } using (IO.FileStream fs = IO.File.OpenWrite(string.Format(@"renders\{0}.bmp", DateTime.Now.Ticks))) { BmpBitmapEncoder bmpEncoder = new BmpBitmapEncoder(); bmpEncoder.Frames.Add(BitmapFrame.Create(bmp)); bmpEncoder.Save(fs); }; } })); }