public Model3DGroup Create(Color modelColor,string pictureName, Point3D startPos, double maxHigh) { try { Uri inpuri = new Uri(@pictureName, UriKind.Relative); BitmapImage bi = new BitmapImage(); bi.BeginInit(); bi.UriSource = inpuri; bi.EndInit(); ImageBrush imagebrush = new ImageBrush(bi); imagebrush.Opacity = 100; imagebrush.Freeze(); Point[] ptexture0 = { new Point(0, 0), new Point(0, 1), new Point(1, 0) }; Point[] ptexture1 = { new Point(1, 0), new Point(0, 1), new Point(1, 1) }; SolidColorBrush modelbrush = new SolidColorBrush(modelColor); Model3DGroup cube = new Model3DGroup(); Point3D uppercircle = startPos; modelbrush.Freeze(); uppercircle.Y = startPos.Y + maxHigh; cube.Children.Add(CreateEllipse2D(modelbrush, uppercircle, _EllipseHigh, new Vector3D(0, 1, 0))); cube.Children.Add(CreateEllipse2D(modelbrush, startPos, _EllipseHigh, new Vector3D(0, -1, 0))); cube.Children.Add(CreateEllipse3D(imagebrush, startPos, _EllipseHigh, maxHigh, ptexture0)); return cube; } catch (Exception ex) { throw ex; } }
private void updateImage(ThumbnailInfo info) { updateOnlineStatus(); System.Drawing.Image bmp = info.Thumbnail; using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) { bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);// 格式自处理,这里用 bitmap try { WindowUtil.BeginInvoke(() => { var bi = new System.Windows.Media.Imaging.BitmapImage(); bi.BeginInit(); bi.StreamSource = new MemoryStream(ms.ToArray()); // 不要直接使用 ms bi.EndInit(); Thumbnail = bi; }); } catch { Dispose(); } } }
/// <summary> /// Gets a bitmap inside the given assembly at the given path therein. /// </summary> /// <param name="uri"> /// The relative URI. /// </param> /// <param name="assemblyName"> /// Name of the assembly. /// </param> /// <returns> /// </returns> public static BitmapImage GetBitmap(Uri uri, string assemblyName) { if (uri == null) { return null; } var stream = GetStream(uri, assemblyName); if (stream == null) { return null; } using (stream) { var bmp = new BitmapImage(); bmp.BeginInit(); bmp.StreamSource = stream; bmp.EndInit(); return bmp; } }
private void ImportImageButtonClick(object sender, RoutedEventArgs e) { OpenFileDialog openFileDialog = new OpenFileDialog(); #if WPF openFileDialog.Filter = "Image Files (*.png, *.jpg, *.bmp)|*.png;*.jpg;*.bmp"; #else openFileDialog.Filter = "Image Files (*.png, *.jpg)|*.png;*.jpg"; #endif bool? dialogResult = openFileDialog.ShowDialog(); if (dialogResult.HasValue && dialogResult.Value == true) { Image image = new Image(); #if WPF image.Source = new BitmapImage(new Uri(openFileDialog.FileName, UriKind.Absolute)); #else using (var fileOpenRead = openFileDialog.File.OpenRead()) { BitmapImage bitmap = new BitmapImage(); bitmap.SetSource(fileOpenRead); image.Source = bitmap; } #endif Viewbox viewBox = new Viewbox() { Stretch = Stretch.Fill, Margin = new Thickness(-4) }; viewBox.Child = image; RadDiagramShape imageShape = new RadDiagramShape() { Content = viewBox }; this.diagram.Items.Add(imageShape); } }
private void client_getApplicationByIdCompleted(object sender, MyService.getApplicationByIdCompletedEventArgs e) { string jsonString = e.Result.ToString(); JObject jobj = JObject.Parse(jsonString); jobj = jobj["Application"] as JObject; string Id = jobj["Id"].ToString(); string Name = jobj["Name"].ToString(); float Price = float.Parse(jobj["Price"].ToString()); float Rating = float.Parse(jobj["Rating"].ToString()); int Reviews = Int32.Parse(jobj["Reviews"].ToString()); DateTime DatePublished = DateTime.Parse(jobj["DatePublished"].ToString()); string PublisherName = jobj["PublisherName"].ToString(); string ImageUrl = jobj["ImageUrl"].ToString(); pivFirstItem.Text = Name; BitmapImage myBitmapImage = new BitmapImage(); myBitmapImage.UriSource = new Uri(ImageUrl); myBitmapImage.DecodePixelWidth = 300; myBitmapImage.DecodePixelWidth = 300; myBitmapImage.DecodePixelType = DecodePixelType.Logical; img.Source = myBitmapImage; txtDatePublished.Text = "Date published: "+DatePublished.ToShortDateString(); txtPublisher.Text = "Publisher: "+PublisherName; txtRating.Text = "Rating: "+Rating.ToString(); txtReviews.Text = "Number of reviews: "+Reviews.ToString(); if (Price > 0) txtPrice.Text = "Price: $ " + Price.ToString(); else txtPrice.Text = "This application is free"; }
public Image GetErrorImageType(int ErrorCode, bool isWarning) { Image image = new Image() { Width = 25, Height = 25 }; var pic = new System.Windows.Media.Imaging.BitmapImage(); pic.BeginInit(); //Image for type of error if (ErrorCode == 0 && isWarning) { pic.UriSource = new Uri("Images/Warning.png", UriKind.Relative); // url is from the xml } else if (ErrorCode != 0) { pic.UriSource = new Uri("Images/Error.png", UriKind.Relative); // url is from the xml } else { pic.UriSource = new Uri("Images/CheckMark.png", UriKind.Relative); // url is from the xml } pic.EndInit(); image.Source = pic; return(image); }
private void updateImage() { try { SnapshotImg.Source = null; ImageExportOptions options = new ImageExportOptions(); options.FilePath = snapshot; // options. options.HLRandWFViewsFileType = ImageFileType.PNG; options.ShadowViewsFileType = ImageFileType.PNG; options.ExportRange = ExportRange.VisibleRegionOfCurrentView; options.ZoomType = ZoomFitType.FitToPage; options.ImageResolution = ImageResolution.DPI_72; options.PixelSize = 1000; doc.ExportImage(options); BitmapImage source = new BitmapImage(); source.BeginInit(); source.UriSource = new Uri(snapshot); source.CacheOption = BitmapCacheOption.OnLoad; source.CreateOptions = BitmapCreateOptions.IgnoreImageCache; source.EndInit(); SnapshotImg.Source = source; PathLabel.Content = "none"; } catch (System.Exception ex1) { TaskDialog.Show("Error!", "exception: " + ex1); } }
private void initImageCache() { // load all images in the "iamges" folder _imageSources = new Dictionary<string, ImageSource>(); if (!string.IsNullOrEmpty(_imageFolder ) && Directory.Exists(_imageFolder)) { foreach (var f in Directory.GetFiles(_imageFolder, "*.png", SearchOption.TopDirectoryOnly)) { if (f != null) { var filePath = Path.Combine(_imageFolder, f); var bmp = new BitmapImage(new Uri(filePath)); var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(f); _imageSources.Add(fileNameWithoutExtension, bmp); } } } _imageSources.Add(".UIController", new BitmapImage(new Uri(@"/Resources/UIController.png", UriKind.Relative))); _imageSources.Add(".FlowUIController", new BitmapImage(new Uri(@"/Resources/UIController.png", UriKind.Relative))); _imageSources.Add(".AbstractUIController", new BitmapImage(new Uri(@"/Resources/UIController.png", UriKind.Relative))); }
private Button FormButton(ProjectData data) { Button button = new Button(); WrapPanel wrapPanel = new WrapPanel(); Image image = new Image(); TextBlock text = new TextBlock(); text.Text = System.IO.Path.GetFileName(data.FileName); System.Windows.Media.Imaging.BitmapImage bi3 = new System.Windows.Media.Imaging.BitmapImage(); bi3.BeginInit(); bi3.UriSource = new Uri("Resources/SmallIcon.ico", UriKind.Relative); bi3.EndInit(); image.Stretch = System.Windows.Media.Stretch.Fill; image.Source = bi3; image.Width = 16; image.Height = 16; image.Margin = new System.Windows.Thickness(0, 0, 5, 0); wrapPanel.Orientation = Orientation.Horizontal; wrapPanel.Children.Add(image); wrapPanel.Children.Add(text); wrapPanel.HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch; wrapPanel.VerticalAlignment = System.Windows.VerticalAlignment.Stretch; button.HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch; button.VerticalAlignment = System.Windows.VerticalAlignment.Stretch; button.VerticalContentAlignment = System.Windows.VerticalAlignment.Stretch; button.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Stretch; button.Tag = data; button.Content = wrapPanel; button.Click += new System.Windows.RoutedEventHandler(button_Click); return(button); }
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { var rawImageData = value as byte[]; if (rawImageData == null) { return(null); } var bitmapImage = new System.Windows.Media.Imaging.BitmapImage(); using (MemoryStream strm = new MemoryStream()) { strm.Write(rawImageData, 0, rawImageData.Length); strm.Position = 0; System.Drawing.Image img = System.Drawing.Image.FromStream(strm); bitmapImage.BeginInit(); MemoryStream ms = new MemoryStream(); img.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp); ms.Seek(0, SeekOrigin.Begin); bitmapImage.StreamSource = ms; bitmapImage.EndInit(); } return(bitmapImage); }
System.Windows.Media.Imaging.BitmapImage RetrieveImage(string value) { System.Windows.Media.Imaging.BitmapImage btm = ImageCache.Retrieve(value); if (btm != null) { return(btm); } System.Windows.Controls.Image img3; img3 = new System.Windows.Controls.Image(); IUsdConfiguraitonManager _cfgMgr = AifServiceContainer.Instance.GetService <IUsdConfiguraitonManager>(); if (_cfgMgr != null && _cfgMgr.IsUsdConfigDataReady) { ImageResources _crmWebResource = new ImageResources(_cfgMgr.CrmManagementSvc); System.Windows.Media.Imaging.BitmapImage bm; bm = _crmWebResource.GetImageFromCRMWebResource((string)value); if (bm != null) { ImageCache.Store((string)value, bm); return(bm.Clone()); } else { return(null); } } else { return(null); } }
public void loadImage(int id) { try { string select = "select * from Images where ImageId='" + id + "'"; DataTable dt = SiaWin.Func.SqlDT(select, "Imagen", 0); if (dt.Rows.Count > 0) { byte[] blob = (byte[])dt.Rows[0]["Image"]; MemoryStream stream = new MemoryStream(); stream.Write(blob, 0, blob.Length); stream.Position = 0; System.Drawing.Image img = System.Drawing.Image.FromStream(stream); System.Windows.Media.Imaging.BitmapImage bi = new System.Windows.Media.Imaging.BitmapImage(); bi.BeginInit(); MemoryStream ms = new MemoryStream(); img.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp); ms.Seek(0, SeekOrigin.Begin); bi.StreamSource = ms; bi.EndInit(); this.Icon = bi; } } catch (Exception w) { SiaWin.Func.SiaExeptionGobal(w); MessageBox.Show("error en el loadImage:" + w); } }
public static Media.Brush GetThumbnailBrush(string fileName, int width = 256, int height = 256, ThumbnailOptions options = ThumbnailOptions.None) { IntPtr hBitmap = GetHBitmap(Path.GetFullPath(fileName), width, height, options); try { Bitmap bmp = Bitmap.FromHbitmap(hBitmap); Media.Imaging.BitmapImage img = new Media.Imaging.BitmapImage(); using (var ms = new MemoryStream()) { bmp.Save(ms, ImageFormat.Png); img.BeginInit(); img.StreamSource = ms; img.CacheOption = Media.Imaging.BitmapCacheOption.OnLoad; img.EndInit(); img.Freeze(); } return(new Media.ImageBrush(img)); } finally { // delete HBitmap to avoid memory leaks DeleteObject(hBitmap); } }
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { // empty images are empty... if (value == null) { return(null); } var image = (System.Drawing.Image)value; // Winforms Image we want to get the WPF Image from... var bitmap = new System.Windows.Media.Imaging.BitmapImage(); bitmap.BeginInit(); bitmap.CacheOption = BitmapCacheOption.OnLoad; using (MemoryStream memoryStream = new MemoryStream()) { // Save to a memory stream... image.Save(memoryStream, ImageFormat.Bmp); // Rewind the stream... memoryStream.Seek(0, System.IO.SeekOrigin.Begin); bitmap.StreamSource = memoryStream; bitmap.EndInit(); } return(bitmap); }
/// <summary> /// 将图片文件转换成BitmapSource /// </summary> /// <param name="sFilePath"></param> /// <returns></returns> public static System.Windows.Media.Imaging.BitmapSource ToBitmapSource(string sFilePath) { try { using (System.IO.FileStream fs = new System.IO.FileStream(sFilePath, System.IO.FileMode.Open, System.IO.FileAccess.Read)) { byte[] buffer = new byte[fs.Length]; fs.Read(buffer, 0, buffer.Length); fs.Close(); fs.Dispose(); System.Windows.Media.Imaging.BitmapImage bitmapImage = new System.Windows.Media.Imaging.BitmapImage(); using (System.IO.MemoryStream ms = new System.IO.MemoryStream(buffer)) { bitmapImage.BeginInit(); bitmapImage.StreamSource = ms; bitmapImage.CacheOption = System.Windows.Media.Imaging.BitmapCacheOption.OnLoad; bitmapImage.EndInit(); bitmapImage.Freeze(); } return(bitmapImage); } } catch (Exception ex) { return(null); } }
static TopWallpaperRenderer() { ScreenArea = new Rect(0, 0, 412, 240); var defTopAlt = new BitmapImage(); defTopAlt.BeginInit(); //defTopAlt.StreamSource = (Stream) Extensions.GetResources(@"TopAlt_DefMask\.png").First().Value; defTopAlt.UriSource = new Uri(@"pack://application:,,,/ThemeEditor.WPF;component/Resources/TopAlt_DefMask.png"); defTopAlt.CacheOption = BitmapCacheOption.OnLoad; defTopAlt.EndInit(); var bgrData = defTopAlt.GetBgr24Data(); RawTexture rTex = new RawTexture(defTopAlt.PixelWidth, defTopAlt.PixelHeight, RawTexture.DataFormat.A8); rTex.Encode(bgrData); DefaultTopSquares = new TextureViewModel(rTex, null); RenderToolFactory.RegisterTool<PenTool, Pen> (key => new Pen(new SolidColorBrush(key.Color) { Opacity = key.Opacity }, key.Width)); RenderToolFactory.RegisterTool<SolidColorBrushTool, Brush> (key => new SolidColorBrush(key.Color) { Opacity = key.Opacity }); RenderToolFactory.RegisterTool<LinearGradientBrushTool, Brush> (key => new LinearGradientBrush(key.ColorA, key.ColorB, key.Angle) { Opacity = key.Opacity }); RenderToolFactory.RegisterTool<ImageBrushTool, Brush> (key => new ImageBrush(key.Image) { TileMode = key.Mode, ViewportUnits = key.ViewportUnits, Viewport = key.Viewport, Opacity = key.Opacity }); Type ownerType = typeof(TopWallpaperRenderer); IsEnabledProperty .OverrideMetadata(ownerType, new FrameworkPropertyMetadata(false, OnIsEnabledChanged)); ClipToBoundsProperty.OverrideMetadata(ownerType, new FrameworkPropertyMetadata(true, null, (o, value) => true)); WidthProperty.OverrideMetadata(ownerType, new FrameworkPropertyMetadata(412.0, null, (o, value) => 412.0)); HeightProperty.OverrideMetadata(ownerType, new FrameworkPropertyMetadata(240.0, null, (o, value) => 240.0)); EffectProperty.OverrideMetadata(ownerType, new FrameworkPropertyMetadata(default(WarpEffect), null, (o, value) => ((TopWallpaperRenderer) o).GetWarpEffectInstance())); }
public static BitmapImage GetCharacterPortrait(Player player) { if (player == null || player.CharacterID == 0) return null; int Size = 64; string filePath = string.Format("{0}\\{1}.jpg", Utils.PortraitDir, player.CharacterID); BitmapImage image = null; try { if (!File.Exists(filePath)) { WebClient wc = new WebClient(); wc.DownloadFile( string.Format("http://img.eve.is/serv.asp?s={0}&c={1}", Size, player.CharacterID), filePath); } image = new BitmapImage(); image.BeginInit(); image.UriSource = new Uri(filePath, UriKind.Absolute); image.EndInit(); } catch (Exception) { } return image; }
public override void Render(DrawingContext dc, GeometryStyleBase geometryStyle) { if (null == dc || !(geometryStyle is ImageStyle)) { return; } ImageStyle style = geometryStyle as ImageStyle; if (!_moving) { _beforeMoveFirstPoint = geometryStyle.FirstPoint; _beforeMoveSecondPoint = geometryStyle.SecondPoint; } if (style.ImageUri == null) { dc.DrawRectangle(Brushes.Transparent, _pen, new Rect(geometryStyle.FirstPoint, geometryStyle.SecondPoint)); } else { BitmapSource source = new System.Windows.Media.Imaging.BitmapImage(style.ImageUri); dc.DrawImage(source, new Rect(geometryStyle.FirstPoint, geometryStyle.SecondPoint)); } }
public SplashScreen() { LoadConfigPrefs(); Image SplashScreen = new Image() { Height = Application.Current.Host.Content.ActualHeight, Width = Application.Current.Host.Content.ActualWidth, Stretch = Stretch.Fill }; var imageResource = GetSplashScreenImageResource(); if (imageResource != null) { BitmapImage splash_image = new BitmapImage(); splash_image.SetSource(imageResource.Stream); SplashScreen.Source = splash_image; } // Instansiate the popup and set the Child property of Popup to SplashScreen popup = new Popup() { IsOpen = false, Child = SplashScreen, HorizontalAlignment = HorizontalAlignment.Stretch, VerticalAlignment = VerticalAlignment.Center }; }
public static System.Windows.Media.Imaging.BitmapImage ToImage(byte[] bytes) { //if (testCount++ > 10) { testCount = 0; throw new Exception("TestException"); } try { using (Stream ms = new System.IO.MemoryStream(bytes)) { System.Windows.Media.Imaging.BitmapImage image = null; try { System.Windows.Application.Current.Dispatcher.Invoke((Action)(() => { try { image = new System.Windows.Media.Imaging.BitmapImage(); image.BeginInit(); image.CacheOption = System.Windows.Media.Imaging.BitmapCacheOption.OnLoad; image.StreamSource = ms; image.EndInit(); image.Freeze(); } catch (Exception) { } })); } catch (NullReferenceException) { } return(image); } } catch (Exception e) { } return(null); }
public StatisticsWindow() { InitializeComponent(); Uri uri = new Uri("pack://siteoforigin:,,,/Resources/Без имени-2.png"); BitmapImage bitmap = new BitmapImage(uri); img.Source = bitmap; }
/// <summary> /// Converts between a System.Drawing.Image and System.Windows.Media.Imaging.BitmapImage /// </summary> internal static SWMI.BitmapImage ToSystemWindowsMediaImagingBitmapImage(SD.Image fromImage) { if (fromImage == null) { return(null); } SWMI.BitmapImage newImage = null; System.IO.MemoryStream stream = new System.IO.MemoryStream(); //Use the same output format that the Image is in, unless it is a MemoryBmp, //in which case use a regular Bmp. SDI.ImageFormat IntermediateFormat = fromImage.RawFormat; if (IntermediateFormat.Guid.CompareTo(SDI.ImageFormat.MemoryBmp.Guid) == 0) { IntermediateFormat = SDI.ImageFormat.Bmp; } fromImage.Save(stream, IntermediateFormat); stream.Seek(0, System.IO.SeekOrigin.Begin); newImage = new SWMI.BitmapImage(); newImage.BeginInit(); newImage.StreamSource = stream; newImage.EndInit(); return(newImage); }
public ExtTreeNode(Image icon, string title) : this() { if (icon != null) { this.icon = icon; } else//test inti icon { this.icon = new Image(); BitmapImage bitmapImage = new BitmapImage(); bitmapImage.BeginInit(); bitmapImage.UriSource = new Uri(@"pack://*****:*****@"../../icons/add.png", UriKind.RelativeOrAbsolute); bitmapImage.EndInit(); this.icon.Source = bitmapImage; } this.icon.Width = 16; this.icon.Height = 16; this.title = title; TextBlock tb = new TextBlock(); tb.Text = title; Grid grid = new Grid(); grid.ColumnDefinitions.Add(new ColumnDefinition()); grid.ColumnDefinitions.Add(new ColumnDefinition()); grid.Children.Add(this.icon); grid.Children.Add(tb); Grid.SetColumn(this.icon, 0); Grid.SetColumn(tb, 1); this.Header = grid; }
public BitmapImage ByteToBitmapImage(byte[] image) { byte[] myByte = image; if (image == null) { return(null); } BitmapImage newImage; using (MemoryStream ms = new MemoryStream(myByte)) { var bmp = Bitmap.FromStream(ms); ms.Seek(0, System.IO.SeekOrigin.Begin); var bitmap = new System.Windows.Media.Imaging.BitmapImage(); bitmap.BeginInit(); bitmap.CacheOption = BitmapCacheOption.OnLoad; bitmap.StreamSource = ms; bitmap.EndInit(); newImage = bitmap; } return(newImage); }
//TODO filter by mimetype public void ShowImage(MemoryStream stream) { try { stream.Position = 0; var bitmapImage = new BitmapImage(); bitmapImage.BeginInit(); bitmapImage.StreamSource = stream; bitmapImage.EndInit(); image1.Width = bitmapImage.Width; image1.Height = bitmapImage.Height; var screenInfo = GetScreenInfo(); image1.Height = screenInfo.Height - 150; image1.Width = (image1.Height * bitmapImage.Width) / bitmapImage.Height; Height = image1.Height + 3; Width = image1.Width + 3; image1.Source = bitmapImage; } catch (NotSupportedException) { } }
private void UserDrawWPF(DrawingContext dc) { int PixelX = 0; int PixelY = 0; if (ActivityRoute != null) { Utilites.UserDrawRoutesWPF(ActivityRoute, dc, System.Windows.Media.Colors.Blue); VMMainViewModel.Instance.ConvertCoordGroundToPixel(ActivityRoute.Points[ActivityRoute.Points.Count - 1].X, ActivityRoute.Points[ActivityRoute.Points.Count - 1].Y, ref PixelX, ref PixelY); ImageSource ImageSource = new System.Windows.Media.Imaging.BitmapImage(new Uri("pack://application:,,,/Images/" + "flag_red.png")); Utilites.UserDrawRasterWPFScreenCoordinate(dc, ImageSource, PixelX, PixelY, 22, 22); } if (referencePoint.X != 0.0 && referencePoint.Y != 0.0) { VMMainViewModel.Instance.ConvertCoordGroundToPixel(referencePoint.X, referencePoint.Y, ref PixelX, ref PixelY); ImageSource ImageSource = new System.Windows.Media.Imaging.BitmapImage(new Uri("pack://application:,,,/Images/" + "flag_blue.png")); Utilites.UserDrawRasterWPFScreenCoordinate(dc, ImageSource, PixelX, PixelY, 22, 22); } //if (ReferenceRoute != null) //{ // Utilites.UserDrawRoutesWPF(ReferenceRoute, dc, System.Windows.Media.Colors.Red); //} }
public async Task<ImageSource> DownloadPicture(string imageUri) { var request = (HttpWebRequest)WebRequest.Create(imageUri); if (string.IsNullOrEmpty(Configuration.SessionCookies) == false) { request.CookieContainer = new CookieContainer(); request.CookieContainer.SetCookies(request.RequestUri, Configuration.SessionCookies); } var response = (HttpWebResponse)(await request.GetResponseAsync()); using (Stream inputStream = response.GetResponseStream()) using (Stream outputStream = new MemoryStream()) { var buffer = new byte[4096]; int bytesRead; do { bytesRead = await inputStream.ReadAsync(buffer, 0, buffer.Length); outputStream.Write(buffer, 0, bytesRead); } while (bytesRead != 0); var bitmapImage = new BitmapImage(); bitmapImage.BeginInit(); bitmapImage.CacheOption = BitmapCacheOption.OnLoad; bitmapImage.StreamSource = outputStream; bitmapImage.EndInit(); bitmapImage.Freeze(); return bitmapImage; } }
public void BeginSaveJpeg() { BitmapImage backgroundImage = new System.Windows.Media.Imaging.BitmapImage(); IAsyncResult result = Microsoft.Xna.Framework.GamerServices.Guide.BeginShowMessageBox("Question", "Do you wish choose a picture from the album?", new string[] { "yes", "no" }, 0, Microsoft.Xna.Framework.GamerServices.MessageBoxIcon.Alert, null, null); result.AsyncWaitHandle.WaitOne(); int?choice = Microsoft.Xna.Framework.GamerServices.Guide.EndShowMessageBox(result); if (choice.HasValue) { if (choice.Value == 0) { PhotoChooserTask photoChooserTask = new PhotoChooserTask(); photoChooserTask.Completed += (s, e) => { if (e.TaskResult == TaskResult.OK) { backgroundImage.SetSource(e.ChosenPhoto); BackgroundImage.Source = backgroundImage; ReplaceImage(); } }; photoChooserTask.Show(); } else { SaveDefault(backgroundImage); } } return; }
void IThumbnailManager.SetThumbnail(string name, BitmapImage thumbnail) { using (var zipArchive = new ZipArchive("AssetThumbnails.zip")) { zipArchive.Save(name, thumbnail.StreamSource); } }
void camera_Completed(object sender, PhotoResult e) { if (e.TaskResult == TaskResult.OK) { //Code to display the photo on the page in an image control named myImage. System.Windows.Media.Imaging.BitmapImage bmp = new System.Windows.Media.Imaging.BitmapImage(); bmp.SetSource(e.ChosenPhoto); using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication()) { if (!isoStore.DirectoryExists(item.Group.Title)) { isoStore.CreateDirectory(item.Group.Title); } string fileName = string.Format("{0}/{1}.jpg", item.Group.Title, DateTime.Now.ToString("dd-MM-yyyy HH-mm-ss")); using (IsolatedStorageFileStream targetStream = isoStore.CreateFile(fileName)) { WriteableBitmap wb = new WriteableBitmap(bmp); wb.SaveJpeg(targetStream, wb.PixelWidth, wb.PixelHeight, 0, 100); targetStream.Close(); } if (null == item.UserImages) { item.UserImages = new System.Collections.ObjectModel.ObservableCollection <string>(); } item.UserImages.Add(fileName); } } }
private void busquedaBtn_Click(object sender, RoutedEventArgs e) { Client cliente = ControllerCliente.Instance.buscarCliente(busquedaBox.Text); if (cliente == null) { MessageBox.Show("No existe con ese carnet"); } else { ciBox.Text = cliente.ci.ToString(); nombreBox.Text = cliente.nombre; PaternoBox.Text = cliente.apellidoPaterno; MaternoBox.Text = cliente.apellidoMaterno; DomicilioBox.Text = cliente.domicilio; ZonaBox.Text = cliente.zona; emailBox.Text = cliente.email; telefonoCasaBox.Text = cliente.telefonoCasa; telefonoOficinaBox.Text = cliente.telefonoOficina; feCNacimientoBox.Text = cliente.fechaNacimiento.ToString(); sexoBox.Text = cliente.sexo; BiometricoBox.Text = cliente.codBiometrico; System.IO.MemoryStream stream = new System.IO.MemoryStream(cliente.foto); BitmapImage foto = new BitmapImage(); foto.BeginInit(); foto.StreamSource = stream; foto.CacheOption = BitmapCacheOption.OnLoad; foto.EndInit(); image.Source = foto; } }
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { var rawImageData = value as byte[]; if (rawImageData == null) { #if DEBUG return(null); #else Uri uri = new Uri("pack://application:,,,/Images/noimage.jpg"); return(new BitmapImage(uri)); #endif } var bitmapImage = new System.Windows.Media.Imaging.BitmapImage(); using (var stream = new MemoryStream(rawImageData)) { bitmapImage.BeginInit(); bitmapImage.CreateOptions = BitmapCreateOptions.PreservePixelFormat; bitmapImage.CacheOption = BitmapCacheOption.OnLoad; bitmapImage.StreamSource = stream; bitmapImage.EndInit(); } return(bitmapImage); }
public static BitmapImage ByteArraytoBitmap(Byte[] byteArray) { MemoryStream stream = new MemoryStream(byteArray); BitmapImage bitmapImage = new BitmapImage(); bitmapImage.SetSource(stream); return bitmapImage; }
public BitmapImage LoadAnimationTexture(string fileName, bool transparent = false) { if (transparent) { FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read); System.Drawing.Bitmap img = new System.Drawing.Bitmap(fileStream); fileStream.Close(); var color = img.Palette.Entries[0]; string hex = HexConverter(color); Instance.ViewModel.SpriteSheetTransparentColors.Add((Color)ColorConverter.ConvertFromString(hex)); img.MakeTransparent(color); return (BitmapImage)BitmapConversion.ToWpfBitmap(img); } else { FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read); var img = new System.Windows.Media.Imaging.BitmapImage(); img.BeginInit(); img.StreamSource = fileStream; img.EndInit(); return img; } }
/// <summary> /// 初始化 /// </summary> public void init(string[] func_list) { for (int i = 0; i < func_list.Length; i++) { // 分割线 Image img = new Image(); BitmapImage bi = new BitmapImage(); bi.BeginInit(); bi.UriSource = new Uri(AppConfig.IconPath, UriKind.Relative); bi.EndInit(); img.Margin = new Thickness(5, (i + 1) * 72 - 20, 0, 0); img.Width = 150; img.Height = 10; img.HorizontalAlignment = HorizontalAlignment.Left; img.VerticalAlignment = VerticalAlignment.Top; img.Source = bi; // 按钮 MainNavButton mnb = new MainNavButton(); mnb.Tag = func_list[i]; mnb.id = i; mnb.init(); mnb.HorizontalAlignment = HorizontalAlignment.Left; mnb.VerticalAlignment = VerticalAlignment.Top; mnb.Margin = new Thickness(0, (i + 1) * 72 - 20 + 3, 0, 0); if (i == 0) { mnb.change_state(); } mnbs.Add(mnb); this.main.Children.Add(img); this.main.Children.Add(mnb); } }
public override WriteableBitmap ApplyFunctionFilter(System.Windows.Media.Imaging.BitmapImage originalBitmapImage) { WriteableBitmap writableImage = new WriteableBitmap(originalBitmapImage); byte[] byteArr = writableImage.WriteableBitMapImageToArray(); double pixel; Offset = (100 + Offset) / 100.0; for (int i = 0; i < byteArr.Length; i++) { pixel = ((double)byteArr[i]) / 255.0; pixel -= 0.5; pixel *= Offset; pixel += 0.5; pixel *= 255; pixel = (pixel < 0 ? 0 : pixel); pixel = (pixel > 255 ? 255 : pixel); byteArr[i] = (byte)pixel; } WriteableBitmap result = originalBitmapImage.ByteArrayToWritableBitmap(byteArr); return(result); }
public MainWindow() { InitializeComponent(); // initialize tabItem array _tabItems = new List<TabItem>(); // add a tabItem with + in header _tabAdd = new TabItem(); //get image for header and setup add button _tabAdd.Style = new Style(); _tabAdd.Background = new SolidColorBrush(Color.FromArgb(0xFF, 0x30, 0x30, 0x30)); _tabAdd.BorderBrush = new SolidColorBrush(Color.FromArgb(0xFF, 0x30, 0x30, 0x30)); BitmapImage bitmap = new BitmapImage(); bitmap.BeginInit(); bitmap.UriSource = new Uri(@"pack://application:,,,/Explore10;component/Images/appbar.add.png"); bitmap.EndInit(); Image plus = new Image(); plus.Source = bitmap; plus.Width = 25; plus.Height = 25; _tabAdd.Width = 35; _tabAdd.Header = plus; _tabAdd.MouseLeftButtonUp += new MouseButtonEventHandler(tabAdd_MouseLeftButtonUp); _tabItems.Add(_tabAdd); // add first tab //this.AddTabItem(); // bind tab control tabDynamic.DataContext = _tabItems; tabDynamic.SelectedIndex = 0; }
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { if (value is string) { string url = value as string; if (!String.IsNullOrEmpty(url)) { if (url.StartsWith("/")) { return("/CO_IA.UI.Screen;component/Images/defaultprogram.png"); } System.Windows.Media.Imaging.BitmapImage bitmapImage = new System.Windows.Media.Imaging.BitmapImage(new Uri(value as string)); return(bitmapImage); } else { return("/CO_IA.UI.Screen;component/Images/defaultprogram.png"); } } if (value == null) { return("/CO_IA.UI.Screen;component/Images/defaultprogram.png"); } return(null); }
private void SearchButton_Click(object sender, RoutedEventArgs e) { var result = WeatherService.GetWeatherFor(SearchBox.Text); string fileUrl = $"{Environment.CurrentDirectory}/{result.icon}.gif"; if (!File.Exists(fileUrl)) { using (var webClient = new WebClient()) { byte[] bytes = webClient.DownloadData(result.icon_url); File.WriteAllBytes(fileUrl, bytes); } } BitmapImage image = new BitmapImage(new Uri(fileUrl)); WeatherImage.Source = image; // CityBlock.Text = result.full.ToString(); LatiLongBlock.Text = result.latitude.ToString() + "/" + result.longitude.ToString(); WeatherBlock.Text = result.weather.ToString(); TempFBlock.Text = result.temp_f.ToString(); TempCBlock.Text = result.temp_c.ToString(); HumidityBlock.Text = result.relative_humidity.ToString(); WindmphBlock.Text = result.wind_mph.ToString(); WindDirectionBlock.Text = result.wind_dir.ToString(); UVIndexBox.Text = result.UV.ToString(); }
private void Le_Imagem() { // ==================================================================== // Ler Imadem A Partir do Caminho Gravado no "Textnome.Text"... // ==================================================================== try { FileStream fs = File.Open(Textnome.Text, FileMode.Open); System.Drawing.Bitmap dImg = new System.Drawing.Bitmap(fs); MemoryStream ms = new MemoryStream(); dImg.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); System.Windows.Media.Imaging.BitmapImage bImg = new System.Windows.Media.Imaging.BitmapImage(); bImg.BeginInit(); bImg.StreamSource = new MemoryStream(ms.ToArray()); bImg.EndInit(); fs.Close(); fs.Dispose(); // Dispensa da Memória para mostrar outra imagem, para não dar Erro. PicFoto.Source = bImg; } catch (Exception) { MessageBox.Show("Se a nova Imagem do novo regidtro não Carregou, clique em outra qualquer e de pois volte a clicar nela, faça isso a té que a mesma aparecça normalmente. Isso não é um 'Bug', trata-se de um procedimento interno de sua Máquina para Alocar o novo registro de Imagem em Memóeria, uma vez carregada, não haverá mais Problema algum...", "INFORMAÇÃO IMPORTANTE !!!", MessageBoxButton.OK, MessageBoxImage.Information); } }
protected override void OnNavigatedTo(NavigationEventArgs e) { base.OnNavigatedTo(e); if (e.NavigationMode == NavigationMode.New) { XElement article = XElement.Load("Resources/about_program.xml"); XElement Credits = article.Element("Credits"); CreditsAbout.Text = Credits.Element("text").Value; CreditsCopyright.Text = "\u00A9" + CreditsCopyright.Text; CreditsText.Content = "\"" + CreditsText.Content + "\""; Version.Text = AppResources.Version + ": " + article.Element("version").Value; XElement developer = article.Element("developer"); Stream stream = Application.GetResourceStream(new Uri(developer.Element("logo").Attribute("src").Value, UriKind.Relative)).Stream; BitmapImage bmp = new BitmapImage(); bmp.SetSource(stream); stream.Close(); DeveloperLogo.Source = bmp; DeveloperLogo.Stretch = Stretch.Uniform; } }
//public static BitmapImage MemberImage(BitmapImage Member) //{ // get // { // var image = new BitmapImage(); // if (Member != null) // { // WebRequest request = WebRequest.Create(new Uri(Member. .ImageFilePath, UriKind.Absolute)); // request.Timeout = -1; // WebResponse response = request.GetResponse(); // Stream responseStream = response.GetResponseStream(); // BinaryReader reader = new BinaryReader(responseStream); // MemoryStream memoryStream = new MemoryStream(); // byte[] bytebuffer = new byte[BytesToRead]; // int bytesRead = reader.Read(bytebuffer, 0, BytesToRead); // while (bytesRead > 0) // { // memoryStream.Write(bytebuffer, 0, bytesRead); // bytesRead = reader.Read(bytebuffer, 0, BytesToRead); // } // image.BeginInit(); // memoryStream.Seek(0, SeekOrigin.Begin); // image.StreamSource = memoryStream; // image.EndInit(); // } // return image; // } //} #endregion public static BitmapImage Image_http_Loaded(Uri _uri) // (string _str) { var BitmapImageTemp = new System.Windows.Media.Imaging.BitmapImage(); int BytesToRead = 100; WebRequest request = WebRequest.Create(_uri); // (new Uri(_str, UriKind.Absolute)) request.Timeout = -1; WebResponse response = request.GetResponse(); Stream responseStream = response.GetResponseStream(); BinaryReader reader = new BinaryReader(responseStream); MemoryStream memoryStream = new MemoryStream(); byte[] bytebuffer = new byte[BytesToRead]; int bytesRead = reader.Read(bytebuffer, 0, BytesToRead); while (bytesRead > 0) { memoryStream.Write(bytebuffer, 0, bytesRead); bytesRead = reader.Read(bytebuffer, 0, BytesToRead); } BitmapImageTemp.BeginInit(); memoryStream.Seek(0, SeekOrigin.Begin); BitmapImageTemp.StreamSource = memoryStream; BitmapImageTemp.EndInit(); return(BitmapImageTemp); }
public override bool View(DecompilerTextView textView) { try { AvalonEditTextOutput output = new AvalonEditTextOutput(); Data.Position = 0; BitmapImage image = new BitmapImage(); //HACK: windows imaging does not understand that .cur files have the same layout as .ico // so load to data, and modify the ResourceType in the header to make look like an icon... byte[] curData = ((MemoryStream)Data).ToArray(); curData[2] = 1; using (Stream stream = new MemoryStream(curData)) { image.BeginInit(); image.StreamSource = stream; image.EndInit(); } output.AddUIElement(() => new Image { Source = image }); output.WriteLine(); output.AddButton(Images.Save, "Save", delegate { Save(null); }); textView.ShowNode(output, this, null); return true; } catch (Exception) { return false; } }
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value == null) { return(null); } //Your incoming ToolImage object var image = (System.Drawing.Image)value; //new-up a BitmapImage var bitmap = new System.Windows.Media.Imaging.BitmapImage(); bitmap.BeginInit(); //stream image info from Image to BitmapImage MemoryStream memoryStream = new MemoryStream(); image.Save(memoryStream, ImageFormat.Bmp); memoryStream.Seek(0, System.IO.SeekOrigin.Begin); bitmap.StreamSource = memoryStream; bitmap.EndInit(); //return the BitmapImage that you can bind to the XAML return(bitmap); }
private void LoadStorage() { if (!File.Exists(JsonFileName)) { throw new FileNotFoundException("cannot find file " + JsonFileName); } using (FileStream fs = new FileStream(JsonFileName, FileMode.Open, FileAccess.Read)) { var reader = new StreamReader(fs); var data = reader.ReadToEnd(); Storage.ReadStorageJosn(data); } foreach (var obj in Storage.GetWallpapers()) { var abspath = Path.GetFullPath(ImagePath + obj.FileName + obj.Extension); var img = new BitmapImage(new Uri(abspath)); lock (objLocker) { ImageDictionary[obj.Url] = img; UrlSet[obj.Url] = obj.Titile; } WallpaperList.Add(new WallpaperInfo() { Url = obj.Url, Title = obj.Titile }); } }
public BitmapImage GetMenuItemImage(string imageID, string companyID) { System.Windows.Media.Imaging.BitmapImage wpfImg = new System.Windows.Media.Imaging.BitmapImage(); try { DBStoredImage dbStoredImage = _context.DBStoredImages.First(); _context.IgnoreResourceNotFoundException = true; _context.MergeOption = MergeOption.NoTracking; dbStoredImage = (from q in _context.DBStoredImages where q.ImageID == imageID && q.CompanyID == companyID select q).FirstOrDefault(); MemoryStream stream = new MemoryStream(); stream.Write(dbStoredImage.StoredImage, 0, dbStoredImage.StoredImage.Length); //System.Windows.Media.Imaging.BitmapImage wpfImg = new System.Windows.Media.Imaging.BitmapImage(); wpfImg.BeginInit(); wpfImg.StreamSource = stream; wpfImg.EndInit(); }//if image fails we will return the empty bitmapimage object catch {//reset it as to have a new crisp empty one to return... as to hopefull not cause errors when trying to display a corrupted one... wpfImg = new System.Windows.Media.Imaging.BitmapImage(); } return(wpfImg); }
private void apartment_Click(object sender, RoutedEventArgs e) { index.DataContext = "1"; indexStack.Background = new SolidColorBrush(Color.FromRgb(53, 60, 70)); BitmapImage image1 = new BitmapImage(new Uri("\\icon\\index.png", UriKind.Relative)); indexImg.Source = image1; undergraduate.DataContext = "1"; undergraduateStack.Background = new SolidColorBrush(Color.FromRgb(53, 60, 70)); BitmapImage image2 = new BitmapImage(new Uri("\\icon\\undergraduate.png", UriKind.Relative)); undergraduateImg.Source = image2; graduate.DataContext = "1"; graduateStack.Background = new SolidColorBrush(Color.FromRgb(53, 60, 70)); BitmapImage image3 = new BitmapImage(new Uri("\\icon\\graduate.png", UriKind.Relative)); graduateImg.Source = image3; document.DataContext = "1"; documentStack.Background = new SolidColorBrush(Color.FromRgb(53, 60, 70)); BitmapImage image4 = new BitmapImage(new Uri("\\icon\\document.png", UriKind.Relative)); documentImg.Source = image4; apartment.DataContext = "2"; currTab.Content = new currTab.apartment(); }
private void _client_ImageReceived(object sender, System.Windows.Media.Imaging.BitmapImage e) { Dispatcher.Invoke(() => { image.Source = e; }); }
public SignatureWindow(string signature) { var digitalSignatureCollection = new List<object>(); digitalSignatureCollection.Add(new ComboBoxItem() { Content = "" }); digitalSignatureCollection.AddRange(Settings.Instance.Global_DigitalSignatureCollection.Select(n => new DigitalSignatureComboBoxItem(n)).ToArray()); InitializeComponent(); { var icon = new BitmapImage(); icon.BeginInit(); icon.StreamSource = new FileStream(Path.Combine(App.DirectoryPaths["Icons"], "Amoeba.ico"), FileMode.Open, FileAccess.Read, FileShare.Read); icon.EndInit(); if (icon.CanFreeze) icon.Freeze(); this.Icon = icon; } _signatureComboBox.ItemsSource = digitalSignatureCollection; for (int index = 0; index < Settings.Instance.Global_DigitalSignatureCollection.Count; index++) { if (Settings.Instance.Global_DigitalSignatureCollection[index].ToString() == signature) { _signatureComboBox.SelectedIndex = index + 1; break; } } }
private void LiveControlManager_OnScreenshotReceived(object sender, ScreenshotMessageEventArgs e) { var screenshot = e.Screenshot; using (var stream = new System.IO.MemoryStream(screenshot.Image)) { Image image = Image.FromStream(stream); var bitmap = new System.Windows.Media.Imaging.BitmapImage(); bitmap.BeginInit(); MemoryStream memoryStream = new MemoryStream(); // Save to a memory stream... image.Save(memoryStream, ImageFormat.Bmp); // Rewind the stream... memoryStream.Seek(0, System.IO.SeekOrigin.Begin); bitmap.StreamSource = memoryStream; bitmap.EndInit(); //this.BGImage.Source = bitmap; //if (dispatcher != null) //Dispatcher.BeginInvoke(MainWindow.RefreshUI,bitmap); //if (ShowRegionOutlines) //{ // var gfx = gdiScreen1.CreateGraphics(); // gfx.DrawLine(pen, new Point(e.Screenshot.Region.X, e.Screenshot.Region.Y), new Point(e.Screenshot.Region.X + e.Screenshot.Region.Width, e.Screenshot.Region.Y)); // gfx.DrawLine(pen, new Point(e.Screenshot.Region.X + e.Screenshot.Region.Width, e.Screenshot.Region.Y), new Point(e.Screenshot.Region.X + e.Screenshot.Region.Width, e.Screenshot.Region.Y + e.Screenshot.Region.Y)); // gfx.DrawLine(pen, new Point(e.Screenshot.Region.X + e.Screenshot.Region.Width, e.Screenshot.Region.Y + e.Screenshot.Region.Y), new Point(e.Screenshot.Region.X, e.Screenshot.Region.Y + e.Screenshot.Region.Y)); // gfx.DrawLine(pen, new Point(e.Screenshot.Region.X, e.Screenshot.Region.Y + e.Screenshot.Region.Y), new Point(e.Screenshot.Region.X, e.Screenshot.Region.Y)); // gfx.Dispose(); //} //gdiScreen1.Draw(image, screenshot.Region); } // LiveControlManager.RequestScreenshot(); }
/// <summary> /// Gets the bitmap image. /// </summary> /// <param name="uri">The URI.</param> /// <returns>BitmapImage.</returns> /// <exception cref="System.ArgumentNullException">uri</exception> public BitmapImage GetBitmapImage(Uri uri) { if (uri == null) { throw new ArgumentNullException("uri"); } var bitmap = new BitmapImage { CreateOptions = BitmapCreateOptions.DelayCreation, CacheOption = BitmapCacheOption.OnDemand, UriCachePolicy = new RequestCachePolicy(RequestCacheLevel.CacheIfAvailable) }; var scalingMode = _config.Configuration.EnableHighQualityImageScaling ? BitmapScalingMode.Fant : BitmapScalingMode.LowQuality; RenderOptions.SetBitmapScalingMode(bitmap, scalingMode); bitmap.BeginInit(); bitmap.UriSource = uri; bitmap.EndInit(); return bitmap; }
public BitmapImage getPacImage() { // double width = (Image_Grid.ActualWidth * 160 )/ 700; // double height = (Image_Grid.ActualHeight * 160 )/ 190; RenderTargetBitmap rtb = new RenderTargetBitmap((int)Image_Grid.ActualWidth, (int)Image_Grid.ActualHeight, 96, 96, PixelFormats.Pbgra32); rtb.Render(Image_Grid); PngBitmapEncoder png = new PngBitmapEncoder(); png.Frames.Add(BitmapFrame.Create(rtb)); MemoryStream stream = new MemoryStream(); png.Save(stream); System.Drawing.Image bmp = System.Drawing.Image.FromStream(stream); System.IO.MemoryStream ms = new System.IO.MemoryStream(); bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Png);// 格式自处理,这里用 bitmap // 下行,初始一个 ImageSource 作为 myImage 的Source System.Windows.Media.Imaging.BitmapImage bi = new System.Windows.Media.Imaging.BitmapImage(); bi.BeginInit(); bi.StreamSource = new MemoryStream(ms.ToArray()); // 不要直接使用 ms bi.EndInit(); //myImage.Source = bi; // done! ms.Close(); return(bi); }
public override Brush getViewTile(ICase tile) { ImageBrush brush = new ImageBrush(); if (tile is CaseDesert) { if (tileDesert == null) tileDesert = new BitmapImage(new Uri("../../Resources/" + styleName + "/caseDesert.png", UriKind.Relative)); brush.ImageSource = tileDesert; } else if (tile is CaseEau) { if (tileEau == null) tileEau = new BitmapImage(new Uri("../../Resources/" + styleName + "/caseEau.png", UriKind.Relative)); brush.ImageSource = tileEau; } else if (tile is CaseForet) { if (tileForet == null) tileForet = new BitmapImage(new Uri("../../Resources/" + styleName + "/caseForet.png", UriKind.Relative)); brush.ImageSource = tileForet; } else if (tile is CaseMontagne) { if (tileMontagne == null) tileMontagne = new BitmapImage(new Uri("../../Resources/" + styleName + "/caseMontagne.png", UriKind.Relative)); brush.ImageSource = tileMontagne; } else if (tile is CasePlaine) { if (tilePlaine == null) tilePlaine = new BitmapImage(new Uri("../../Resources/" + styleName + "/casePlaine.png", UriKind.Relative)); brush.ImageSource = tilePlaine; } return brush; }
public System.Windows.Media.Imaging.BitmapImage createImage() { string fileName = filePath; using (var file = new org.pdfclown.files.File(fileName)) { Document document = file.Document; Pages pages = document.Pages; Page page = pages[0]; SizeF imageSize = page.Size; Renderer renderer = new Renderer(); System.Drawing.Image image = renderer.Render(page, imageSize); // Winforms Image we want to get the WPF Image from var bitmap = new System.Windows.Media.Imaging.BitmapImage(); bitmap.BeginInit(); MemoryStream memoryStream = new MemoryStream(); // Save to a memory stream image.Save(memoryStream, ImageFormat.Bmp); // Rewind the stream memoryStream.Seek(0, System.IO.SeekOrigin.Begin); bitmap.StreamSource = memoryStream; bitmap.EndInit(); return(bitmap); } }
/* * This returns the status of the system i.e. running or not... */ bool SetRunningStatus(bool running) { if (running) { if(mIsRunning == false) { var uri = new Uri("pack://application:,,,/Images/Generic/RunningOn.png"); var bitmap = new BitmapImage(uri); StatusIndicator.Source = bitmap; statusLabel.Content = "Started!"; mIsRunning = true; return true; } else { MessageBox.Show("The task is already running, try stopping it first!"); return false; } } else { var uri = new Uri("pack://application:,,,/Images/Generic/RunningOff.png"); var bitmap = new BitmapImage(uri); StatusIndicator.Source = bitmap; statusLabel.Content = "Stopped!"; mIsRunning = false; return true; } }
public Tuple <BitmapImage, Color> LoadAnimationTexture(string fileName, bool transparent = false) { if (transparent) { FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read); System.Drawing.Bitmap img = new System.Drawing.Bitmap(fileStream); fileStream.Close(); var color = img.Palette.Entries[0]; string hex = HexConverter(color); img.MakeTransparent(color); var finalResult = (BitmapImage)Extensions.BitmapConversion.ToWpfBitmap((System.Drawing.Bitmap)img.Clone()); img.Dispose(); return(new Tuple <BitmapImage, Color>(finalResult, (Color)ColorConverter.ConvertFromString(hex))); } else { FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read); var img = new System.Windows.Media.Imaging.BitmapImage(); img.BeginInit(); img.StreamSource = fileStream; img.CacheOption = BitmapCacheOption.OnLoad; img.EndInit(); var finalResult = (BitmapImage)img.Clone(); fileStream.Close(); return(new Tuple <BitmapImage, Color>(finalResult, Colors.Black)); } }
/// <summary> /// Called when IsEnabled property is changed for all GreyscalOnDisabledImage instances. /// </summary> /// <param name="source"></param> /// <param name="args"></param> private static void OnGreyscaleOnDisabledImageIsEnabledPropertyChanged(DependencyObject source, DependencyPropertyChangedEventArgs args) { // Get the image object. var img = source as GreyscaleOnDisabledImage; // Ensure we have an instance of GreyscaleOnDisabledImage. if (img == null) return; // Check the new value of the IsEnabled property if (Convert.ToBoolean(args.NewValue)) // It is enabled (true)? { // Set the Source property to the original value. img.Source = ((FormatConvertedBitmap)img.Source).Source; // Reset the Opcity Mask img.OpacityMask = null; } else // It isn't enabled (false), use greyscale! { // Get the image as a bitmap var bitmapImage = new BitmapImage(new Uri(img.Source.ToString())); // Convert the image to greyscale using the bitmap img.Source = new FormatConvertedBitmap(bitmapImage, PixelFormats.Gray32Float, null, 0); // Create an Opacity Mask to use for the greyscale image img.OpacityMask = new ImageBrush(bitmapImage); } }
private void Init(String n, bool s) { Name = n; Male = s; JobRole = "Boss"; pictureFile = ".../.../Pictures/Enemies/Ravenscroft.png"; characterPicture = new BitmapImage(new Uri(pictureFile, UriKind.Relative)); /****************************************************************** * stat progression unique to this job role. * **************************************************************** */ HealthMulti = 3.00; EnergyMulti = 3.00; AttackMulti = 2.00; DefenseMulti = 3.00; SpeedMulti = 2; AgilityMulti = 2; AttackRangeMulti = 1.00; SpecialAttackMulti = 3.00; SpecialDefenseMulti = 3.00; ExperienceAmountMulti = 100.00; /****************************************************************** * stats initialized after multipliers applied. * **************************************************************** */ InstantiateLevel(1); }
public AnimatedGifWindow() { var img = new Image(); var src = default(BitmapImage); var source = Path.Combine( Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "background.gif"); if (File.Exists(source)) { src = new BitmapImage(); src.BeginInit(); src.StreamSource = File.OpenRead(source); src.EndInit(); ImageBehavior.SetAnimatedSource(img, src); this.Content = img; this.Width = src.Width; this.Height = src.Height; } this.AllowsTransparency = true; this.WindowStyle = WindowStyle.None; this.WindowStartupLocation = WindowStartupLocation.CenterScreen; this.ShowInTaskbar = true; this.Topmost = true; this.TaskbarItemInfo = new TaskbarItemInfo { ProgressState = TaskbarItemProgressState.Normal }; this.Background = new SolidColorBrush(Color.FromArgb(0, 0, 0, 0)); }
public static System.Windows.Media.Imaging.BitmapImage DrawingImageToBitmapImage(System.Drawing.Image dImage) { if (dImage == null) { return(null); } var image = new System.Windows.Media.Imaging.BitmapImage(); using (var stream = new MemoryStream()) { dImage.Save(stream, System.Drawing.Imaging.ImageFormat.Png); stream.Seek(0, SeekOrigin.Begin); image.BeginInit(); image.CreateOptions = System.Windows.Media.Imaging.BitmapCreateOptions.PreservePixelFormat; image.CacheOption = System.Windows.Media.Imaging.BitmapCacheOption.OnLoad; image.UriSource = null; image.StreamSource = stream; image.EndInit(); } image.Freeze(); return(image); }