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. }
protected override GeneratorResult ProcessInternal(ThumbnailBannerGeneratorSettings settings, GeneratorEntry entry) { try { entry.State = JobStates.Processing; _wrapper = new FfmpegWrapper(FfmpegExePath); var videoInfo = _wrapper.GetVideoInfo(settings.VideoFile); if (!videoInfo.IsGoodEnough()) { entry.State = JobStates.Done; entry.DoneType = JobDoneTypes.Failure; entry.Update("Failed", 1); return(GeneratorResult.Failed()); } TimeSpan duration = videoInfo.Duration; TimeSpan intervall = duration.Divide(settings.Columns * settings.Rows + 1); var frameArguments = new FrameConverterArguments { Width = 800, Intervall = intervall.TotalSeconds, StatusUpdateHandler = (progress) => { entry.Update(null, progress); }, InputFile = settings.VideoFile, OutputDirectory = FfmpegWrapper.CreateRandomTempDirectory() }; entry.Update("Extracting Frames", 0); var frames = _wrapper.ExtractFrames(frameArguments); if (_canceled) { return(GeneratorResult.Failed()); } entry.Update("Saving Thumbnails", 1); List <ThumbnailBannerGeneratorImage> images = new List <ThumbnailBannerGeneratorImage>(); foreach (var frame in frames) { images.Add(new ThumbnailBannerGeneratorImage { Image = frame.Item2, Position = frame.Item1 }); } ThumbnailBannerGeneratorData data = new ThumbnailBannerGeneratorData(); data.Settings = settings; data.Images = images.ToArray(); data.VideoName = settings.VideoFile; data.VideoInfo = videoInfo; data.FileSize = new FileInfo(settings.VideoFile).Length; var result = CreateBanner(data); JpegBitmapEncoder encoder = new JpegBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create((BitmapSource)result)); using (FileStream stream = new FileStream(settings.OutputFile, FileMode.Create)) encoder.Save(stream); Directory.Delete(frameArguments.OutputDirectory); entry.DoneType = JobDoneTypes.Success; entry.Update("Done", 1); return(GeneratorResult.Succeeded(settings.OutputFile)); } catch (Exception) { entry.Update("Failed", 1); entry.DoneType = JobDoneTypes.Failure; return(GeneratorResult.Failed()); } finally { entry.State = JobStates.Done; if (_canceled) { entry.DoneType = JobDoneTypes.Cancelled; entry.Update("Cancelled", 1); } } }
void Worker_DoWork(object sender, DoWorkEventArgs e) { List <object> args = e.Argument as List <object>; int Errors = 0; object NamingMethod = args[0]; int i = 0; foreach (string path in (string[])args[1]) { i++; try { // Get Directory, Name and Extension of File string dir = Path.GetDirectoryName(path); string name = Path.GetFileNameWithoutExtension(path); string ext = Path.GetExtension(path); // Convert extension to lowercase if (ext.Any(char.IsUpper)) { ext = ext.ToLower(); } // Get Date DateTime dateTaken; if (ext == ".mp4" || ext == ".mov" || ext == ".avi" || ext == ".mts" || ext == ".m2ts") { DateTime fileCreatedDate = File.GetCreationTime(path); DateTime fileChangedDate = File.GetLastWriteTime(path); if (fileChangedDate < fileCreatedDate) { dateTaken = fileChangedDate; } else { dateTaken = fileCreatedDate; } } else { using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.Read)) { BitmapSource img = BitmapFrame.Create(fs); BitmapMetadata md = (BitmapMetadata)img.Metadata; string date = md.DateTaken; if (string.IsNullOrEmpty(date)) { (sender as BackgroundWorker).ReportProgress(i, "エ" + "Kein Aufnahmedatum für " + Path.GetFileName(path) + " gefunden." + Environment.NewLine); Errors++; continue; } dateTaken = DateTime.Parse(date); } } ChooseName: string newname = ""; if (ext == ".mp4" || ext == ".mov" || ext == ".avi" || ext == ".mts" || ext == ".m2ts") { newname = "VID_"; } if (NamingMethod == ImgRenameMichael) { newname += Number2String(dateTaken.Year - 1999, true) + Number2String(dateTaken.Month, true); int Day = dateTaken.Day; if (Day <= 9) { newname += Day; } else { newname += Number2String(Day - 9, true); } newname += (dateTaken.Hour * 3600 + dateTaken.Minute * 60 + dateTaken.Second); } else if (NamingMethod == img_date_time) { if (ext != ".mp4" && ext != ".mov" && ext != ".avi" && ext != ".mts" && ext != ".m2ts") { newname = "IMG_"; } newname += dateTaken.ToString("yyyyMMdd") + "_" + dateTaken.ToString("HHmmss"); } string newpath = Path.Combine(dir, dateTaken.ToString("yyyy-MM-dd"), newname + ext); Directory.CreateDirectory(Path.Combine(dir, dateTaken.ToString("yyyy-MM-dd"))); if (File.Exists(newpath)) { dateTaken = dateTaken.AddSeconds(1); goto ChooseName; } File.Move(path, newpath); (sender as BackgroundWorker).ReportProgress(i, Path.GetFileName(path) + " wurde nach " + Path.Combine(dateTaken.ToString("yyyy-MM-dd"), newname + ext) + " verschoben." + Environment.NewLine); } catch (Exception exc) { (sender as BackgroundWorker).ReportProgress(i, "エ" + "Fehler: " + exc + Environment.NewLine); Errors++; continue; } } (sender as BackgroundWorker).ReportProgress(i, Environment.NewLine); if (Errors == 1) { (sender as BackgroundWorker).ReportProgress(i, "エ" + "Abgeschlossen mit einem Fehler." + Environment.NewLine); } else if (Errors > 1) { (sender as BackgroundWorker).ReportProgress(i, "エ" + "Abgeschlossen mit " + Errors + " Fehlern." + Environment.NewLine); } else { (sender as BackgroundWorker).ReportProgress(i, "Abgeschlossen ohne Fehler." + Environment.NewLine); } e.Result = true; }
/// <summary> /// Adding the new car asynchronously. /// </summary> /// <returns></returns> private async Task AddCarAsync() { using (var a9 = new Asphalt9Entities()) { using (var transaction = a9.Database.BeginTransaction()) { try { // creating new entity with the given car information by the user. var newCar = new Grande { Brand = Car.CarBrand, CarName = Car.CarName, CarClass = Car.CarClass, CarType = Enum.Parse(typeof(CarType), Car.Type).ToString(), Fuel = Car.Fuel, CarImage = string.Concat(Car.CarClass.ToLower(), "_", ImageName), Refill = Car.Refill, ReleaseDate = Car.ReleaseDate, Stars = Car.Stars, // every single grande entity has the links with other entities via foreign key created in database. Blueprint = new Entities.Blueprint() { FirstStarBP = Car.Blueprints.FirstStar, SecondStarBP = Car.Blueprints.SecondStar, ThirdStarBP = Car.Blueprints.ThirdStar, FourthStarBP = Car.Blueprints.FourthStar, FifthStarBP = Car.Blueprints.FifthStar, SixthStarBP = Car.Blueprints.SixthStar, TotalBP = Car.Blueprints.Total }, StockDetail = new StockDetail() { TopSpeed = Car.Performance.StockTopSpeed, Acceleration = Car.Performance.StockAcceleration, Handling = Car.Performance.StockHandling, Nitro = Car.Performance.StockNitro, }, MaxDetail = new MaxDetail() { TopSpeed = Car.Performance.MaxTopSpeed, Acceleration = Car.Performance.MaxAcceleration, Handling = Car.Performance.MaxHandling, Nitro = Car.Performance.MaxNitro, }, StarRank = new StarRank() { StockStarRank = Car.Ranks.Stock, FirstStarRank = Car.Ranks.FirstStar, SecondStarRank = Car.Ranks.SecondStar, ThirdStarRank = Car.Ranks.ThirdStar, FourthStarRank = Car.Ranks.FourthStar, FifthStarRank = Car.Ranks.FifthStar, SixthStarRank = Car.Ranks.SixthStar, Max = Car.Ranks.Max }, Upgrade = new Upgrade() { Stage1 = Car.Upgrades.Stage0, Stage2 = Car.Upgrades.Stage1, Stage3 = Car.Upgrades.Stage2, Stage4 = Car.Upgrades.Stage3, Stage5 = Car.Upgrades.Stage4, Stage6 = Car.Upgrades.Stage5, Stage7 = Car.Upgrades.Stage6, Stage8 = Car.Upgrades.Stage7, Stage9 = Car.Upgrades.Stage8, Stage10 = Car.Upgrades.Stage9, Stage11 = Car.Upgrades.Stage10, Stage12 = Car.Upgrades.Stage11, Stage13 = Car.Upgrades.Stage12, Total = Car.Upgrades.TotalStagesCost }, UncommonPart = new UncommonPart() { Cost = Car.AdditionalParts.UncommonCost, Quantity = Car.AdditionalParts.UncommonQuantity, TotalCost = Car.AdditionalParts.UncommonTotalCost }, RarePart = new RarePart() { Cost = Car.AdditionalParts.RareCost, Quantity = Car.AdditionalParts.RareQuantity, TotalCost = Car.AdditionalParts.RareTotalCost }, EpicPart = new EpicPart() { Cost = Car.AdditionalParts.EpicCost, Quantity = Car.AdditionalParts.EpicQuantity, TotalCost = Car.AdditionalParts.EpicTotalCost } }; // here we check if the current car is new or already exist. if (a9.Grandes .Any(item => string.Concat(item.Brand, " ", item.CarName) == string.Concat(newCar.Brand, " ", newCar.CarName))) { Status = "Another car with same name is already exists!"; return; } // Adding new Car a9.Grandes.Add(newCar); // saving the addition. a9.SaveChanges(); // Committing the addition of the new car into the database. transaction.Commit(); // Saving the image into app image directory. await Task.Run(() => { var encoder = new PngBitmapEncoder(); encoder.Frames.Add(item: BitmapFrame.Create(source: CarImage)); var imagePath = FileHelpers.ImagePath(imageName: newCar.CarImage); using (var fileStream = new FileStream(path: imagePath, mode: FileMode.Create)) { encoder.Save(stream: fileStream); } }); // Notifying the state of operation. Status = $"{newCar.Brand} {newCar.CarName} has been added successfully."; } catch { // Rolling back adding the car in case an error occurred. transaction.Rollback(); Status = @"Error occurred while adding the car!"; } } } }
private void Button_Click_1(object sender, RoutedEventArgs e) { string identificador = new Seguridad().SHA1(DateTime.Now + ""); string foto = this.paciente.nombre + "_" + this.paciente.apellidos + "_" + identificador + ".jpg"; foto = foto.Replace(" ", "_"); if (MiWebCam != null && MiWebCam.IsRunning) { /*CerrarWebCam(); * string filePath = ruta +foto; * var encoder = new JpegBitmapEncoder(); * encoder.Frames.Add(BitmapFrame.Create((BitmapSource)img1.Source)); * using (FileStream stream = new FileStream(filePath, FileMode.Create)) * encoder.Save(stream);*/ System.Windows.Forms.MessageBox.Show("La camara sigue encendida no ha tomado la foto ", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } else { string filePath = filePath = ruta + foto; var encoder = new JpegBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create((BitmapSource)img1.Source)); using (FileStream stream = new FileStream(filePath, FileMode.Create)) encoder.Save(stream); } Servicios.Paciente paciente = new Servicios.Paciente(bandera_offline_online); bool inserto = paciente.insertarPaciente(this.paciente.nombre, this.paciente.apellidos, this.paciente.direccion, this.paciente.telefono, foto, this.paciente.antecedente, this.paciente.email, this.paciente.marketing, this.paciente.clinica.id_clinica, alias); if (inserto) { string destFile = System.IO.Path.Combine(ruta_offline, foto); string destFile2 = System.IO.Path.Combine(@configuracion.carpetas.ruta_imagenes_carpeta + "\\", foto); System.IO.File.Copy(ruta + foto, destFile, true); System.IO.File.Copy(ruta + foto, destFile2, true); if (File.Exists(ruta + foto)) { File.Delete(ruta + foto); } //System.Windows.Forms.MessageBox.Show("Se subio correctamente la foto", "Correcto", MessageBoxButtons.OK, MessageBoxIcon.Information); Soc socio = System.Windows.Application.Current.Windows.OfType <Soc>().FirstOrDefault(); Recep recep = System.Windows.Application.Current.Windows.OfType <Recep>().FirstOrDefault(); Admin admin = System.Windows.Application.Current.Windows.OfType <Admin>().FirstOrDefault(); if (admin != null) { admin.Main.NavigationUIVisibility = System.Windows.Navigation.NavigationUIVisibility.Visible; admin.Main.Content = new Page6(alias); } else if (recep != null) { recep.Main3.NavigationUIVisibility = System.Windows.Navigation.NavigationUIVisibility.Visible; recep.Main3.Content = new Pacientes_Recepcionista(this.paciente.clinica.id_clinica, alias); } else if (socio != null) { socio.Main4.NavigationUIVisibility = System.Windows.Navigation.NavigationUIVisibility.Visible; socio.Main4.Content = new Pacientes_socio(this.lista, this.alias); } //paciente = new Servicios.Paciente(!bandera_offline_online); //bool inserto_2 = paciente.insertarPaciente(this.paciente.nombre, this.paciente.apellidos, this.paciente.direccion, this.paciente.telefono, foto, this.paciente.antecedente, this.paciente.email, this.paciente.marketing, this.paciente.clinica.id_clinica); //if(inserto_2) //{ // System.Windows.Forms.MessageBox.Show("Tardaran unos minutos al subir la foto", "Espera", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); // bool subir = SubirFicheroStockFTP(foto, @configuracion.carpetas.ruta_imagenes_carpeta + "\\"); // if (subir) // { // System.Windows.Forms.MessageBox.Show("Se subio correctamente la foto", "Correcto", MessageBoxButtons.OK, MessageBoxIcon.Information); // Soc socio = System.Windows.Application.Current.Windows.OfType<Soc>().FirstOrDefault(); // Recep recep = System.Windows.Application.Current.Windows.OfType<Recep>().FirstOrDefault(); // Admin admin = System.Windows.Application.Current.Windows.OfType<Admin>().FirstOrDefault(); // if (admin != null) // { // admin.Main.NavigationUIVisibility = System.Windows.Navigation.NavigationUIVisibility.Visible; // admin.Main.Content = new Page6(); // } // else // if (recep != null) // { // recep.Main3.NavigationUIVisibility = System.Windows.Navigation.NavigationUIVisibility.Visible; // recep.Main3.Content = new Pacientes_Recepcionista(this.paciente.clinica.id_clinica); // } // else // if (socio != null) // { // socio.Main4.NavigationUIVisibility = System.Windows.Navigation.NavigationUIVisibility.Visible; // socio.Main4.Content = new Pacientes_socio(this.lista,this.alias); // } // } // else // { // System.Windows.Forms.MessageBox.Show("No se pudo subir la foto", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); // Soc socio = System.Windows.Application.Current.Windows.OfType<Soc>().FirstOrDefault(); // Recep recep = System.Windows.Application.Current.Windows.OfType<Recep>().FirstOrDefault(); // Admin admin = System.Windows.Application.Current.Windows.OfType<Admin>().FirstOrDefault(); // if (admin != null) // { // admin.Main.NavigationUIVisibility = System.Windows.Navigation.NavigationUIVisibility.Visible; // admin.Main.Content = new Page6(); // } // else // if (recep != null) // { // recep.Main3.NavigationUIVisibility = System.Windows.Navigation.NavigationUIVisibility.Visible; // recep.Main3.Content = new Pacientes_Recepcionista(this.paciente.clinica.id_clinica); // } // else // if (socio != null) // { // socio.Main4.NavigationUIVisibility = System.Windows.Navigation.NavigationUIVisibility.Visible; // socio.Main4.Content = new Pacientes_socio(this.lista, this.alias); // } // } //} //else //{ // Soc socio = System.Windows.Application.Current.Windows.OfType<Soc>().FirstOrDefault(); // Recep recep = System.Windows.Application.Current.Windows.OfType<Recep>().FirstOrDefault(); // Admin admin = System.Windows.Application.Current.Windows.OfType<Admin>().FirstOrDefault(); // if (admin != null) // { // admin.Main.NavigationUIVisibility = System.Windows.Navigation.NavigationUIVisibility.Visible; // admin.Main.Content = new Page6(); // } // else // if (recep != null) // { // recep.Main3.NavigationUIVisibility = System.Windows.Navigation.NavigationUIVisibility.Visible; // recep.Main3.Content = new Pacientes_Recepcionista(this.paciente.clinica.id_clinica); // } // else // if (socio != null) // { // socio.Main4.NavigationUIVisibility = System.Windows.Navigation.NavigationUIVisibility.Visible; // socio.Main4.Content = new Pacientes_socio(this.lista, this.alias); // } } else { // System.Windows.Forms.MessageBox.Show("No se pudo registrar el paciente ", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } //bool insertarPaciente = paciente.insertarPaciente(this.paciente.nombre, this.paciente.apellidos, this.paciente.direccion, this.paciente.telefono, foto, this.paciente.antecedente, this.paciente.email, this.paciente.marketing, this.paciente.clinica.id_clinica); //if (insertarPaciente) //{ // System.Windows.Forms.MessageBox.Show("Se registro correctamente el Paciente", "Correcto", MessageBoxButtons.OK, MessageBoxIcon.Information); // Test_Internet ti = new Test_Internet(); // if (ti.Test()) // { // System.Windows.Forms.MessageBox.Show("Tardaran unos minutos al subir la foto", "Espera", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); // bool subir = SubirFicheroStockFTP(foto, ruta); // if (subir) // { // //bool descargo = downloadFile("ftp://jjdeveloperswdm.com/", "*****@*****.**", "bonita_smile", foto, // // @"\\DESKTOP-ED8E774\bs\" + foto, 10); // string destFile = System.IO.Path.Combine(@"\\DESKTOP-ED8E774\bs\", foto); // //MessageBox.Show("el valor de result es " + result); // System.IO.File.Copy(ruta+foto, destFile, true); // //File.Delete(ruta + foto); // System.Windows.Forms.MessageBox.Show("Se subio correctamente la foto", "Correcto", MessageBoxButtons.OK, MessageBoxIcon.Information); // // } // else // { // System.Windows.Forms.MessageBox.Show("No se pudo subir la foto", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); // } // } // else // { // System.Windows.Forms.MessageBox.Show("No se pudo subir la foto por el internet ", "Error por falta de internet", MessageBoxButtons.OK, MessageBoxIcon.Error); // string destFile = System.IO.Path.Combine(ruta_offline, foto); // string destFile2 = System.IO.Path.Combine(@"\\DESKTOP-ED8E774\bs\", foto); // //MessageBox.Show("el valor de result es " + result); // System.IO.File.Copy(ruta + foto, destFile, true); // System.IO.File.Copy(ruta + foto, destFile2, true); // File.Delete(ruta + foto); // System.Windows.Forms.MessageBox.Show("Se subira la foto cuando tengas internet y des click en sincronizar ", "Se guardara la foto", MessageBoxButtons.OK, MessageBoxIcon.Information); // Recep recep = System.Windows.Application.Current.Windows.OfType<Recep>().FirstOrDefault(); // Admin admin = System.Windows.Application.Current.Windows.OfType<Admin>().FirstOrDefault(); // if (admin != null) // { // admin.Main.Content = new Page6(); // } // else // if (recep != null) // { // recep.Main3.Content = new Pacientes_Recepcionista(this.paciente.clinica.id_clinica); // } // } //} // }
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); } } } }
/// <summary> /// Creates a thumbnail from the given image. /// </summary> /// <param name="image">The source image.</param> /// <param name="size">Requested image size.</param> /// <param name="useEmbeddedThumbnails">Embedded thumbnail usage.</param> /// <param name="useExifOrientation">true to automatically rotate images based on Exif orientation; otherwise false.</param> /// <param name="useWIC">true to use Windows Imaging Component; otherwise false.</param> /// <returns>The thumbnail image from the given image or null if an error occurs.</returns> public static Image FromImage(Image image, Size size, UseEmbeddedThumbnails useEmbeddedThumbnails, bool useExifOrientation, bool useWIC) { if (size.Width <= 0 || size.Height <= 0) { throw new ArgumentException(); } if (useWIC) { #if USEWIC MemoryStream stream = null; BitmapFrame frameWpf = null; try { stream = new MemoryStream(); image.Save(stream, ImageFormat.Bmp); // Performance vs image quality settings. // Selecting BitmapCacheOption.None speeds up thumbnail generation of large images tremendously // if the file contains no embedded thumbnail. The image quality is only slightly worse. stream.Seek(0, SeekOrigin.Begin); frameWpf = BitmapFrame.Create(stream, BitmapCreateOptions.IgnoreColorProfile, BitmapCacheOption.None); } catch { if (stream != null) { stream.Dispose(); stream = null; } frameWpf = null; } if (stream == null || frameWpf == null) { if (stream != null) { stream.Dispose(); stream = null; } // .Net 2.0 fallback Image img = GetThumbnailBmp(image, size, useExifOrientation ? GetRotation(image) : 0); return(img); } Image thumb = GetThumbnail(frameWpf, size, useEmbeddedThumbnails, useExifOrientation ? GetRotation(frameWpf) : 0); stream.Dispose(); return(thumb); #else // .Net 2.0 fallback return(GetThumbnailBmp(image, size, useExifOrientation ? GetRotation(image) : 0)); #endif } else { // .Net 2.0 fallback return(GetThumbnailBmp(image, size, useExifOrientation ? GetRotation(image) : 0)); } }
public MainWindow() { InitializeComponent(); Icon = BitmapFrame.Create(Application.GetResourceStream(new Uri("icon.png", UriKind.RelativeOrAbsolute)).Stream); }
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; } }
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); }; } })); }
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 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 }
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 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); } }
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 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 <double>(() => Canvas.GetTop(RightImage)) * scaleDiffRight; var leftPoint = Dispatcher.Invoke <double>(() => 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 <double>(() => Canvas.GetTop(LeftImage)) * scaleDiffRight; var leftPoint = Dispatcher.Invoke <double>(() => 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); } }
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; }
static internal ImageSource GetImageSourceFromResource(string resourceName) { return(BitmapFrame.Create(typeof(QueryCompletionData).Assembly.GetManifestResourceStream(typeof(QueryCompletionData).Namespace + "." + resourceName))); }
/// <summary> /// Handle pasting and handle images /// </summary> public void PasteOperation() { if (Clipboard.ContainsImage()) { string imagePath = null; var bmpSource = Clipboard.GetImage(); using (var bitMap = WindowUtilities.BitmapSourceToBitmap(bmpSource)) { imagePath = AddinManager.Current.RaiseOnSaveImage(bitMap); } if (!string.IsNullOrEmpty(imagePath)) { SetSelection($"![]({imagePath})"); PreviewMarkdownCallback(); // force a preview refresh return; } string initialFolder = null; if (!string.IsNullOrEmpty(MarkdownDocument.Filename) && MarkdownDocument.Filename != "untitled") { initialFolder = Path.GetDirectoryName(MarkdownDocument.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" || ext == ".jpeg") { encoder = new JpegBitmapEncoder(); } else if (ext == ".gif") { encoder = new GifBitmapEncoder(); } encoder.Frames.Add(BitmapFrame.Create(bmpSource)); encoder.Save(fileStream); } } 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); } if (!relPath.StartsWith("..\\")) { imagePath = relPath; } } if (imagePath.Contains(":\\")) { imagePath = "file:///" + imagePath; } SetSelection($"![]({imagePath})"); PreviewMarkdownCallback(); // force a preview refresh } } else if (Clipboard.ContainsText()) { // just paste as is at cursor or selection SetSelection(Clipboard.GetText()); } }
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); } }
private void KickTalker_Tick(object sender, EventArgs e) { if (MessQueWrapper.count != 0) { lock (lockObj) { if (ReEntry) { ReEntry = false; Task.Run(() => { Dictionary <int, string> an = Config.AvatorNames; foreach (var item in MessQueWrapper.QueueRef().GetConsumingEnumerable()) { Dispatcher.Invoke(() => { IpcTask?.SetTaskId(item.TaskId); HttpTask?.SetTaskId(item.TaskId); HttpTask2?.SetTaskId(item.TaskId); TextBlockTweetCounter.Text = "0"; TextBlockReceveText.Text = item.Message; TextBlockAvatorText.Text = string.Format(@"{0} ⇒ {1} ⇒ {2}", ConstClass.ListenInterfaceMap[item.ListenInterface], ConstClass.BouyomiVoiceMap[item.BouyomiVoice], an[item.Cid]); }); WcfClient.Talk(item.Cid, item.Message, "", item.Effects, item.Emotions); LonelyCount = 0; } IpcTask?.SetTaskId(0); HttpTask?.SetTaskId(0); HttpTask2?.SetTaskId(0); ReEntry = true; }); } } } else { int cnt = LonelyCount; if (QuietMessageKeyMax != 0) { Task.Run(() => { Dispatcher.Invoke(() => { string s = (!UserData.IsSilentAvator && UserData.QuietMessages.ContainsKey(cnt)) ? "match" : ""; TextBlockTweetCounter.Text = string.Format(@"{0} ({1} Sec) {2}", TimeSpan.FromSeconds(cnt), cnt, s); TextBlockTweetMuteStatus.Text = UserData.IsSilentAvator ? "はい" : "いいえ"; }); }); if (!UserData.IsSilentAvator && UserData.QuietMessages.ContainsKey(cnt)) { int cid = LonelyCidList[r.Next(0, LonelyCidList.Count)]; int idx = r.Next(0, UserData.QuietMessages[cnt].Count); Task.Run(() => { Dispatcher.Invoke(() => { TextBlockReceveText.Text = UserData.QuietMessages[cnt][idx]; TextBlockAvatorText.Text = string.Format(@"⇒ {0}", LonelyAvatorNames[cid]); //Console.WriteLine(@"{0}-{1} : {2}", cnt, idx, UserData.QuietMessages[cnt][idx]); }); WcfClient.Talk(cid, UserData.QuietMessages[cnt][idx], "", null, null); }); } } // アイコン変化にもつかう switch (LonelyCount) { case 300: this.Icon = BitmapFrame.Create(new Uri("pack://Application:,,,/Resources/icon2b.ico", UriKind.RelativeOrAbsolute)); break; case 600: this.Icon = BitmapFrame.Create(new Uri("pack://Application:,,,/Resources/icon3.ico", UriKind.RelativeOrAbsolute)); break; } LonelyCount++; if ((QuietMessageKeyMax == 0) && (LonelyCount > 600)) { LonelyCount = 0; } else if (LonelyCount > QuietMessageKeyMax) { LonelyCount = 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)) { 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; } } }
/// <summary> /// Crops a given image. /// </summary> /// <param name="source">The BitmapSource.</param> /// <param name="rect">The crop rectangle.</param> /// <returns>The Cropped image.</returns> public static BitmapFrame CropImage(BitmapSource source, Int32Rect rect) { var croppedImage = new CroppedBitmap(source, rect); return(BitmapFrame.Create(croppedImage)); }
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(); }
/// <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); }
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(); }
private void Button_Click(object sender, RoutedEventArgs e) { System.Windows.Controls.Button boton = sender as System.Windows.Controls.Button; string[] coordenadas = BuscarNumeros(boton.Name); int columna = Int32.Parse(coordenadas[1]); int fila = Int32.Parse(coordenadas[2]); int respuesta = oper.revisaMina(columna, fila); if (respuesta == 9) { Uri resourceUri = new Uri("Resources/bomb1.png", UriKind.Relative); StreamResourceInfo streamInfo = System.Windows.Application.GetResourceStream(resourceUri); BitmapFrame temp = BitmapFrame.Create(streamInfo.Stream); var brush = new ImageBrush(); brush.ImageSource = temp; boton.Background = brush; System.Windows.MessageBox.Show("Perdiste :c", "Buscaminas", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Stop); } if (respuesta == 0) { Uri resourceUri = new Uri("Resources/7to_tOpy.jpg", UriKind.Relative); StreamResourceInfo streamInfo = System.Windows.Application.GetResourceStream(resourceUri); BitmapFrame temp = BitmapFrame.Create(streamInfo.Stream); var brush = new ImageBrush(); brush.ImageSource = temp; boton.Background = brush; if (contador < 74) { if (minasDesbloqueadas.Contains(boton.Name) == false) { minasDesbloqueadas.Add(boton.Name); contador++; } } else { System.Windows.MessageBox.Show("Buscaminas", "Ganaste! c:", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Information); } Console.WriteLine(contador); } if (respuesta != 0 && respuesta != 9) { Uri resourceUri = new Uri("Resources/" + respuesta + ".jpg", UriKind.Relative); StreamResourceInfo streamInfo = System.Windows.Application.GetResourceStream(resourceUri); BitmapFrame temp = BitmapFrame.Create(streamInfo.Stream); var brush = new ImageBrush(); brush.ImageSource = temp; boton.Background = brush; if (contador < 74) { if (minasDesbloqueadas.Contains(boton.Name) == false) { minasDesbloqueadas.Add(boton.Name); contador++; } } else { System.Windows.MessageBox.Show("Buscaminas", "Ganaste! c:", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Information); } Console.WriteLine(contador); } }
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 BitmapFrame FastResize(BitmapFrame bfPhoto, float nWidth, float nHeight) { TransformedBitmap tbBitmap = new TransformedBitmap(bfPhoto, new ScaleTransform(nWidth / bfPhoto.Width, nHeight / bfPhoto.Height, 0, 0)); return(BitmapFrame.Create(tbBitmap)); }
public Photo(string path) { _path = path; _source = new Uri(path); _image = BitmapFrame.Create(_source); }