Search Results

Search found 121 results on 5 pages for 'bitmapimage'.

Page 2/5 | < Previous Page | 1 2 3 4 5  | Next Page >

  • MemoryStream and BitmapSource

    - by Vinjamuri
    I have a MemoryStream of 10K which was created from a bitmap of 2MB and compressed using JPEG. Since MemoryStream can’t directly be placed in System.Windows.Controls.Image for the GUI, I am using the following intermediate code to convert this back to BitmapImage and eventually System.Windows.Controls.Image. System.Windows.Controls.Image image = new System.Windows.Controls.Image(); BitmapImage imageSource = new BitmapImage(); s.SlideInformation.Thumbnail.Seek(0, SeekOrigin.Begin); imageSource.BeginInit(); imageSource.CacheOption = BitmapCacheOption.OnDemand; imageSource.CreateOptions = BitmapCreateOptions.DelayCreation; imageSource.StreamSource = s.SlideInformation.Thumbnail; imageSource.EndInit(); imageSource.Freeze(); image.Source = imageSource; ret = image.Source; My question is, when I store this in BitmapImage, the memory allocation is taking around 2MB. Is this expected? Is there any way to reduce the memory? I have around 300 thumbnails and this converstion takes around 600MB, which is very high. Appreciate your help!

    Read the article

  • Setting Image.Source doesn't update when loading from a resource.

    - by ChrisF
    I've got this definition in my XAML: <Image Name="AlbumArt" Source="/AlbumChooser2;component/Resources/help.png" /> The image is display OK on startup. In my code I'm looking for mp3's to play and I display the associated album art in this Image. Now if there's no associated image I want to display a "no image" image. So I've got one defined and I load it using: BitmapImage noImage = new BitmapImage( new Uri("/AlbumChooser2;component/Resources/no_image.png", UriKind.Relative)); I've got a helper class that finds the image if there is one (returning it as a BitmapImage), or returns null if there isn't one: if (findImage.Image != null) { this.AlbumArt.Source = findImage.Image; // This works } else { this.AlbumArt.Source = noImage; // This doesn't work } In the case where an image is found the source is updated and the album art gets displayed. In the case where an image isn't found I don't get anything displayed - just a blank. I don't think that it's the setting of AlbumArt.Source that's wrong, but the loading of the BitmapImage. If I use a different image it works, but if I recreate the image it doesn't work. What could be wrong with the image?

    Read the article

  • Using WPF class in a web application, problem with hosting permission

    - by tanathos
    I'm developing a DLL that uses WPF classes to make image manipulation. It works fine in my local environment, but when I try to use it in an hosted web site I retrieve this error: Request for the permission of type 'System.Security.Permissions.MediaPermission, WindowsBase, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' failed. exactly when I try to call the EndInit() of a BitmapImage object: BitmapImage originalImage = new BitmapImage(); originalImage.BeginInit(); originalImage.CacheOption = BitmapCacheOption.OnLoad; originalImage.UriSource = new Uri(physical_imagepath); originalImage.EndInit(); Any suggestion?

    Read the article

  • How to display and change an icon inside a python Tk Frame

    - by codingJoe
    I have a python Tkinter Frame that displays several fields. I want to also add an red/yellow/green icon that will display the status of an external device. The icon is loaded from a file called ICON_LED_RED.ico. How do I display the icon in my frame? How do I change the icon at runtime? for example replace BitmapImage('RED.ico') with BitmapImage('GREEN.ico') class Application(Frame): def init(self, master=None): Frame.__init__(self, master) self.pack() self.createWidgets() def createWidgets(self): # ...other frame code.. works just fine. self.OKBTN = Button(self) self.OKBTN["text"] = "OK" self.OKBTN["fg"] = "red" self.OKBTN["command"] = self.ok_btn_func self.OKBTN.pack({"side": "left"}) # when I add the following the frame window is not visible # The process is locked up such that I have to do a kill -9 self.statusFrame = Frame(self, bd=2, relief=RIDGE) Label(self.statusFrame, text='Status:').pack(side=LEFT, padx=5) self.statIcon = BitmapImage('data/ICON_LED_RED.ico') Label (self.statusFrame, image=self.statIcon ).grid() self.statusFrame.pack(expand=1, fill=X, pady=10, padx=5)

    Read the article

  • problem loading resource from class library

    - by mishal153
    I have a class library (mylibrary) which has a resource called "close.png". I used redGate reflector to confirm that the resource is actually present in the dll. Now i use mylibrary.dll in a project where i attempt to extract this "close.png" resource like this : BitmapImage crossImage = new BitmapImage(); crossImage.BeginInit(); crossImage.UriSource = new Uri(@"/mylibrary;component/Resources/close.png", UriKind.RelativeOrAbsolute); crossImage.EndInit(); This BitmapImage crossImage is then used like : Button closeButton = new Button() { Content = new System.Windows.Controls.Image() { Source = crossImage }, MaxWidth = 20, MaxHeight = 20 }; On doing this i get no exceptions being thrown but the button shows no image. Also, i do see some exception info if i investigate the button's 'content' in the debugger.

    Read the article

  • WPF databind in memory image to Image control

    - by Ready Cent
    I am using a DataGrid and trying to do the following Databinding <DataTemplate> <Grid> <Image> <Image.Source> <BitmapImage UriSource="{Binding Data.CustomImage}" CacheOption="OnLoad" /> </Image.Source> </Image> </Grid> </DataTemplate> CustomImage is of type BitmapImage. When I run I get the error: Initialization of 'System.Windows.Media.Imaging.BitmapImage' threw an exception. The thing is that these images are stored as resources in a different assembly so I can't just point to a location on disk

    Read the article

  • How to set uri for local image in silverlight app?

    - by KentZhou
    In SL class library MyLib, I have a image say my.png. Then I want to use it in code behind I tried following way: StreamResourceInfo resourceStream = Application.GetResourceStream(new Uri("/MyLib;component/my.png", UriKind.Relative)); BitmapImage image = new BitmapImage(); image.SetSource(resourceStream.Stream); this.MyIcon.Source = image; But it's not woking. I think it's the Uri not set correctly. Help please.

    Read the article

  • Windows phone app xaml error

    - by thewarri0r9
    i am developing an app for windows phone 8 and i stuck on this code which visual studio showing invalid xaml. But Code compiles and works well. Invalid xaml Code is : <DataTemplate x:Key="AddrBookItemTemplate"> <StackPanel Margin="0,0,0,2" Orientation="Horizontal"> <StackPanel Width="80" Orientation="Horizontal" Height="80"> <Ellipse Margin="0" Height="70" Width="70" HorizontalAlignment="Left" Stroke="{x:Null}"> <Ellipse.Fill> <ImageBrush Stretch="Fill" ImageSource="{Binding imageBytes, Converter={StaticResource BytesToImageConverter}}"/> </Ellipse.Fill> </Ellipse> </StackPanel> <StackPanel Height="80" Margin="0" Width="380" HorizontalAlignment="Left"> <TextBlock FontWeight="Bold" Text="{Binding FirstName}" FontFamily="Segoe WP Semibold" FontSize="30" VerticalAlignment="Top" Margin="5,0,0,0" HorizontalAlignment="Left" /> <TextBlock Text="{Binding Phone}" FontFamily="Segoe WP" FontSize="24" Foreground="{StaticResource PhoneTextBoxReadOnlyBrush}" Margin="5,0,0,-12" Width="320" HorizontalAlignment="Left" VerticalAlignment="Top"/> </StackPanel> </StackPanel> </DataTemplate> I am serializing image by converting it to byte, it works fine but if image is null it gives an error. code behind: if (e.Results != null) { List<AddressBook> source = new List<AddressBook>(); foreach (var result in e.Results) { if (result.PhoneNumbers.FirstOrDefault() != null && result.GetPicture()!=null) { BitmapImage bmp = new BitmapImage(); BitmapImage nullbmp = new BitmapImage(); if (result.GetPicture() == null) { bmp.UriSource = new Uri(@"/Images/ci2.png", UriKind.RelativeOrAbsolute); } else { bmp.SetSource(result.GetPicture()); } listobj.Add(new AddressBook() { FirstName = result.DisplayName != null ? result.DisplayName : "", imageBytes = AddressBook.imageConvert(bmp), EmailAddress = "", LastName = "", Phone = result.PhoneNumbers.FirstOrDefault() != null ? result.PhoneNumbers.FirstOrDefault().PhoneNumber : "", }); } } Above code show an error "object reference not set to instance of an object". I want to show the default image (or color) in ellipse when image is null.What should I do?

    Read the article

  • Using Image Source with big images in WPF

    - by xyzzer
    I am working on an application that allows users to manipulate multiple images by using ItemsControl. I started running some tests and found that the app has problems displaying some big images - ie. it did not work with the high resolution (21600x10800), 20MB images from http://earthobservatory.nasa.gov/Features/BlueMarble/BlueMarble_monthlies.php, though it displays the 6200x6200, 60MB Hubble telescope image from http://zebu.uoregon.edu/hudf/hudf.jpg just fine. The original solution just specified an Image control with a Source property pointing at a file on a disk (through a binding). With the Blue Marble file - the image would just not show up. Now this could be just a bug hidden somewhere deep in the funky MVVM + XAML implementation - the visual tree displayed by Snoop goes like: Window/Border/AdornerDecorator/ContentPresenter/Grid/Canvas/UserControl/Border/ContentPresenter/Grid/Grid/Grid/Grid/Border/Grid/ContentPresenter/UserControl/UserControl/Border/ContentPresenter/Grid/Grid/Grid/Grid/Viewbox/ContainerVisual/UserControl/Border/ContentPresenter/Grid/Grid/ItemsControl/Border/ItemsPresenter/Canvas/ContentPresenter/Grid/Grid/ContentPresenter/Image... Now debug this! WPF can be crazy like that... Anyway, it turned out that if I create a simple WPF application - the images load just fine. I tried finding out the root cause, but I don't want to spend weeks on it. I figured the right thing to do might be to use a converter to scale the images down - this is what I have done: ImagePath = @"F:\Astronomical\world.200402.3x21600x10800.jpg"; TargetWidth = 2800; TargetHeight = 1866; and <Image> <Image.Source> <MultiBinding Converter="{StaticResource imageResizingConverter}"> <MultiBinding.Bindings> <Binding Path="ImagePath"/> <Binding RelativeSource="{RelativeSource Self}" /> <Binding Path="TargetWidth"/> <Binding Path="TargetHeight"/> </MultiBinding.Bindings> </MultiBinding> </Image.Source> </Image> and public class ImageResizingConverter : MarkupExtension, IMultiValueConverter { public Image TargetImage { get; set; } public string SourcePath { get; set; } public int DecodeWidth { get; set; } public int DecodeHeight { get; set; } public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) { this.SourcePath = values[0].ToString(); this.TargetImage = (Image)values[1]; this.DecodeWidth = (int)values[2]; this.DecodeHeight = (int)values[3]; return DecodeImage(); } private BitmapImage DecodeImage() { BitmapImage bi = new BitmapImage(); bi.BeginInit(); bi.DecodePixelWidth = (int)DecodeWidth; bi.DecodePixelHeight = (int)DecodeHeight; bi.UriSource = new Uri(SourcePath); bi.EndInit(); return bi; } public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) { throw new Exception("The method or operation is not implemented."); } public override object ProvideValue(IServiceProvider serviceProvider) { return this; } } Now this works fine, except for one "little" problem. When you just specify a file path in Image.Source - the application actually uses less memory and works faster than if you use BitmapImage.DecodePixelWidth. Plus with Image.Source if you have multiple Image controls that point to the same image - they only use as much memory as if only one image was loaded. With the BitmapImage.DecodePixelWidth solution - each additional Image control uses more memory and each of them uses more than when just specifying Image.Source. Perhaps WPF somehow caches these images in compressed form while if you specify the decoded dimensions - it feels like you get an uncompressed image in memory, plus it takes 6 times the time (perhaps without it the scaling is done on the GPU?), plus it feels like the original high resolution image also gets loaded and takes up space. If I just scale the image down, save it to a temporary file and then use Image.Source to point at the file - it will probably work, but it will be pretty slow and it will require handling cleanup of the temporary file. If I could detect an image that does not get loaded properly - maybe I could only scale it down if I need to, but Image.ImageFailed never gets triggered. Maybe it has something to do with the video memory and this app just using more of it with the deep visual tree, opacity masks etc. Actual question: How can I load big images as quickly as Image.Source option does it, without using more memory for additional copies and additional memory for the scaled down image if I only need them at a certain resolution lower than original? Also, I don't want to keep them in memory if no Image control is using them anymore.

    Read the article

  • Load Images in WPF application

    - by LLS
    I am not familiar with WPF, and I just feel quite confusing. I am trying to create a little computer game, and there are elements I want to display dynamically. I use Image class and add the images to a canvas. But I'm not sure whether it's a good practice. I feel that adding controls to canvas seem to be a little wired. And I'm a little concerned about the performance, because I may need many images. The real problem is, I can't load the images from the image files. I see an example in a text book like this (XMAL): <Image Panel.ZIndex="0" Margin="0,0,0,0" Name ="image1"> <Image.Source> <BitmapImage UriSource="Bell.gif" /> </Image.Source> </Image> Where Bell.gif is added into the project. And I tried to copy this in code to create an image. new Image { Source = new BitmapImage(new Uri("Blockade.bmp"))} But I got invalid Uri exception. After some search in the Internet, I found that loading resources dynamically seems to be difficult. Can I load the files added to the project dynamically? If I use absolute path then it's OK. But I can't expect every computer will put the files in the same location. Can I use relative path? I tried new Image { Source = new BitmapImage(new Uri(@"Pictures\Blank Land.bmp", UriKind.Relative)) } But it doesn't work. (The image is blank) Thanks.

    Read the article

  • WP7 BarcodeManager - Invalid cross-thread access

    - by rpf
    I'm trying to use Windows Phone 7 Silverlight ZXing Barcode Scanning Library but I'm having some problems. I'm using a background worker to check the image, but when I do this: WP7BarcodeManager.ScanBarcode(this.Image, BarcodeResults_Finished); The code throws an exception: Invalid cross-thread access. Here is my code... void photoChooserTask_Completed(object sender, PhotoResult e) { if (e.TaskResult == TaskResult.OK) { ShowImage(); System.Windows.Media.Imaging.BitmapImage bmp = new System.Windows.Media.Imaging.BitmapImage(); bmp.SetSource(e.ChosenPhoto); imgCapture.Source = bmp; this.Image = new BitmapImage(); this.Image.SetSource(e.ChosenPhoto); progressBar.Visibility = System.Windows.Visibility.Visible; txtStatus.Visibility = System.Windows.Visibility.Collapsed; worker.RunWorkerAsync(); } else ShowMain(); } void worker_DoWork(object sender, DoWorkEventArgs e) { try { Thread.Sleep(2000); WP7BarcodeManager.ScanMode = com.google.zxing.BarcodeFormat.UPC_EAN; WP7BarcodeManager.ScanBarcode(this.Image, BarcodeResults_Finished); } catch (Exception ex) { Debug.WriteLine("Error processing image.", ex); } } How can I solve this?

    Read the article

  • How do I tile and overlay images in WPF?

    - by imnlfn
    I'm very new to WPF and trying to port an application from VB6 to C# and XAML. What I need to do now is create one big image out of a number of small ones, arranged like a series of "tiles." Some of these smaller ones will have overlays superimposed on them. In VB6, accomplishing both the tiling and overlaying would simply be a matter of using the PaintPicture method with the PictureBox control. This is my attempt at the tiling and overlaying in one step (though really the overlaying could occur beforehand): ImageDrawing Drawing1 = new ImageDrawing(new BitmapImage(new Uri(@"c:\one.bmp", UriKind.Absolute)), new Rect(0, 0, 40, 130)); ImageDrawing Drawing2 = new ImageDrawing(new BitmapImage(new Uri(@"c:\two.bmp", UriKind.Absolute)), new Rect(40, 0, 45, 130)); ImageDrawing Drawing3 = new ImageDrawing(new BitmapImage(new Uri(@"c:\overlay.bmp", UriKind.Absolute)), new Rect(40, 0, 45, 130)); DrawingGroup myDrawingGroup = new DrawingGroup(); myDrawingGroup.Children.Add(Drawing1); myDrawingGroup.Children.Add(Drawing2); myDrawingGroup.Children.Add(Drawing3); myImage.Source = new DrawingImage(myDrawingGroup); The tiling works fine, but the overlay is a no-go. I was wondering if someone could point me towards a means of accomplishing the overlays and someone could indicate whether this is the best way to do the tiling. Thanks!!

    Read the article

  • I created a custom (WPF) DataGridBoundColumn and get unexpected behaviour, what am I missing?

    - by aspic
    Hi, I am using a DataGrid (from Microsoft.Windows.Controls.DataGrid) to display items on and on this DataGrid I use a custom Column which extends DataGridBoundColumn. I have bound an ObservableCollection to the ItemSource of the DataGrid. Conversation is one of my own custom datatypes which a (among other things) has a boolean called active. I bound this boolean to the DataGrid as follows: DataGridActiveImageColumn test = new DataGridActiveImageColumn(); test.Header = "Active"; Binding binding1 = new Binding("Active"); test.Binding = binding1; ConversationsDataGrid.Columns.Add(test); My custom DataGridBoundColumn DataGridActiveImageColumn overrides the GenerateElement method to let it return an Image depending on whether the conversation it is called for is active or not. The code for this is: namespace Microsoft.Windows.Controls { class DataGridActiveImageColumn : DataGridBoundColumn { protected override FrameworkElement GenerateElement(DataGridCell cell, object dataItem) { // Create Image Element Image myImage = new Image(); myImage.Width = 10; bool active=false; if (dataItem is Conversation) { Conversation c = (Conversation)dataItem; active = c.Active; } BitmapImage myBitmapImage = new BitmapImage(); // BitmapImage.UriSource must be in a BeginInit/EndInit block myBitmapImage.BeginInit(); if (active) { myBitmapImage.UriSource = new Uri(@"images\active.png", UriKind.Relative); } else { myBitmapImage.UriSource = new Uri(@"images\inactive.png", UriKind.Relative); } // To save significant application memory, set the DecodePixelWidth or // DecodePixelHeight of the BitmapImage value of the image source to the desired // height or width of the rendered image. If you don't do this, the application will // cache the image as though it were rendered as its normal size rather then just // the size that is displayed. // Note: In order to preserve aspect ratio, set DecodePixelWidth // or DecodePixelHeight but not both. myBitmapImage.DecodePixelWidth = 10; myBitmapImage.EndInit(); myImage.Source = myBitmapImage; return myImage; } protected override FrameworkElement GenerateEditingElement(DataGridCell cell, object dataItem) { throw new NotImplementedException(); } } } All this works as expected, and when during the running of the program the active boolean of conversations changes, this is automatically updated in the DataGrid. However: When there are more entries on the DataGrid then fit at any one time (and vertical scrollbars are added) the behavior with respect to the column for all the conversations is strange. The conversations that are initially loaded are correct, but when I use the scrollbar of the DataGrid conversations that enter the view seems to have a random status (although more inactive than active ones, which corresponds to the actual ratio). When I scroll back up, the active images of the Conversations initially shown (before scrolling) are not correct anymore as well. When I replace my custom DataGridBoundColumn class with (for instance) DataGridCheckBoxColumn it works as intended so my extension of the DataGridBoundColumn class must be incomplete. Personally I think it has something to do with the following: From the MSDN page on the GenerateElement method (http://msdn.microsoft.com/en-us/library/system.windows.controls.datagridcolumn.generateelement%28VS.95%29.aspx): Return Value Type: System.Windows. FrameworkElement A new, read-only element that is bound to the column's Binding property value. I do return a new element (the image) but it is not bound to anything. I am not quite sure what I should do. Should I bind the Image to something? To what exactly? And why? (I have been experimenting, but was unsuccessful thus far, hence this post) Thanks in advance.

    Read the article

  • Running multiple image manipulations in parallel causing OutOfMemory exception

    - by Tom
    I am working on a site where I need to be able to split and image around 4000x6000 into 4 parts (amongst many other tasks) and I need this to be as quick as possible for multiple users. My current code for doing this is var bitmaps = new RenderTargetBitmap[elements.Length]; using (var stream = blobService.Stream(key)) { BitmapImage bi = new BitmapImage(); bi.BeginInit(); bi.StreamSource = stream; bi.EndInit(); for (var i = 0; i < elements.Length; i++) { var element = elements[i]; TransformGroup transformGroup = new TransformGroup(); TranslateTransform translateTransform = new TranslateTransform(); translateTransform.X = -element.Left; translateTransform.Y = -element.Top; transformGroup.Children.Add(translateTransform); DrawingVisual vis = new DrawingVisual(); DrawingContext cont = vis.RenderOpen(); cont.PushTransform(transformGroup); cont.DrawImage(bi, new Rect(new Size(bi.PixelWidth, bi.PixelHeight))); cont.Close(); RenderTargetBitmap rtb = new RenderTargetBitmap(element.Width, element.Height, 96d, 96d, PixelFormats.Default); rtb.Render(vis); bitmaps[i] = rtb; } } for (var i = 0; i < bitmaps.Length; i++) { using (MemoryStream ms = new MemoryStream()) { PngBitmapEncoder encoder = new PngBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(bitmaps[i])); encoder.Save(ms); var regionKey = WebPath.Variant(key, elements[i].Id); saveBlobService.Save("image/png", regionKey, ms); } } I am running multiple threads which take jobs off a queue. I am finding that if this part of code is hit by 4 threads at once I get an OutOfMemory exception. I can stop this happening by wrapping all the code above in a lock(obj) but this isn't ideal. I have tried wrapping just the first using block (where the file is read from disk and split) but I still get the out of memory exceptions (this part of the code executes quite quickly). I this normal considering the amount of memory this should be taking up? Are there any optimisations I could make? Can I increase the memory available? UPDATE: My new code as per Moozhe's help public static void GenerateRegions(this IBlobService blobService, string key, Element[] elements) { using (var stream = blobService.Stream(key)) { foreach (var element in elements) { stream.Position = 0; BitmapImage bi = new BitmapImage(); bi.BeginInit(); bi.SourceRect = new Int32Rect(element.Left, element.Top, element.Width, element.Height); bi.StreamSource = stream; bi.EndInit(); DrawingVisual vis = new DrawingVisual(); DrawingContext cont = vis.RenderOpen(); cont.DrawImage(bi, new Rect(new Size(element.Width, element.Height))); cont.Close(); RenderTargetBitmap rtb = new RenderTargetBitmap(element.Width, element.Height, 96d, 96d, PixelFormats.Default); rtb.Render(vis); using (MemoryStream ms = new MemoryStream()) { PngBitmapEncoder encoder = new PngBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(rtb)); encoder.Save(ms); var regionKey = WebPath.Variant(key, element.Id); blobService.Save("image/png", regionKey, ms); } } } }

    Read the article

  • How do I catch this WPF Bitmap loading exception?

    - by mmr
    I'm developing an application that loads bitmaps off of the web using .NET 3.5 sp1 and C#. The loading code looks like: try { CurrentImage = pics[unChosenPics[index]]; bi = new BitmapImage(CurrentImage.URI); // BitmapImage.UriSource must be in a BeginInit/EndInit block. bi.DownloadCompleted += new EventHandler(bi_DownloadCompleted); AssessmentImage.Source = bi; } catch { System.Console.WriteLine("Something broke during the read!"); } and the code to load on bi_DownloadCompleted is: void bi_DownloadCompleted(object sender, EventArgs e) { try { double dpi = 96; int width = bi.PixelWidth; int height = bi.PixelHeight; int stride = width * 4; // 4 bytes per pixel byte[] pixelData = new byte[stride * height]; bi.CopyPixels(pixelData, stride, 0); BitmapSource bmpSource = BitmapSource.Create(width, height, dpi, dpi, PixelFormats.Bgra32, null, pixelData, stride); AssessmentImage.Source = bmpSource; Loading.Visibility = Visibility.Hidden; AssessmentImage.Visibility = Visibility.Visible; } catch { System.Console.WriteLine("Exception when viewing bitmap."); } } Every so often, an image comes along that breaks the reader. I guess that's to be expected. However, rather than being caught by either of those try/catch blocks, the exception is apparently getting thrown outside of where I can handle it. I could handle it using global WPF exceptions, like this SO question. However, that will seriously mess up the control flow of my program, and I'd like to avoid that if at all possible. I have to do the double source assignment because it appears that many images are lacking in width/height parameters in the places where the microsoft bitmap loader expects them to be. So, the first assignment appears to force the download, and the second assignment gets the dpi/image dimensions happen properly. What can I do to catch and handle this exception? Stack trace: at MS.Internal.HRESULT.Check(Int32 hr) at System.Windows.Media.Imaging.BitmapFrameDecode.get_ColorContexts() at System.Windows.Media.Imaging.BitmapImage.FinalizeCreation() at System.Windows.Media.Imaging.BitmapImage.OnDownloadCompleted(Object sender, EventArgs e) at System.Windows.Media.UniqueEventHelper.InvokeEvents(Object sender, EventArgs args) at System.Windows.Media.Imaging.LateBoundBitmapDecoder.DownloadCallback(Object arg) at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Boolean isSingleParameter) at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler) at System.Windows.Threading.DispatcherOperation.InvokeImpl() at System.Threading.ExecutionContext.runTryCode(Object userData) at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Windows.Threading.DispatcherOperation.Invoke() at System.Windows.Threading.Dispatcher.ProcessQueue() at System.Windows.Threading.Dispatcher.WndProcHook(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled) at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled) at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o) at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Boolean isSingleParameter) at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler) at System.Windows.Threading.Dispatcher.InvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Boolean isSingleParameter) at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam) at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg) at System.Windows.Threading.Dispatcher.TranslateAndDispatchMessage(MSG& msg) at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame) at System.Windows.Application.RunInternal(Window window) at LensComparison.App.Main() in C:\Users\Mark64\Documents\Visual Studio 2008\Projects\LensComparison\LensComparison\obj\Release\App.g.cs:line 48 at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args) at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading.ThreadHelper.ThreadStart()

    Read the article

  • How to Clear an image control in WPF (C#)

    - by antongladchenko
    I have an image control with a source image located in my c drive. I get a message that the image is being used by another process whenever I try to delete the original image to change it with another one dynamically. How do I release the image from the image control to be able to delete it. I tried this variants: string path = ((BitmapImage)img.Source).UriSource.LocalPath; img.SetValue(System.Windows.Controls.Image.SourceProperty, null); File.Delete(path); And: string path = ((BitmapImage)img.Source).UriSource.LocalPath; img.Source = null; File.Delete(path) But it's not work...

    Read the article

  • Adding image to RichTextBox programatically does not show in Xaml property

    - by rotary_engine
    Trying to add an image to a RichTextBox progamatically from a Stream. The image displays in the text box, however when reading the Xaml property there is no markup for the image. private void richTextBox3_Drop(object sender, DragEventArgs e) { if (e.Data.GetDataPresent(DataFormats.FileDrop)) { FileInfo[] files = (FileInfo[])e.Data.GetData(DataFormats.FileDrop); using (Stream s = files[0].OpenRead()) { InlineUIContainer container = new InlineUIContainer(); BitmapImage bmp = new BitmapImage(); bmp.SetSource(s); Image img = new Image(); img.SetValue(Image.SourceProperty, bmp); container.Child = img; richTextBox3.Selection.Insert(container); } } } private void Button_Click_1(object sender, RoutedEventArgs e) { // this doesn't have the markup from the inserted image System.Windows.MessageBox.Show(richTextBox3.Xaml); } What is the correct way to insert an image into the RichTextBox at runtime so that it can be persisted to a data store? In the Xaml property.

    Read the article

  • WPF : how can i use a picture while i'm showing it?

    - by Roy Gavrielov
    hello, i'm trying to do so but the program throws this exception : An unhandled exception of type 'System.IO.IOException' occurred in mscorlib.dll Additional information: The process cannot access the file 'C:\Users\Roy\documents\visual studio 2010\Projects\Assignment3\Assignment3\bin\Debug\Images\Chrysanthemum.jpg' because it is being used by another process. is there a way to use it while it's open? code : if (imgAddMessage.Source != null) { BitmapImage src = (BitmapImage)imgAddMessage.Source; if (!Directory.Exists("Images")) { Directory.CreateDirectory("Images"); } FileStream stream = new FileStream("Images/" + imageName, FileMode.Create, FileAccess.ReadWrite); JpegBitmapEncoder encoder = new JpegBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(src)); encoder.Save(stream); stream.Close(); } thanks.

    Read the article

  • WPF, Image MouseDown Event

    - by PrimeTSS
    I have an control with a mouse down event where Id like to chnage the Image when the image is clicked. But I cant seem to alter ANY of the images properties in the event. Event private void Image_MouseDown(object sender, MouseButtonEventArgs e) { BitmapImage bitImg = new BitmapImage(); bitImg.BeginInit(); bitImg.UriSource = new Uri("./Resource/Images/Bar1.png", UriKind.Relative); bitImg.EndInit(); ((Image)sender).Source = null; ((Image)sender).Width = 100; ((Image)sender).Visibility = Visibility.Hidden; } The event does fire, and even the .Visibility property does not alter the image and make it hidden. What am I doing wrong?

    Read the article

  • how to flip Image in wpf

    - by shashank
    Hello! I recently learned how to rotate a BitmapImage using the 'TransformedBitmap' and 'RotateTransformed' classes. Now I am able to perform clockwise rotations on my images. But how do I FLIP an image? I can't find the class(es) to perform horizontal and vertical flips of a BitmapImage. Please help me figure out how to do it. For instance, if my image was a drawing that looked like a 'd', then a vertical flip would result in something like a 'q', and a horizontal flip would result in something lika a 'b'. I hope this is clear enough. Thanks in advance! Best regards, shashank

    Read the article

  • How can I overlay one image onto another?

    - by Edward Tanguay
    I would like to display an image composed of two images. I want image rectangle.png to show with image sticker.png on top of it with its left-hand corner at pixel 10, 10. Here is as far as I got, but how do I combine the images? Image image = new Image(); image.Source = new BitmapImage(new Uri(@"c:\test\rectangle.png")); image.Stretch = Stretch.None; image.HorizontalAlignment = HorizontalAlignment.Left; Image imageSticker = new Image(); imageSticker.Source = new BitmapImage(new Uri(@"c:\test\sticker.png")); image.OverlayImage(imageSticker, 10, 10); //how to do this? TheContent.Content = image;

    Read the article

  • Bogus WPF / XAML errors in Visual Studio 2010

    - by epalm
    There are bogus errors hanging around, but at runtime everything works. Right now, I'm getting Cannot locate resource 'img/icons/silk/arrow_refresh.png'. I've got a simple UserControl called ImageButton (doesn't everyone?): <UserControl x:Class="WinDispatchClientWpf.src.controls.ImageButton" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" mc:Ignorable="d"> <Button Name="btnButton" Click="btnButton_Click"> <StackPanel Orientation="Horizontal"> <Image Name="btnImage" Stretch="None" /> <TextBlock Name="btnText" /> </StackPanel> </Button> </UserControl> Which does what you'd expect: [ContentProperty("Text")] public partial class ImageButton : UserControl { public String Image { set { btnImage.Source = GuiUtil.CreateBitmapImage(value); } } public String Text { set { btnText.Text = value; } } public double Gap { set { btnImage.Margin = new Thickness(0, 0, value, 0); } } public bool ToolBarStyle { set { if (value) { btnButton.Style = (Style)FindResource(ToolBar.ButtonStyleKey); } } } public bool IsCancel { set { btnButton.IsCancel = value; } } public bool IsDefault { set { btnButton.IsDefault = value; } } public event RoutedEventHandler Click; public ImageButton() { InitializeComponent(); } private void btnButton_Click(object sender, RoutedEventArgs e) { if (Click != null) { Click(sender, e); } } } Where CreateBitmapImage is the following: public static BitmapImage CreateBitmapImage(string imagePath) { BitmapImage icon = new BitmapImage(); icon.BeginInit(); icon.UriSource = new Uri(String.Format("pack://application:,,,/{0}", imagePath)); icon.EndInit(); return icon; } I can't see the design view of any xaml file that uses an ImageButton like such: <Window foo="bar" xmlns:wpfControl="clr-namespace:MyProj.src.controls"> <Grid> <wpfControl:ImageButton ToolBarStyle="True" Gap="3" Click="btnRefresh_Click" Text="Refresh" Image="img/icons/silk/arrow_refresh.png" /> </Grid> </Window> Why is VS complaining?

    Read the article

  • Call HttpWebRequest in another thread as UI with Task class - avoid to dispose object created in Task scope

    - by John
    I would like call HttpWebRequest on another thread as UI, because I must make 200 request or server and downloaded image. My scenation is that I make a request on server, create image and return image. This I make in another thread. I use Task class, but it call automaticaly Dispose method on all object created in task scope. So I return null object from this method. public BitmapImage CreateAvatar(Uri imageUri, int sex) { if (imageUri == null) return CreateDefaultAvatar(sex); BitmapImage image = null; new Task(() => { var request = WebRequest.Create(imageUri); var response = request.GetResponse(); using (var stream = response.GetResponseStream()) { Byte[] buffer = new Byte[response.ContentLength]; int offset = 0, actuallyRead = 0; do { actuallyRead = stream.Read(buffer, offset, buffer.Length - offset); offset += actuallyRead; } while (actuallyRead > 0); image = new BitmapImage { CreateOptions = BitmapCreateOptions.None, CacheOption = BitmapCacheOption.OnLoad }; image.BeginInit(); image.StreamSource = new MemoryStream(buffer); image.EndInit(); image.Freeze(); } }).Start(); return image; } How avoid it? Thank Mr. Jon Skeet try this: private Stream GetImageStream(Uri imageUri) { Byte[] buffer = null; //new Task(() => //{ var request = WebRequest.Create(imageUri); var response = request.GetResponse(); using (var stream = response.GetResponseStream()) { buffer= new Byte[response.ContentLength]; int offset = 0, actuallyRead = 0; do { actuallyRead = stream.Read(buffer, offset, buffer.Length - offset); offset += actuallyRead; } while (actuallyRead > 0); } //}).Start(); return new MemoryStream(buffer); } It return object which is null a than try this: private Stream GetImageStream(Uri imageUri) { Byte[] buffer = null; new Task(() => { var request = WebRequest.Create(imageUri); var response = request.GetResponse(); using (var stream = response.GetResponseStream()) { buffer= new Byte[response.ContentLength]; int offset = 0, actuallyRead = 0; do { actuallyRead = stream.Read(buffer, offset, buffer.Length - offset); offset += actuallyRead; } while (actuallyRead > 0); } }).Start(); return new MemoryStream(buffer); } Method above return null

    Read the article

  • How to save an image in it's original format?

    - by Patrick Klug
    I am trying to figure out how I can get the original format of an image so that I can store it with the same encoding. It seems that the only way to save an Image is by using a BitmapEncoder but I don't know how I can get the correct format from the image. Example: Clipboard.GetImage() returns a InteropBitmap which doesn't seem to contain any information about the original format. I also tried using an Extension method: public static void Save(this BitmapImage image, System.IO.Stream stream) { var decoder = BitmapDecoder.Create(image.StreamSource, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default); var encoder = BitmapEncoder.Create(decoder.CodecInfo.ContainerFormat); foreach (var frame in decoder.Frames) { encoder.Frames.Add(BitmapFrame.Create(decoder.Frames[0])); } encoder.Save(stream); } but the problem is that a) the ImageSource is not always a BitmapImage (Clipboard.GetImage()) for example and b) the image.StreamSource can be null in some cases (seems to be when the image is loaded via a relative Uri)

    Read the article

< Previous Page | 1 2 3 4 5  | Next Page >