public BitmapImage Render(uint clearColor, uint setColor) { int resultWidth = Data.Count; int maximum = Data.Max(); double divisor = 1; int resultHeight = maximum; if (resultHeight > 1024) { while (resultHeight > 1024) { resultHeight /= 2; divisor *= 2; } } BitmapImage result = new BitmapImage(resultWidth, resultHeight); result.SetAllPixels(clearColor); for (int i = 0; i < Data.Count; i++) { int element = Data[i]; int adjustedHeight = (element > 1) ? (int)(element / divisor) : 1; int y = result.Height - 1; while (adjustedHeight > 0) { result[i, y] = setColor; y--; adjustedHeight--; } } return result; }
public async void Open(Image source, TextBox target) { try { FileOpenPicker picker = new FileOpenPicker(); picker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary; picker.FileTypeFilter.Add(textExt); picker.FileTypeFilter.Add(imageExt); StorageFile file = await picker.PickSingleFileAsync(); switch (file.FileType) { case textExt: target.Text = await FileIO.ReadTextAsync(file); break; case imageExt: using (IRandomAccessStream stream = await file.OpenReadAsync()) { BitmapDecoder bitmapDecoder = await BitmapDecoder.CreateAsync(stream); SoftwareBitmap softwareBitmap = await bitmapDecoder.GetSoftwareBitmapAsync( BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied); OcrEngine engine = OcrEngine.TryCreateFromLanguage(new Language("en-us")); OcrResult ocrResult = await engine.RecognizeAsync(softwareBitmap); target.Text = ocrResult.Text; stream.Seek(0); BitmapImage image = new BitmapImage(); image.SetSource(stream); source.Source = image; } break; default: break; } } catch { } }
public static BitmapImage GetImage(string path, bool negateResult = false) { if (string.IsNullOrEmpty(path)) return null; var isDarkTheme = #if WINDOWS_STORE || WINDOWS_PHONE_APP Application.Current.RequestedTheme == ApplicationTheme.Dark; #elif WINDOWS_PHONE (Application.Current.Resources.Contains("PhoneDarkThemeVisibility") && ((Visibility) Application.Current.Resources["PhoneDarkThemeVisibility"]) == Visibility.Visible); #endif if (negateResult) isDarkTheme = !isDarkTheme; BitmapImage result; path = string.Format(path, isDarkTheme ? "dark" : "light"); // Check if we already cached the image if (!ImageCache.TryGetValue(path, out result)) { result = new BitmapImage(new Uri(path, UriKind.Relative)); ImageCache.Add(path, result); } return result; }
static void Main(string[] args) { ResourceWriter myResource = new ResourceWriter("Images.resources"); myResource.AddResource("flash", new Bitmap("flashScreen.png")); Image simpleImage = new Image(); simpleImage.Margin = new Thickness(0); BitmapImage bi = new BitmapImage(); //BitmapImage.UriSource must be in a BeginInit/EndInit block bi.BeginInit(); bi.UriSource = new Uri(@"pack://siteoforigin:,,,/alarm3.png"); bi.EndInit(); //set image source simpleImage.Source = bi; // simpleImage.Stretch = Stretch.None; simpleImage.HorizontalAlignment = HorizontalAlignment.Center; simpleImage.Visibility = Visibility.Hidden; simpleImage.Name = "AlarmIndicator"; simpleImage.Width = 13; myResource.AddResource("alarm", new Image("alarm3.png")); myResource.Close(); }
static public Texture2D LoadBitmap(string imageName, int w, int h) { // // Load a bitmap image through writeablebitmap so that we can populate our device // texture // StreamResourceInfo sr = Application.GetResourceStream(new Uri(imageName, UriKind.Relative)); BitmapImage bs = new BitmapImage(); bs.SetSource(sr.Stream); var wb = new WriteableBitmap(w, h); ScaleTransform t = new ScaleTransform(); t.ScaleX = (double)w / (double)bs.PixelWidth; t.ScaleY = (double)h / (double)bs.PixelHeight; Image image = new Image(); image.Source = bs; wb.Render(image, t); wb.Invalidate(); Texture2D tex = new Texture2D(GraphicsDeviceManager.Current.GraphicsDevice, wb.PixelWidth, wb.PixelHeight, false, SurfaceFormat.Color); wb.CopyTo(tex); return tex; }
public object Convert(object value, Type typeName, object parameter, string language) #endif { if (value is byte[]) { var array = (byte[])value; if (array.Length > 0) { try { var stream = new MemoryStream(); stream.Write(array, 0, array.Length); var img = new BitmapImage(); #if WINRT img.SetSource(stream.AsRandomAccessStream()); #elif WPF img.StreamSource = stream; #else img.SetSource(stream); #endif return img; } catch { } } } return null; }
/// <summary> /// Converts a value. /// </summary> /// <param name="value">The value produced by the binding source.</param> /// <param name="targetType">The type of the binding target property.</param> /// <param name="parameter">The converter parameter to use.</param> /// <param name="culture">The culture to use in the converter.</param> /// <returns> /// A converted value. If the method returns null, the valid null value is used. /// </returns> public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { if (value == null) { return null; } // if if (value is string) { value = new Uri((string)value, UriKind.RelativeOrAbsolute); } // if if (value is Uri) { BitmapImage bi = new BitmapImage(); #if !NETFX_CORE bi.BeginInit(); #endif bi.DecodePixelWidth = 80; //// bi.DecodePixelHeight = 60; bi.UriSource = (Uri)value; #if !NETFX_CORE bi.EndInit(); #endif return bi; } // if return null; } // Convert
/// <summary> /// Loads an IImage from a path /// </summary> /// <param name="path"></param> /// <returns></returns> public async Task<IImage> LoadImageAsync(string path) { var file = await Windows.Storage.KnownFolders.PicturesLibrary.GetFileAsync(path); var fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read); var bitmap = new BitmapImage(); bitmap.SetSource(fileStream); return new BitmapImageImage(bitmap); }
private async void ColorThread() { try { var reader = new DataReader( Client.InputStream ); reader.InputStreamOptions = InputStreamOptions.Partial; reader.ByteOrder = ByteOrder.LittleEndian; while ( IsConnected ) { await reader.LoadAsync( 4 ); var size = reader.ReadUInt32(); await reader.LoadAsync( size ); byte[] bytes = new byte[size]; reader.ReadBytes( bytes ); MemoryStream ms = new MemoryStream( bytes ); BinaryReader br = new BinaryReader(ms); ColorFrameReadyEventArgs args = new ColorFrameReadyEventArgs(); ColorFrameData cfd = new ColorFrameData(); cfd.Format = (ImageFormat)br.ReadInt32(); cfd.ImageFrame = br.ReadColorImageFrame(); MemoryStream msData = new MemoryStream( bytes, (int)ms.Position, (int)(ms.Length - ms.Position) ); if (cfd.Format == ImageFormat.Raw) { cfd.RawImage = ms.ToArray(); } else { InMemoryRandomAccessStream ras = new InMemoryRandomAccessStream(); DataWriter dw = new DataWriter(ras.GetOutputStreamAt(0)); dw.WriteBytes(msData.ToArray()); await dw.StoreAsync(); // Set to the image BitmapImage bImg = new BitmapImage(); bImg.SetSource(ras); cfd.BitmapImage = bImg; } ColorFrame = cfd; args.ColorFrame = cfd; if (ColorFrameReady != null) { ColorFrameReady(this, args); } } } catch(IOException) { Disconnect(); } }
/// <summary> /// Loads an IImage from a path /// </summary> /// <param name="path"></param> /// <returns></returns> public IImage LoadImage(string path) { using (var fs = File.OpenRead(path)) { var bitmap = new BitmapImage(); bitmap.SetSource(fs); return new BitmapImageImage(bitmap); } }
private static async void OnCacheUriChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { //Uri oldCacheUri = (Uri)e.OldValue; Uri newCacheUri = (Uri)d.GetValue(CacheUriProperty); if (newCacheUri != null) { try { //Get image from cache (download and set in cache if needed) var cacheUri = await WebDataCache.GetLocalUriAsync(newCacheUri); // Check if the wanted image uri has not changed while we were loading if (newCacheUri != (Uri)d.GetValue(CacheUriProperty)) return; #if NETFX_CORE //Set cache uri as source for the image SetSourceOnObject(d, new BitmapImage(cacheUri)); #elif WINDOWS_PHONE BitmapImage bimg = new BitmapImage(); using (IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication()) { using (IsolatedStorageFileStream stream = iso.OpenFile(cacheUri.PathAndQuery, FileMode.Open, FileAccess.Read)) { bimg.SetSource(stream); } } //Set cache uri as source for the image SetSourceOnObject(d, bimg); #endif } catch (Exception ex) { Debug.WriteLine(ex); //Revert to using passed URI SetSourceOnObject(d, new BitmapImage(newCacheUri), false); } } else { SetSourceOnObject(d, null, false); } }
public ImageButton(Action<ImageButton> onClick = null) { if (onClick != null) OnClick += onClick; mImage = new BitmapImage(1, 1, new BitmapProperties() { DpiX = 96.0f, DpiY = 96.0f, PixelFormat = new PixelFormat {AlphaMode = AlphaMode.Premultiplied, Format = SharpDX.DXGI.Format.B8G8R8A8_UNorm} }); }
public static BitmapImage GetImageFromIso(string fileName) { BitmapImage bi = new BitmapImage(); using (IsolatedStorageFile isof = IsolatedStorageFile.GetUserStoreForApplication()) { IsolatedStorageFileStream fileStream = isof.OpenFile(fileName, FileMode.Open, FileAccess.Read); bi.SetSource(fileStream); //this.img.Height = bi.PixelHeight; //this.img.Width = bi.PixelWidth; } return bi; }
private void ColorThread() { try { NetworkStream ns = Client.GetStream(); BinaryReader reader = new BinaryReader(ns); while(Client.Connected) { ColorFrameReadyEventArgs args = new ColorFrameReadyEventArgs(); ColorFrameData cfd = new ColorFrameData(); int size = reader.ReadInt32(); byte[] data = reader.ReadBytes(size); MemoryStream ms = new MemoryStream(data); BinaryReader br = new BinaryReader(ms); cfd.Format = (ImageFormat)br.ReadInt32(); cfd.ImageFrame = br.ReadColorImageFrame(); MemoryStream msData = new MemoryStream(data, (int)ms.Position, (int)(ms.Length - ms.Position)); Context.Send(delegate { if(cfd.Format == ImageFormat.Raw) cfd.RawImage = ms.ToArray(); else { BitmapImage bi = new BitmapImage(); bi.BeginInit(); bi.StreamSource = msData; bi.EndInit(); cfd.BitmapImage = bi; } ColorFrame = cfd; args.ColorFrame = cfd; if(ColorFrameReady != null) ColorFrameReady(this, args); }, null); } } catch(IOException) { Client.Close(); } }
public async Task ExibirImagem(IRandomAccessStream stream, bool forcar = false) #endif { if (!forcar && Image != null) return; var bitmapImage = new BitmapImage(); #if WINDOWS_PHONE bitmapImage.SetSource(stream); #elif NETFX_CORE await bitmapImage.SetSourceAsync(stream); #endif Image = bitmapImage; ShowImage = true; NotifyOfPropertyChange("IsValid"); }
/// <summary>Creates a single UI element for the given HTML node and HTML view.</summary> /// <param name="node">The node.</param> /// <param name="htmlView">The text block.</param> /// <returns>The UI element.</returns> public override DependencyObject CreateControl(HtmlNode node, IHtmlView htmlView) { try { var imageUri = node.Attributes["src"]; var height = 0; if (node.Attributes.ContainsKey("height")) int.TryParse(node.Attributes["height"], out height); var width = 0; if (node.Attributes.ContainsKey("width")) int.TryParse(node.Attributes["width"], out width); if (height == 1 && width == 1) return null; var image = new Image(); image.Width = 0; image.Height = 0; var bitmapImage = new BitmapImage(new Uri(imageUri)); var imageBlock = new ImageBlock { Image = image, UserHeight = height, UserWidth = width, Source = bitmapImage }; bitmapImage.ImageOpened += delegate { imageBlock.Update(htmlView.ActualWidth); }; image.HorizontalAlignment = HorizontalAlignment.Left; image.Source = bitmapImage; image.Margin = new Thickness(0, htmlView.ParagraphMargin, 0, htmlView.ParagraphMargin); if (width > 0) image.Width = width; if (height > 0) image.Height = height; htmlView.SizeDependentControls.Add(imageBlock); return new ContentPresenter { Content = image }; } catch { return null; } }
/// <summary> /// Converts image type from SQL Server (byte[]) to WPF BitmapImage /// </summary> /// <param name="array">SQL Image (byte[])</param> /// <returns></returns> public static BitmapImage ByteToBitmapImage(byte[] data) { MemoryStream ms1 = new MemoryStream(); ms1.Write(data, 0, data.Length); ms1.Position = 0; Image image = Image.FromStream(ms1); BitmapImage bitmapImage = new BitmapImage(); bitmapImage.BeginInit(); MemoryStream ms2 = new MemoryStream(); image.Save(ms2, ImageFormat.Png); ms2.Seek(0, SeekOrigin.Begin); bitmapImage.StreamSource = ms2; bitmapImage.EndInit(); return bitmapImage; }
// // LoadTexture - Create a Texture2D from an image in our XAP // static public Texture2D LoadBitmap(string imageName) { // // Load a bitmap image through writeablebitmap so that we can populate our device // texture // StreamResourceInfo sr = Application.GetResourceStream(new Uri(imageName, UriKind.Relative)); BitmapImage bs = new BitmapImage(); bs.SetSource(sr.Stream); Texture2D t = new Texture2D(GraphicsDeviceManager.Current.GraphicsDevice, bs.PixelWidth, bs.PixelHeight, false, SurfaceFormat.Color); bs.CopyTo(t); return t; }
/// <summary> /// Gets the image from the URI. If the image starts with isostore:/ that it will get the image /// out of isolatedstorage, otherwise it will just use the URI as is. /// </summary> /// <param name="imageSource">The image source URI.</param> /// <returns> /// The image as a BitmapImage so it can be set against the Image item /// </returns> public static ImageSource ToBitmapImage(this ImageSource imageSource) { // If the imageSource is null, then there's nothing further to see here if (imageSource == null) { return null; } var checkedImageSource = imageSource as BitmapImage; if (checkedImageSource == null) { return imageSource; } #if WINDOWS_PHONE var imgSource = checkedImageSource.UriSource.ToString().ToLower(); // If the imgSource is an isostore uri, then we need to pull it out of storage if (imgSource.StartsWith(IsoStoreScheme) || imgSource.StartsWith(MsAppXScheme)) { imgSource = imgSource.Replace(IsoStoreScheme, string.Empty).TrimEnd('.'); imgSource = imgSource.Replace(MsAppXScheme, string.Empty).TrimEnd('.'); checkedImageSource = new BitmapImage(); if (!ApplicationSpace.IsDesignMode) { // TODO: get this to leverage storage classes using (var isoStore = IsolatedStorageFile.GetUserStoreForApplication()) { if (isoStore.FileExists(imgSource)) { using (var file = isoStore.OpenFile(imgSource, FileMode.Open)) { checkedImageSource.SetSource(file); } } } } } #endif return checkedImageSource; }
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { if (value == null) return null; if (!string.IsNullOrEmpty(value.ToString())) { BitmapImage bi = new BitmapImage(); bi.BeginInit(); bi.UriSource = new Uri(value.ToString()); bi.CacheOption = BitmapCacheOption.OnLoad; bi.EndInit(); return bi; } return null; }
public override DependencyObject GenerateSingle(HtmlNode node, IHtmlTextBlock textBlock) { try { var uri = node.Attributes["src"]; var height = 0; if (node.Attributes.ContainsKey("height")) int.TryParse(node.Attributes["height"], out height); var width = 0; if (node.Attributes.ContainsKey("width")) int.TryParse(node.Attributes["width"], out width); if (height == 1 && width == 1) return null; var image = new Image(); var imgSource = new BitmapImage(new Uri(uri)); var block = new ImageBlock { Image = image, UserHeight = height, UserWidth = width, Source = imgSource }; imgSource.ImageOpened += delegate { block.Update(textBlock.ActualWidth); }; image.HorizontalAlignment = HorizontalAlignment.Left; image.Source = imgSource; image.Margin = new Thickness(0, textBlock.ParagraphMargin, 0, textBlock.ParagraphMargin); if (width > 0) image.Width = width; if (height > 0) image.Height = height; textBlock.SizeDependentControls.Add(block); return image; } catch { return null; } }
private static BitmapImage LoadImage(byte[] imageData) { if (imageData == null || imageData.Length == 0) return null; var image = new BitmapImage(); using (var mem = new MemoryStream(imageData)) { mem.Position = 0; image.BeginInit(); image.CreateOptions = BitmapCreateOptions.PreservePixelFormat; image.CacheOption = BitmapCacheOption.OnLoad; image.UriSource = null; image.StreamSource = mem; image.EndInit(); } image.Freeze(); return image; }
public static Bitmap BitmapImage2Bitmap(BitmapImage bitmapImage) { try { using (var outStream = new MemoryStream()) { BitmapEncoder enc = new BmpBitmapEncoder(); enc.Frames.Add(BitmapFrame.Create(bitmapImage)); enc.Save(outStream); var bitmap = new Bitmap(outStream); return new Bitmap(bitmap); } } catch { return null; } }
public static BitmapSource ToWpfBitmap(this Bitmap bitmap) { using (MemoryStream stream = new MemoryStream()) { bitmap.Save(stream, ImageFormat.Bmp); stream.Position = 0; BitmapImage result = new BitmapImage(); result.BeginInit(); // According to MSDN, "The default OnDemand cache option retains access to the stream until the image is needed." // Force the bitmap to load right now so we can dispose the stream. result.CacheOption = BitmapCacheOption.OnLoad; result.StreamSource = stream; result.EndInit(); result.Freeze(); return result; } }
public static BitmapImage CreateBitmapImage(this Stream imageData) { var bitmapImage = new BitmapImage(); #if SILVERLIGHT imageData.Position = 0; bitmapImage.SetSource(imageData); #elif NETFX_CORE imageData.Position = 0; var memoryStream = new System.IO.MemoryStream(); imageData.CopyTo(memoryStream); bitmapImage.SetSource(ToRandomAccessStream(memoryStream).Result); #else imageData.Position = 0; bitmapImage.BeginInit(); bitmapImage.StreamSource = imageData; bitmapImage.EndInit(); #endif return bitmapImage; }
public static IObservable<BitmapImage> BytesToImage(byte[] compressedImage) { try { var ret = new BitmapImage(); #if SILVERLIGHT ret.SetSource(new MemoryStream(compressedImage)); #else ret.BeginInit(); ret.StreamSource = new MemoryStream(compressedImage); ret.EndInit(); ret.Freeze(); #endif return Observable.Return(ret); } catch (Exception ex) { return Observable.Throw<BitmapImage>(ex); } }
/// <summary> /// Populates the page with content passed during navigation. Any saved state is also /// provided when recreating a page from a prior session. /// </summary> /// <param name="navigationParameter">The parameter value passed to /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested. /// </param> /// <param name="pageState">A dictionary of state preserved by this page during an earlier /// session. This will be null the first time a page is visited.</param> protected override void LoadState(LoadStateEventArgs e) // WAS: LoadState(Object navigationParameter, Dictionary<String, Object> pageState) { Opened(); #if TODOish pageSubtitle.Text = " " + App.CurrentDisasterEventName; // TO DO: binding in XAML instead of here? Add space to separate from icon string prefix = "ms-appx:///"; if (App.CurrentDisasterEventTypeIcon.Length > prefix.Length) { eventTypeImage.Source = new BitmapImage(new Uri(App.CurrentDisasterEventTypeIcon)); #if MAYBE string path = App.CurrentDisasterEventTypeIcon.Substring(prefix.Length); path += Windows.ApplicationModel.Package.Current.InstalledLocation.ToString(); BitmapImage img = new BitmapImage(); var uri = new Uri(path); img.UriSource = uri; eventTypeImage.Source = img; #endif // Tried XAML binding, didn't work: <Image x:Name="eventTypeImage" Source="{Binding CurrentDisasterEventTypeIcon}" Width="40" VerticalAlignment="Top"/> MyZoneButtonItemWidth = "140"; } #endif }
private ImageSource GetFile(string str) { ImageSource result; if (File.Exists(AppDomain.CurrentDomain.BaseDirectory + "\\CrystalIcons\\32x32\\" + str)) { BitmapImage bitmapImage = new BitmapImage(); bitmapImage.BeginInit(); bitmapImage.UriSource = new Uri(AppDomain.CurrentDomain.BaseDirectory + "\\CrystalIcons\\32x32\\" + str, UriKind.Absolute); bitmapImage.EndInit(); result = bitmapImage; } else { BitmapImage bitmapImage = new BitmapImage(); bitmapImage.BeginInit(); bitmapImage.StreamSource = Application.GetResourceStream(new Uri("CrystalIcons/32x32/" + str, UriKind.RelativeOrAbsolute)).Stream; bitmapImage.EndInit(); result = bitmapImage; } return(result); }
private async void Page_Loaded(object sender, RoutedEventArgs e) { ToursList = await tourHelper.GetAllAsync(); foreach (var t in ToursList) { if (t.Image != null) { byte[] b = Convert.FromBase64String(t.Image); using var ms = new MemoryStream(b); var image = new BitmapImage(); image.BeginInit(); image.CacheOption = BitmapCacheOption.OnLoad; // з кожного запису турів переводимо масив байтів в картинку і .......... image.StreamSource = ms; image.EndInit(); t.TourImage = image;// .............. Присвоюємо цю картинку локальному полю в класі Tour і здійснюємо байндинг до цього поля з елементу зображення } } ListViewTravel.ItemsSource = ToursList; }
public void update_film_info(film f, BitmapImage poster) { panel_film pf = (active.Parent as Border).Parent as panel_film; pf.NameFilm = f.get_name(); pf.Year = f.get_year(); List <string> genres = f.get_genres(); string gnr = ""; for (int i = 0; i < genres.Count; i++) { gnr += genres[i]; if (i != genres.Count - 1) { gnr += ", "; } } pf.Genres = gnr; if (poster != null) { pf.Poster = poster; } }
public void ClosePopup() { try { //Reset the image resources vBitmapImage = null; image_source.Source = null; //Disable page events DisablePageEvents(); //Set Landscape Display if ((bool)AppVariables.ApplicationSettings["DisableLandscapeDisplay"]) { DisplayInformation.AutoRotationPreferences = DisplayOrientations.Portrait; } //Close the popup popup_Main.IsOpen = false; PopupIsOpen = false; } catch { } }
public static void ChangeSource(this Image image, BitmapImage source, TimeSpan fadeOutTime, TimeSpan fadeInTime) { var fadeInAnimation = new DoubleAnimation(1d, fadeInTime); if (image.Source != null) { var fadeOutAnimation = new DoubleAnimation(0d, fadeOutTime); fadeOutAnimation.Completed += (o, e) => { image.Source = source; image.BeginAnimation(Image.OpacityProperty, fadeInAnimation); }; image.BeginAnimation(Image.OpacityProperty, fadeOutAnimation); } else { image.Opacity = 0d; image.Source = source; image.BeginAnimation(Image.OpacityProperty, fadeInAnimation); } }
// Token: 0x06000003 RID: 3 RVA: 0x000021D0 File Offset: 0x000003D0 private void _scan_Loaded(object sender, RoutedEventArgs e) { BitmapImage bitmapImage = new BitmapImage(); bitmapImage.BeginInit(); bitmapImage.UriSource = new Uri("https://graph.facebook.com/" + this.idman + "/picture?height=500"); bitmapImage.EndInit(); this._id.Text = this.idman; this._name.Text = this.nameman; this._image.Source = bitmapImage; base.Title = "Facebook Friends BackUp - " + this.nameman + " - " + this.idman; this.checkoke = 1; this._list.Items.Clear(); this._process.Content = "Đang loading vui lòng chờ..."; RestClient client = new RestClient("https://graph.facebook.com/v3.0/me/friends?access_token=" + this.tk + "&limit=5000&fields=id,name"); client.Timeout = -1; RestRequest request = new RestRequest(Method.GET); IRestResponse response = client.Execute(request); string data = response.Content; JToken stuff = JToken.Parse(data); this.savejson = stuff; int count = Regex.Matches(data, "\"id\"").Count; this.max = count; for (int i = 0; i < count; i++) { this._list.Items.Add(new uiscan.MyItem { Stt = i, Link = "https://facebook.com/" + stuff["data"][i]["id"], Name = stuff["data"][i]["name"].ToString() }); } this._process.Content = "Đã xong! Đã load xong " + this.max + " người bạn."; }
public Level_AreaItemControl(Level_AreaItemWrapper wrapper, BitmapImage icon) : base(wrapper, icon) { PropertyInfo prop = null; // Текст подсказки StringBuilder sb = new StringBuilder(); sb.AppendLine(String.Format(Localization.Tooltip_Level, wrapper.Caption)); prop = wrapper.GetCustomProperty(InfoBase.HIERARCHY_CAPTION); if (prop != null) { sb.AppendLine(String.Format(Localization.Tooltip_Hierarchy, prop.Value)); } prop = wrapper.GetCustomProperty(InfoBase.DIMENSION_CAPTION); if (prop != null) { sb.AppendLine(String.Format(Localization.Tooltip_Dimension, prop.Value)); } prop = wrapper.GetCustomProperty(InfoBase.CUBE_CAPTION); if (prop != null) { sb.AppendLine(String.Format(Localization.Tooltip_Cube, prop.Value)); } String str = sb.ToString(); str = str.TrimEnd('\n'); str.TrimEnd('\r'); // Подсказка ToolTipControl m_ToolTip = new ToolTipControl(); m_ToolTip.Caption = wrapper.Caption; m_ToolTip.Text = str; ToolTipService.SetToolTip(this, m_ToolTip); }
private void LoadImageFromFileName(string fileName) { var oldImageError = imageError; try { // Check file exists, it should! var fi = new FileInfo(fileName); if (fi.Exists) { var i = new BitmapImage(); i.BeginInit(); i.UriSource = new Uri(fileName, UriKind.RelativeOrAbsolute); i.EndInit(); Image = i; // Some santity checking. imageError = i.Width <= 128 && i.Height <= 128 ? ImageError.NoError : ImageError.TooLarge; } else { Image = null; imageError = ImageError.NotFound; } } catch (Exception) { Image = null; imageError = ImageError.Unknown; } if (imageError != oldImageError) { UpdateErrorMessage(true); } }
public void RotationCharacterOfInventory(object sender, MouseButtonEventArgs e) { angle = angle < 5 ? angle++ : (byte)0; var image = new BitmapImage(); image.BeginInit(); switch (angle) { case 0: angleCharacter = "sw"; break; case 1: angleCharacter = "w"; break; case 2: angleCharacter = "nw"; break; case 3: angleCharacter = "ne"; break; case 4: angleCharacter = "e"; break; case 5: angleCharacter = "se"; break; } image.UriSource = new Uri(Environment.CurrentDirectory + "/data/image/characters/" + nameArmor + angleCharacter + ".gif"); image.EndInit(); ImageBehavior.SetAnimatedSource((sender as Image), image); }
private async void ChangeBackground(object sender, RoutedEventArgs e) { Windows.Storage.Pickers.FileOpenPicker picker = new Windows.Storage.Pickers.FileOpenPicker { ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail, SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.PicturesLibrary }; picker.FileTypeFilter.Clear(); picker.FileTypeFilter.Add(".jpg"); picker.FileTypeFilter.Add(".png"); picker.FileTypeFilter.Add(".jpeg"); StorageFile imgFile = await picker.PickSingleFileAsync(); if (imgFile != null) { using (IRandomAccessStream fileStream = await imgFile.OpenAsync(FileAccessMode.Read)) { BitmapImage bitmapImage = new BitmapImage(); await bitmapImage.SetSourceAsync(fileStream); bg.ImageSource = bitmapImage; StorageFolder localFolder = ApplicationData.Current.LocalFolder; BitmapDecoder decoder = await BitmapDecoder.CreateAsync(fileStream); SoftwareBitmap softwareBitmap = await decoder.GetSoftwareBitmapAsync(); StorageFile localFile = await localFolder.CreateFileAsync("background.jpg", CreationCollisionOption.ReplaceExisting); await ImgManager.SaveSoftwareBitmapToFile(softwareBitmap, localFile); } } }
/// <summary> /// Loads Application's internal Image Format. /// </summary> /// <param name="file">File to open.</param> /// <returns>Loaded Image Instance.</returns> public static EditedImage LoadMyImage(FileInfo file) { EditedImage image = new EditedImage(); // Loading Document: XmlDocument document = new XmlDocument(); document.Load(file.FullName); // Getting Image Width and Height from Root Node: XmlNode root = document.GetElementsByTagName("MyImage")[0]; image.Width = int.Parse(root.Attributes["Width"].Value); image.Height = int.Parse(root.Attributes["Height"].Value); // Getting Layers: XmlNodeList layerNodes = document.GetElementsByTagName("Layer"); // Adding Layers in back Direction: for (int i = layerNodes.Count - 1; i >= 0; i--) { image.AddLayer(); // Loading Layer Image: byte[] imageBytes = Convert.FromBase64String(layerNodes[i].InnerText); using (MemoryStream input = new MemoryStream(imageBytes)) { BitmapImage bitmap = new BitmapImage(); bitmap.BeginInit(); bitmap.StreamSource = input; bitmap.EndInit(); image.CurrentLayer.Image = bitmap; } image.CurrentLayer.Name = layerNodes[i].Attributes["Name"].Value; image.CurrentLayer.Visible = bool.Parse(layerNodes[i].Attributes["Visible"].Value); } return(image); }
/* * private void All_Click(object sender, RoutedEventArgs e) * { * Button button = (Button)sender; * DoorItem door = button.DataContext as DoorItem; * * OpenDoor?.Invoke(sender, new OpenDoorEventArgs * { * ButtonName = "count", * Door = button.DataContext as DoorItem * }); * * e.Handled = true; * } */ void SetBackgroundImage() { // TODO: ShelfCfgDom 在从自助借还模式切换为智能书柜模式时会成为 null // 优化 if (this.Background != null) { return; } // shelf.xml 中 root 元素的 backImageFile 属性 string backImageFile = ShelfData.ShelfCfgDom?.DocumentElement?.GetAttribute("backImageFile"); if (string.IsNullOrEmpty(backImageFile)) { return; } string filename = System.IO.Path.Combine(WpfClientInfo.UserDir, backImageFile); try { BitmapImage bitmap = new BitmapImage(); bitmap.BeginInit(); bitmap.CacheOption = BitmapCacheOption.OnLoad; bitmap.UriSource = new Uri(filename, UriKind.Absolute); bitmap.EndInit(); var brush = new ImageBrush(bitmap); brush.Stretch = Stretch.Uniform; this.Background = brush; } catch (Exception ex) { // TODO: 用一个报错文字图片设定为背景? } }
public static void ImageLoadAfterSecond() { switch (StageManager.stageNum) { case 1: bmObject = new BitmapImage(new Uri("furniture.png", UriKind.Relative)); cbObject[0] = new CroppedBitmap(bmObject, new Int32Rect(0, 0, 32, 64)); //chair cbObject[1] = new CroppedBitmap(bmObject, new Int32Rect(32, 32, 64, 32)); //table cbObject[2] = new CroppedBitmap(bmObject, new Int32Rect(96, 32, 64, 32)); //huton bmScenery = new BitmapImage(new Uri("scenery_2.png", UriKind.Relative)); cbScenery = new CroppedBitmap(bmScenery, new Int32Rect(0, 0, 1024, 768)); bmNpc = new BitmapImage(new Uri("npc.png", UriKind.Relative)); cbNpc[0] = new CroppedBitmap(bmNpc, new Int32Rect(0, 0, 32, 64)); cbNpc[1] = new CroppedBitmap(bmNpc, new Int32Rect(32, 0, 32, 64)); break; case 2: bmScenery = new BitmapImage(new Uri("scenery_3.png", UriKind.Relative)); cbScenery = new CroppedBitmap(bmScenery, new Int32Rect(0, 0, 1024, 768)); bmNpc = new BitmapImage(new Uri("npc.png", UriKind.Relative)); cbNpc[0] = new CroppedBitmap(bmNpc, new Int32Rect(0, 64, 32, 64)); cbNpc[1] = new CroppedBitmap(bmNpc, new Int32Rect(32, 64, 32, 64)); bmObject = new BitmapImage(new Uri("object_3.png", UriKind.Relative)); cbObject[0] = new CroppedBitmap(bmObject, new Int32Rect(32, 0, 32, 32)); cbObject[1] = new CroppedBitmap(bmObject, new Int32Rect(64, 0, 64, 32)); cbObject[2] = new CroppedBitmap(bmObject, new Int32Rect(0, 32, 96, 64)); break; } }
private void miOpen_Click(object sender, RoutedEventArgs e) { OpenFileDialog openDialog = new OpenFileDialog { Title = "Open an image", Filter = "Image Files(*.BMP;*.JPG;*.GIF;*.PNG)|*.BMP;*.JPG;*.GIF;*.PNG|All files (*.*)|*.*" }; if (openDialog.ShowDialog() == true) { try { nameOfImage = openDialog.FileName; // initialize and fill the bitmap BitmapImage bitmapSource = new BitmapImage(); bitmapSource.BeginInit(); bitmapSource.UriSource = new Uri(nameOfImage); bitmapSource.EndInit(); bitmap = new WriteableBitmap(bitmapSource); this.image.Source = bitmap; // make the container fit the image ResizeImage(); // make the window fit the image ResizeWindow(); } catch { nameOfImage = null; MessageBox.Show("Error opening the file", "Error", MessageBoxButton.OK, MessageBoxImage.Error); } } }
void UpdateContent() { var text = Element.Text; var elementImage = Element.Image; // No image, just the text if (elementImage == null) { Control.Content = text; return; } var bmp = new BitmapImage(new Uri("/" + elementImage.File, UriKind.Relative)); var image = new WImage { Source = bmp, VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Center }; bmp.ImageOpened += (sender, args) => { image.Width = bmp.PixelWidth; image.Height = bmp.PixelHeight; Element.InvalidateMeasureInternal(InvalidationTrigger.RendererReady); }; // No text, just the image if (string.IsNullOrEmpty(text)) { Control.Content = image; return; } // Both image and text, so we need to build a container for them Control.Content = CreateContentContainer(Element.ContentLayout, image, text); }
public static BitmapImage GetDisplayPicture(string fileName) { if (fileName == null) { return(null); } var filename = fileName.Replace(":", ".").Replace(" ", ""); var displayPicture = new BitmapImage(); lock (Sync) { using (var isf = IsolatedStorageFile.GetUserStoreForApplication()) { var path = System.IO.Path.Combine("Images", filename + ".png"); if (!isf.FileExists(path)) { return(null); } using (var fs = isf.OpenFile(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { var data = new byte[fs.Length]; if (data.Length == 0) { return(null); } fs.Read(data, 0, data.Length); using (var ms = new MemoryStream(data)) { displayPicture.SetSource(ms); } } } } return(displayPicture); }
private void HellCanvas_Initialized(object sender, EventArgs e) { HellCanvas.Focusable = true; HellCanvas.Focus(); StoryBox.Focusable = false; BitmapImage bit = new BitmapImage(); bit.BeginInit(); bit.UriSource = new Uri("../../Object Model/MainCharacter.png", UriKind.Relative); bit.EndInit(); MainCharacter.Source = bit; bit = new BitmapImage(); bit.BeginInit(); bit.UriSource = new Uri("../../Object Model/SatanicCircle.png", UriKind.Relative); bit.EndInit(); SatanicCircle.Source = bit; make.MakeDoor(MainCharacter, HellCanvas, "", Door1); make.MakeDoor(MainCharacter, HellCanvas, "", Door2); make.MakeDoor(MainCharacter, HellCanvas, "", Door3); make.MakeDoor(MainCharacter, HellCanvas, "", Door4); make.MakeNPC(MainCharacter, HellCanvas, "../../Object Model/devil.png", Satan); make.MakeItem(MainCharacter, HellCanvas, "../../Object Model/Water.png", water); make.MakeItem(MainCharacter, HellCanvas, "../../Object Model/Ice.png", ice); move.ConnectCharacter_and_Canvas(MainCharacter, HellCanvas); BadStory.AddIntro("<LevelIntro>Narrator: Now all Xavier has to do is collect the ice and the water and talk to Satan to start his new-ish life."); BadStory.AddIntro("<CharacterIntro>Satan: I see you wish to be my new right hand man. Well your gonna have to work for it! Now give me my water and set up my fan. Maybe in a couple " + "thousands years I will consider you. Now LEAVE! Before I get annoyed."); }
async Task Initialize() { PivotSize = LemuriaPivot.Items.Count; // load a jpeg, be sure to have the Pictures Library capability in your manifest var folder = await Package.Current.InstalledLocation.GetFolderAsync(@"Assets"); var file = await folder.GetFileAsync("Background.jpg"); using (var data = await file.OpenAsync(FileAccessMode.Read)) { BitmapImage bitmapImage = new BitmapImage(); await bitmapImage.SetSourceAsync(data); LemuriaPivot.Background = new ImageBrush { ImageSource = bitmapImage, Stretch = Stretch.UniformToFill }; // Ensure image loaded await Task.Delay(500); } // Notifiers notifiers.PropertyChanged += Notifiers_PropertyChanged; // Forward ForwardButton.AddHandler(PointerPressedEvent, new PointerEventHandler(MoveForward_PointerPressed), true); ForwardButton.AddHandler(PointerReleasedEvent, new PointerEventHandler(MoveForward_PointerReleased), true); // Backward BackwardButton.AddHandler(PointerPressedEvent, new PointerEventHandler(MoveBackward_PointerPressed), true); BackwardButton.AddHandler(PointerReleasedEvent, new PointerEventHandler(MoveBackward_PointerReleased), true); // Left LeftButoon.AddHandler(PointerPressedEvent, new PointerEventHandler(TurnLeft_PointerPressed), true); LeftButoon.AddHandler(PointerReleasedEvent, new PointerEventHandler(TurnLeft_PointerReleased), true); // Right RightButton.AddHandler(PointerPressedEvent, new PointerEventHandler(TurnRight_PointerPressed), true); RightButton.AddHandler(PointerReleasedEvent, new PointerEventHandler(TurnRight_PointerReleased), true); SelectPage("connect"); }
public static BitmapImage ResizeImage(System.Drawing.Image image, int width, int height) { var destRect = new System.Drawing.Rectangle(0, 0, width, height); var destImage = new Bitmap(width, height); destImage.SetResolution(image.HorizontalResolution, image.VerticalResolution); using (var graphics = Graphics.FromImage(destImage)) { graphics.CompositingMode = CompositingMode.SourceCopy; graphics.CompositingQuality = CompositingQuality.HighQuality; graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; graphics.SmoothingMode = SmoothingMode.HighQuality; graphics.PixelOffsetMode = PixelOffsetMode.HighQuality; using (var wrapMode = new ImageAttributes()) { wrapMode.SetWrapMode(WrapMode.TileFlipXY); graphics.DrawImage(image, destRect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, wrapMode); } } using (var memory = new MemoryStream()) { destImage.Save(memory, ImageFormat.Png); memory.Position = 0; var bitmapImage = new BitmapImage(); bitmapImage.BeginInit(); bitmapImage.StreamSource = memory; bitmapImage.CacheOption = BitmapCacheOption.OnLoad; bitmapImage.EndInit(); bitmapImage.Freeze(); return(bitmapImage); } }
/// <summary> /// 下载图片进度 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void bitmapImage_DownloadProgress(object sender, DownloadProgressEventArgs e) { if (e.Progress == 100) { BitmapImage bitmapImage = sender as BitmapImage; int height = bitmapImage.PixelHeight; int width = bitmapImage.PixelWidth; //当下载的图片有效时 if (height > 0 && width > 0) { if (width > bitmapImage.PixelHeight) { CurImage.Width = (width < CurImage.MaxWidth) ? width : CurImage.MaxWidth; } else { CurImage.Height = (height < CurImage.MaxHeight) ? height : CurImage.MaxHeight; } //SetPositionInfo(height, width); LoadInfo.Visibility = System.Windows.Visibility.Collapsed; CurImageFadeIn.Begin(); } else //不存在或路径无效时 { //CurImage.Source = new BitmapImage(new Uri("/Images/NoPhoto.jpg", UriKind.RelativeOrAbsolute)); //CurImage.Width = 142; //CurImage.Height = 119; LoadInfo.Content = "图片信息无效!"; } } else { LoadInfo.Content = "正在加载数据" + e.Progress + "..."; } }
private void ProgramOnOnOptionsChanged() { if (!this.Dispatcher.CheckAccess()) { Dispatcher.Invoke(new Action(this.ProgramOnOnOptionsChanged)); return; } var issub = SubscriptionModule.Get().IsSubscribed ?? false; if (issub && !String.IsNullOrWhiteSpace(Prefs.WindowSkin)) { var bimage = new BitmapImage(new Uri(Prefs.WindowSkin)); var ib = new ImageBrush(bimage); if (Prefs.TileWindowSkin) { ib.Stretch = Stretch.None; ib.TileMode = TileMode.Tile; ib.ViewportUnits = BrushMappingMode.Absolute; ib.Viewport = new Rect(0, 0, bimage.PixelWidth, bimage.PixelHeight); } else { ib.Stretch = Stretch.Fill; } this.MainBorder.Background = ib; } else { var bimage = new BitmapImage(new Uri("pack://application:,,,/Resources/background.png")); var ib = new ImageBrush(bimage); ib.Stretch = Stretch.Fill; this.MainBorder.Background = ib; //this.MainBorder.SetResourceReference(Border.BackgroundProperty, "ControlBackgroundBrush"); } }
private static void DrawLargeSmallImage(JArray propertiesArray) { JToken largePreviewImage = propertiesArray.FirstOrDefault(x => string.Equals(x["name"].Value <string>(), "LargePreviewImage")); JToken smallPreviewImage = propertiesArray.FirstOrDefault(x => string.Equals(x["name"].Value <string>(), "SmallPreviewImage")); if (largePreviewImage != null || smallPreviewImage != null) { JToken assetPathName = largePreviewImage != null ? largePreviewImage["tag_data"]["asset_path_name"] : smallPreviewImage != null ? smallPreviewImage["tag_data"]["asset_path_name"] : null; if (assetPathName != null) { // CID_716_Athena_Commando_M_BlueFlames if (smallPreviewImage != null && assetPathName.Value <string>().Equals("/Game/UI/Foundation/Textures/Icons/Heroes/Athena/Soldier/T-Soldier-HID-716-Athena-Commando-M-BlueFlames-L.T-Soldier-HID-716-Athena-Commando-M-BlueFlames-L")) { assetPathName = smallPreviewImage["tag_data"]["asset_path_name"]; } string texturePath = FoldersUtility.FixFortnitePath(assetPathName.Value <string>()); using (Stream image = AssetsUtility.GetStreamImageFromPath(texturePath)) { if (image != null) { BitmapImage bmp = new BitmapImage(); bmp.BeginInit(); bmp.CacheOption = BitmapCacheOption.OnLoad; bmp.StreamSource = image; bmp.EndInit(); bmp.Freeze(); IconCreator.ICDrawingContext.DrawImage(bmp, new Rect(3, 3, 509, 509)); } } } } }
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value is Action <string, byte[]> action && parameter is string filter) { return(new TransientCommand(() => { Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog(); dlg.Filter = filter; if (dlg.ShowDialog() == true) { bool failed = false; try { var bytes = File.ReadAllBytes(dlg.FileName); BitmapImage biImg = new BitmapImage(); using MemoryStream ms = new MemoryStream(bytes); biImg.BeginInit(); biImg.StreamSource = ms; biImg.EndInit(); action(dlg.FileName, bytes); } catch (Exception e) { Log.Warning(e, $"Failed to open image file"); failed = true; } if (failed) { action(dlg.FileName, null); } } })); } return(null); }
private void WebClient_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e) { if (CoverPath != "" && CoverTemp != "") { File.Delete(CoverPath); File.Move(CoverTemp, CoverPath); } img_cover.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(() => { int numberOfRetries = 5; int delayOnRetry = 1000; for (int i = 1; i < numberOfRetries; i++) { try { BitmapImage image = new BitmapImage(); image.BeginInit(); image.CacheOption = BitmapCacheOption.OnLoad; image.CreateOptions = BitmapCreateOptions.IgnoreImageCache; image.UriSource = new Uri(CoverPath); image.EndInit(); img_cover.Source = image; break; } catch (Exception) when(i <= numberOfRetries) { Console.WriteLine(@"Try " + i + @" of " + numberOfRetries); Thread.Sleep(delayOnRetry); } } })); }
/// <summary> /// Creates a menuitem. /// </summary> /// <param name="iconSourcePath">The path to the icon to display next to the menuitem.</param> /// <param name="text">The text of the menu command.</param> /// <param name="command">The command object.</param> /// <param name="tag">An optional, user-defined tag to attach to the menuitem (default is null).</param> /// <param name="isEnabled">An optional variable indicating whether the menu item is enabled (default is true).</param> /// <param name="commandParameter">The command parameter, or null if the command does not take a parameter.</param> /// <returns>A new menuitem.</returns> public static MenuItem CreateMenuItem(string iconSourcePath, string text, ICommand command, object tag = null, bool isEnabled = true, object commandParameter = null) { // Create the bitmap for the icon var image = new BitmapImage(); image.BeginInit(); image.UriSource = new Uri(iconSourcePath ?? string.Empty, UriKind.RelativeOrAbsolute); image.EndInit(); // Create the icon var icon = new System.Windows.Controls.Image { Height = 16, Width = 16, Margin = new Thickness(4, 0, 0, 0), Source = image, Style = MenuItemIconStyle, }; var menuItemHeader = new TextBlock { Text = text, Style = MenuItemTextBlockStyle, }; // Create the menuitem return(new MenuItem { Height = 25, Icon = icon, Header = menuItemHeader, Command = command, CommandParameter = commandParameter, Tag = tag, IsEnabled = isEnabled, }); }
private void CreateButtonForGrid(ExecutionTask task, Grid grid, int gridRow, int gridColumn) { if (task != null && grid != null) { var button = new Button() { Content = task.Caption, Margin = new Thickness(10, 10, 10, 10), HorizontalAlignment = HorizontalAlignment.Stretch, VerticalAlignment = VerticalAlignment.Stretch, Tag = task.Id, ToolTip = task.GetToolTip() }; var fullImagePath = task.GetImageFullPath(); if (!string.IsNullOrEmpty(fullImagePath) && File.Exists(fullImagePath)) { var img = new BitmapImage(new Uri(fullImagePath, UriKind.RelativeOrAbsolute)); var image = new Image { Source = img, HorizontalAlignment = HorizontalAlignment.Stretch, VerticalAlignment = VerticalAlignment.Stretch, }; button.Content = image; } button.Click += btn_TaskClick; grid.Children.Add(button); Grid.SetRow(button, gridRow); Grid.SetColumn(button, gridColumn); } }
private async void btnChooseImage_Click(object sender, RoutedEventArgs e) { int decodePixelHeight = 200; int decodePixelWidth = 200; FileOpenPicker open = new FileOpenPicker(); open.SuggestedStartLocation = PickerLocationId.PicturesLibrary; open.ViewMode = PickerViewMode.Thumbnail; // Filter to include a sample subset of file types open.FileTypeFilter.Clear(); open.FileTypeFilter.Add(".bmp"); open.FileTypeFilter.Add(".png"); open.FileTypeFilter.Add(".jpeg"); open.FileTypeFilter.Add(".jpg"); // Open a stream for the selected file StorageFile file = await open.PickSingleFileAsync(); // Ensure a file was selected if (file != null) { // Ensure the stream is disposed once the image is loaded using (IRandomAccessStream fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read)) { // Set the image source to the selected bitmap BitmapImage bitmapImage = new BitmapImage(); bitmapImage.DecodePixelHeight = decodePixelHeight; bitmapImage.DecodePixelWidth = decodePixelWidth; await bitmapImage.SetSourceAsync(fileStream); imgPerson.Source = bitmapImage; } } }
private void execute <Object>(Object obj) { string st = obj as string; switch (st) { case "EditImage": { try { var path = F_File.browserFile("image | *.png;*.jpg;"); var bitmapImage = new BitmapImage(new Uri(path)); PICTURE_CUSTOMER = F_Image.BitmapImage2Bytes(bitmapImage); } catch (Exception e) { F_File.LogError(e); } } break; case "DeleteImage": { PICTURE_CUSTOMER = new byte[] { }; } break; case "Save": { T_Helper.customer.EditFromObject(getInput()); TableCustomersViewModel.Send(null);; } break; default: break; } }
/// <summary> /// Loads an image from the specified path. /// </summary> /// <param name="path">The path to the image file.</param> /// <returns>The pixels as an array.</returns> private static OxyColor[,] LoadImage(string path) { if (!File.Exists(path)) { return(null); } // TODO: use OxyPlot to decode var bitmapImage = new BitmapImage(); bitmapImage.BeginInit(); bitmapImage.UriSource = new Uri(path, UriKind.Relative); bitmapImage.EndInit(); // Assumes ARGB int size = bitmapImage.PixelHeight * bitmapImage.PixelWidth * 4; var pixels = new byte[size]; bitmapImage.CopyPixels(pixels, bitmapImage.PixelWidth * 4, 0); var r = new OxyColor[bitmapImage.PixelWidth, bitmapImage.PixelHeight]; var index = 0; for (int i = 0; i < bitmapImage.PixelHeight; i++) { for (int j = 0; j < bitmapImage.PixelWidth; j++) { byte red = pixels[index++]; byte green = pixels[index++]; byte blue = pixels[index++]; byte alpha = pixels[index++]; r[j, i] = OxyColor.FromArgb(alpha, red, green, blue); } } return(r); }
public MainPage() { InitializeComponent(); // Monitors state of audio playback so we can update the UI. DispatcherTimer dt = new DispatcherTimer(); dt.Interval = TimeSpan.FromMilliseconds(33); dt.Tick += new EventHandler(dt_Tick); dt.Start(); // Event handler for getting audio data when the buffer is full microphone.BufferReady += new EventHandler <EventArgs>(microphone_BufferReady); microphoneImage = new BitmapImage(new Uri("Images/microphone.png", UriKind.RelativeOrAbsolute)); speakerImage = new BitmapImage(new Uri("Images/speaker.png", UriKind.RelativeOrAbsolute)); darkVader = new BitmapImage(new Uri("Images/darkvader.png", UriKind.RelativeOrAbsolute)); lightVader = new BitmapImage(new Uri("Images/lightvader.png", UriKind.RelativeOrAbsolute)); darkMouse = new BitmapImage(new Uri("Images/darkmouse.png", UriKind.RelativeOrAbsolute)); lightMouse = new BitmapImage(new Uri("Images/lightmouse.png", UriKind.RelativeOrAbsolute)); mouth = new BitmapImage(new Uri("Images/mouth.png", UriKind.RelativeOrAbsolute)); Visibility v = (Visibility)Resources["PhoneLightThemeVisibility"]; if (v == System.Windows.Visibility.Visible) { // Light theme //vaderImage.Source = lightVader; //mouseImage.Source = lightMouse; } else { // Dark theme //vaderImage.Source = darkVader; //mouseImage.Source = darkMouse; } }
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { string path = value as string; if (String.IsNullOrEmpty(path)) return null; BitmapImage bitmap; if (path.StartsWith("isostore:")) { using (var storage = IsolatedStorageFile.GetUserStoreForApplication()) { using (var sourceFile = storage.OpenFile(path.Substring(9), FileMode.Open, FileAccess.Read)) { bitmap = new BitmapImage(); bitmap.SetSource(sourceFile); return bitmap; } } } bitmap = new BitmapImage(new Uri(path, UriKind.Relative)); return bitmap; }
// We could use this piece of code to also download the thumb // if we had WPF. But we don't. private void LoadThumbnail(Uri url) { try { WebClient wc = new WebClient(); byte[] bytes = wc.DownloadData(url); MemoryStream stream = new MemoryStream(bytes); BitmapImage image = new BitmapImage(); image.BeginInit(); image.StreamSource = stream; image.EndInit(); //set thumbnail Thumbnail = image; } catch { BitmapImage image = new BitmapImage(); image.BeginInit(); image.UriSource = new Uri("youtube_logo.png", UriKind.Relative); image.EndInit(); Thumbnail = image; } }
/// <summary> /// Gets a tile from a compact cache. /// </summary> /// <param name="level">The level.</param> /// <param name="row">The row.</param> /// <param name="col">The col.</param> /// <param name="onComplete">The on complete.</param> private void GetCompactTile(int level, int row, int col, Action<ImageSource> onComplete) { Action<byte[]> complete = delegate(byte[] tileData) { if (tileData == null) onComplete(null); else { BitmapImage bmi = new BitmapImage(); bmi.BeginInit(); MemoryStream ms = new MemoryStream(tileData); bmi.StreamSource = ms; bmi.EndInit(); onComplete(bmi); } }; System.Threading.ThreadPool.QueueUserWorkItem(delegate(object state) { Action<byte[]> callback = (Action<byte[]>)state; var tileData = CacheSource.GetTile(level, row, col, packetSize, TileCacheFilePath); Dispatcher.BeginInvoke((Action)delegate() { callback(tileData); }); }, complete); }