Search Results

Search found 22 results on 1 pages for 'bitmapframe'.

Page 1/1 | 1 

  • BitmapFrame in another thread

    - by Lasse Lindström
    Hi I am using a WPF BackgroundWorker to create thumbnails. My worker function looks like: private void work(object sender, DoWorkEventArgs e) { try { var paths = e.Argument as string[]; var boxList = new List(); foreach (string path in paths) { if (!string.IsNullOrEmpty(path)) { FileInfo info = new FileInfo(path); if (info.Exists && info.Length 0) { BitmapImage bi = new BitmapImage(); bi.BeginInit(); bi.DecodePixelWidth = 200; bi.CacheOption = BitmapCacheOption.OnLoad; bi.UriSource = new Uri(info.FullName); bi.EndInit(); var item = new BoxItem(); item.FilePath = path; MemoryStream ms = new MemoryStream(); PngBitmapEncoder encoder = new PngBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(bi)); encoder.Save(ms); item.ThumbNail = ms.ToArray(); ms.Close(); boxList.Add(item); } } } e.Result = boxList; } catch (Exception ex) { //nerver comes here } } When this fuction is finnished and before the BackgroundWorker "Completed" function is started, I can see on the output window on Vs2008, that a exception is generated. It looks like: A first chance exception of type 'System.NotSupportedException' occurred in PresentationCore.dll The number of exceptions generates equals the number of thumbnails to be generated. Using "trial and error" I have isolated the problem to: BitmapFrame.Create(bi) Removing that line (makes my function useless) also removes the exception. I have not found any explanation to this,,, or a better method to create thumbnails i a background thread. Can anyone help me? //lasse

    Read the article

  • Convert WPF BitmapSource to Icon for window

    - by simmotech
    I have a 16x16 .png file which I have loaded as an ImageSource (BitmapSource) and it is working fine when I use it on an Image in a tabcontrol header. I now want to use that same image in a floating window (inherited from the WPF Window class) when the user drags the document tab. (This is AvalonDock which I have tweaked to allow images in the tab header) After many searches on the web, I understand that Window.Icon requires a BitmapFrame but all the sample code seems to assume that a .ico file is available which it isn't in my case. I have tried the following code (plus variants including cloning, freezing etc): var image = (Image) content.Icon; var bitmapSource = (BitmapSource) image.Source; Icon = BitmapFrame.Create(bitmapSource); but when the Show() method is called, an exception is thrown: "Exception of type 'System.ExecutionEngineException' was thrown." How can a I create a compatible bitmap on the fly to allow the Window to display the icon?

    Read the article

  • Why is my image being displayed larger?

    - by bsh152s
    I'm trying to display an image on a splash screen and it's being stretched upon display. The image I'm trying to display is a simple bmp file. Any ideas why? In SplashWindow.xaml: <Window ... SizeToContent="WidthAndHeight"> <Grid> ... <Image Grid.Row="0" Source="{Binding SplashImage}"></Image> </Grid> </Window> In SplashViewModel.cs public ImageSource SplashImage { get { return ImageUtilities.GetImageSource(_splashImageFilenameString); } } From ImageUtilities.cs public static ImageSource GetImageSource(string imageFilename) { BitmapFrame bitmapFrame = null; if(!string.IsNullOrEmpty(imageFilename)) { if(File.Exists(imageFilename)) { bitmapFrame = BitmapFrame.Create(new Uri(imageFilename)); } else { Debug.Assert(false, "File " + imageFilename + " does not exist."); } } return bitmapFrame; }

    Read the article

  • C# WPF application is using too much memory while GC.GetTotalMemory() is low

    - by Dmitry
    I wrote little WPF application with 2 threads - main thread is GUI thread and another thread is worker. App has one WPF form with some controls. There is a button, allowing to select directory. After selecting directory, application scans for .jpg files in that directory and checks if their thumbnails are in hashtable. if they are, it does nothing. else it's adding their full filenames to queue for worker. Worker is taking filenames from this queue, loading JPEG images (using WPF's JpegBitmapDecoder and BitmapFrame), making thumbnails of them (using WPF's TransformedBitmap) and adding them to hashtable. Everything works fine, except memory consumption by this application when making thumbnails for big images (like 5000x5000 pixels). I've added textboxes on my form to show memory consumption (GC.GetTotalMemory() and Process.GetCurrentProcess().PrivateMemorySize64) and was very surprised, cuz GC.GetTotalMemory() stays close to 1-2 Mbytes, while private memory size constantly grows, especially when loading new image (~ +100Mb per image). Even after loading all images, making thumbnails of them and freeing original images, private memory size stays at ~700-800Mbytes. My VirtualBox is limited to 512Mb of physical memory and Windows in VirtualBox starts to swap alot to handle this huge memory consumption. I guess I'm doing something wrong, but I don't know how to investigate this problem, cuz according to GC, allocated memory size is very low. Attaching code of thumbnail loader class: class ThumbnailLoader { Hashtable thumbnails; Queue<string> taskqueue; EventWaitHandle wh; Thread[] workers; bool stop; object locker; int width, height, processed, added; public ThumbnailLoader() { int workercount,i; wh = new AutoResetEvent(false); thumbnails = new Hashtable(); taskqueue = new Queue<string>(); stop = false; locker = new object(); width = height = 64; processed = added = 0; workercount = Environment.ProcessorCount; workers=new Thread[workercount]; for (i = 0; i < workercount; i++) { workers[i] = new Thread(Worker); workers[i].IsBackground = true; workers[i].Priority = ThreadPriority.Highest; workers[i].Start(); } } public void SetThumbnailSize(int twidth, int theight) { width = twidth; height = theight; if (thumbnails.Count!=0) AddTask("#resethash"); } public void GetProgress(out int Added, out int Processed) { Added = added; Processed = processed; } private void AddTask(string filename) { lock(locker) { taskqueue.Enqueue(filename); wh.Set(); added++; } } private string NextTask() { lock(locker) { if (taskqueue.Count == 0) return null; else { processed++; return taskqueue.Dequeue(); } } } public static string FileNameToHash(string s) { return FormsAuthentication.HashPasswordForStoringInConfigFile(s, "MD5"); } public bool GetThumbnail(string filename,out BitmapFrame thumbnail) { string hash; hash = FileNameToHash(filename); if (thumbnails.ContainsKey(hash)) { thumbnail=(BitmapFrame)thumbnails[hash]; return true; } AddTask(filename); thumbnail = null; return false; } private BitmapFrame LoadThumbnail(string filename) { FileStream fs; JpegBitmapDecoder bd; BitmapFrame oldbf, bf; TransformedBitmap tb; double scale, dx, dy; fs = new FileStream(filename, FileMode.Open); bd = new JpegBitmapDecoder(fs, BitmapCreateOptions.None, BitmapCacheOption.OnLoad); oldbf = bd.Frames[0]; dx = (double)oldbf.Width / width; dy = (double)oldbf.Height / height; if (dx > dy) scale = 1 / dx; else scale = 1 / dy; tb = new TransformedBitmap(oldbf, new ScaleTransform(scale, scale)); bf = BitmapFrame.Create(tb); fs.Close(); oldbf = null; bd = null; GC.Collect(); return bf; } public void Dispose() { lock(locker) { stop = true; } AddTask(null); foreach (Thread worker in workers) { worker.Join(); } wh.Close(); } private void Worker() { string curtask,hash; while (!stop) { curtask = NextTask(); if (curtask == null) wh.WaitOne(); else { if (curtask == "#resethash") thumbnails.Clear(); else { hash = FileNameToHash(curtask); try { thumbnails[hash] = LoadThumbnail(curtask); } catch { thumbnails[hash] = null; } } } } } }

    Read the article

  • Generate BitmapSource from UIElement

    - by Joel
    I am attempting to generate a BitmapFrame that is based on a UIElement. Here is my function: private BitmapFrame RenderToBitmap2() { RenderTargetBitmap renderBitmap = new RenderTargetBitmap(200, 200, 96, 96, PixelFormats.Pbgra32); DrawingVisual drawingVisual = new DrawingVisual(); DrawingContext drawingContext = drawingVisual.RenderOpen(); VisualBrush aVisualBrush = new VisualBrush(GenerateTestStackPanel()); drawingContext.DrawRectangle(aVisualBrush, new Pen(Brushes.Green, 2), new Rect(new Size(150, 150))); drawingContext.Close(); renderBitmap.Render(drawingVisual); return BitmapFrame.Create(renderBitmap); } For testing and debugging purposes, I am using an additional function that creates a simple StackFrame that should create a valid visual element that can be represented: private StackPanel GenerateTestStackPanel() { // Create a red Ellipse. Ellipse myEllipse = new Ellipse(); myEllipse.Fill = Brushes.Green; myEllipse.StrokeThickness = 2; myEllipse.Stroke = Brushes.Black; // Set the width and height of the Ellipse. myEllipse.Width = 200; myEllipse.Height = 200; // Add the Ellipse to the StackPanel. StackPanel myStackPanel = new StackPanel(); myStackPanel.Children.Add(myEllipse); return myStackPanel; } For some reason, the VisualBrush is not being rendered in the DrawRetangle(...) function. I can see the green border but nothing else. In addition, if I swap out the VisualBrush with a standard brush, it works great: drawingContext.DrawRectangle(Brushes.Plum, new Pen(Brushes.Green, 2), new Rect(new Size(150, 150))); Thanks in advance! -Joel

    Read the article

  • Loading a image and copying the metadata of a jpeg image.

    - by Ravi shankar
    I am trying to load a jpeg image and trying to copy metadata to new image, but the new image is created with out any metadata. Can some one help me out in solving above problem. I am using C++ CLI 3.5. if (System::IO::Stream ^jpegStreamIn = File::Open(FileMyPictures, FileMode::Open, FileAccess::ReadWrite, FileShare::None)) { decoder = gcnew System::Windows::Media::Imaging::JpegBitmapDecoder(jpegStreamIn, System::Windows::Media::Imaging::BitmapCreateOptions::PreservePixelFormat, System::Windows::Media::Imaging::BitmapCacheOption::OnLoad); jpegStreamIn->Close(); } bitmapFrame = decoder->Frames[0]; metadata = (System::Windows::Media::Imaging::BitmapMetadata^)bitmapFrame->Metadata;

    Read the article

  • JpegBitmapEncoder.Save() throws exception when writing image with metadata to MemoryStream

    - by Dmitry
    I am trying to set up metadata on JPG image what does not have it. You can't use in-place writer (InPlaceBitmapMetadataWriter) in this case, cuz there is no place for metadata in image. If I use FileStream as output - everything works fine. But if I try to use MemoryStream as output - JpegBitmapEncoder.Save() throws an exception (Exception from HRESULT: 0xC0000005). After some investigation I also found out what encoder can save image to memory stream if I supply null instead of metadata. I've made a very simplified and short example what reproduces the problem: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Drawing; using System.Drawing.Imaging; using System.Windows.Media.Imaging; namespace JpegSaveTest { class Program { public static JpegBitmapEncoder SetUpMetadataOnStream(Stream src, string title) { uint padding = 2048; BitmapDecoder original; BitmapFrame framecopy, newframe; BitmapMetadata metadata; JpegBitmapEncoder output = new JpegBitmapEncoder(); src.Seek(0, SeekOrigin.Begin); original = JpegBitmapDecoder.Create(src, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad); if (original.Frames[0] != null) { framecopy = (BitmapFrame)original.Frames[0].Clone(); if (original.Frames[0].Metadata != null) metadata = original.Frames[0].Metadata.Clone() as BitmapMetadata; else metadata = new BitmapMetadata("jpeg"); metadata.SetQuery("/app1/ifd/PaddingSchema:Padding", padding); metadata.SetQuery("/app1/ifd/exif/PaddingSchema:Padding", padding); metadata.SetQuery("/xmp/PaddingSchema:Padding", padding); metadata.SetQuery("System.Title", title); newframe = BitmapFrame.Create(framecopy, framecopy.Thumbnail, metadata, original.Frames[0].ColorContexts); output.Frames.Add(newframe); } else { Exception ex = new Exception("Image contains no frames."); throw ex; } return output; } public static MemoryStream SetTagsInMemory(string sfname, string title) { Stream src, dst; JpegBitmapEncoder output; src = File.Open(sfname, FileMode.Open, FileAccess.Read, FileShare.Read); output = SetUpMetadataOnStream(src, title); dst = new MemoryStream(); output.Save(dst); src.Close(); return (MemoryStream)dst; } static void Main(string[] args) { string filename = "Z:\\dotnet\\gnom4.jpg"; MemoryStream s; s = SetTagsInMemory(filename, "test title"); } } } It is simple console application. To run it, replace filename variable content with path to any .jpg file without metadata (or use mine). Ofc I can just save image to temporary file first, close it, then open and copy to MemoryStream, but its too dirty and slow workaround. Any ideas about getting this working are welcome :)

    Read the article

  • How to copy DispatcherObject (BitmapSource) into different thread?

    - by Tomáš Kafka
    Hi, I am trying to figure out how can I copy DispatcherObject (in my case BitmapSource) into another thread. Use case: I have a WPF app that needs to show window in a new thread (the app is actually Outlook addin and we need to do this because Outlook has some hooks in the main UI thread and is stealing certain hotkeys that we need to use - 'lost in translation' in interop of Outlook, WPF (which we use for UI), and Winforms (we need to use certain microsoft-provided winforms controls)). With that, I have my implementation of WPFMessageBox, that is configured by setting some static properties - and and one of them is BitmapSource for icon. This is used so that in startup I can set WPFMessageBox.Icon once, and since then, every WPFMessageBox will have the same icon. The problem is that BitmapSource, which is assigned into icon, is a DispatcherObject, and when read, it will throw InvalidOperationException: "The calling thread cannot access this object because a different thread owns it.". How can I clone that BitmapSource into the actual thread? It has Clone() and CloneCurrentValue() methods, which don't work (they throw the same exception as well). It also occured to me to use originalIcon.Dispatcher.Invoke( do the cloning here ) - but the BitmapSource's Dispatcher is null, and still - I'd create a copy on a wrong thread and still couldnt use it on mine. BitmapSource.IsFrozen == true. Any idea on how to copy the BitmapSource into different thread (without completely reconstructing it from an image file in a new thread)? EDIT: So, freezing does not help: In the end I have a BitmapFrame (Window.Icon doesn't take any other kind of ImageSource anyway), and when I assign it as a Window.Icon on a different thread, even if frozen, I get InvalidOperationException: "The calling thread cannot access this object because a different thread owns it." with a following stack trace: WindowsBase.dll!System.Windows.Threading.Dispatcher.VerifyAccess() + 0x4a bytes WindowsBase.dll!System.Windows.Threading.DispatcherObject.VerifyAccess() + 0xc bytes PresentationCore.dll!System.Windows.Media.Imaging.BitmapDecoder.Frames.get() + 0xe bytes PresentationFramework.dll!MS.Internal.AppModel.IconHelper.GetIconHandlesFromBitmapFrame(object callingObj = {WPFControls.WPFMBox.WpfMessageBoxWindow: header}, System.Windows.Media.Imaging.BitmapFrame bf = {System.Windows.Media.Imaging.BitmapFrameDecode}, ref MS.Win32.NativeMethods.IconHandle largeIconHandle = {MS.Win32.NativeMethods.IconHandle}, ref MS.Win32.NativeMethods.IconHandle smallIconHandle = {MS.Win32.NativeMethods.IconHandle}) + 0x3b bytes > PresentationFramework.dll!System.Windows.Window.UpdateIcon() + 0x118 bytes PresentationFramework.dll!System.Windows.Window.SetupInitialState(double requestedTop = NaN, double requestedLeft = NaN, double requestedWidth = 560.0, double requestedHeight = NaN) + 0x8a bytes PresentationFramework.dll!System.Windows.Window.CreateSourceWindowImpl() + 0x19b bytes PresentationFramework.dll!System.Windows.Window.SafeCreateWindow() + 0x29 bytes PresentationFramework.dll!System.Windows.Window.ShowHelper(object booleanBox) + 0x81 bytes PresentationFramework.dll!System.Windows.Window.Show() + 0x48 bytes PresentationFramework.dll!System.Windows.Window.ShowDialog() + 0x29f bytes WPFControls.dll!WPFControls.WPFMBox.WpfMessageBox.ShowDialog(System.Windows.Window owner = {WPFControlsTest.MainWindow}) Line 185 + 0x10 bytes C#

    Read the article

  • Using a Windows Forms icon in WPF

    - by flobadob
    I've got this WPF code which works... Uri iconUri = new Uri("pack://application:,,,/media/images/VS.ico", UriKind.RelativeOrAbsolute); this.Icon = BitmapFrame.Create(iconUri); I'm using a windows forms notifyIcon control in my WPF app, and I now need to assing the Icon to it. How do I get from my WPF icon to a System.Drawing.Icon ?

    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

  • 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] The calling thread cannot access this object because a different thread owns it.

    - by zunyite
    Why I can't create CroppedBitmap in the following code ? I got an exception : The calling thread cannot access this object because a different thread owns it. public MainWindow() { InitializeComponent(); ThreadPool.QueueUserWorkItem((o) => { //load a large image file var bf = BitmapFrame.Create( new Uri("D:\\1172735642.jpg"), BitmapCreateOptions.DelayCreation | BitmapCreateOptions.IgnoreColorProfile, BitmapCacheOption.None); bf.Freeze(); Dispatcher.BeginInvoke( new Action(() => { CroppedBitmap cb = new CroppedBitmap(bf, new Int32Rect(1,1,5,5)); cb.Freeze(); //set Image's source to cb.... }), System.Windows.Threading.DispatcherPriority.ApplicationIdle); } ); }

    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

  • WPF 3.5 RenderTargetBitmap memory hog

    - by kingRauk
    I have a 3.5 WPF application that use's RenderTargetBitmap. It eat's memory like a big bear. It's is a know problem in 3.5 that RenderTargetBitmap.Render has memory problems. Have find some solutions for it, but i doesnt help. https://connect.microsoft.com/VisualStudio/feedback/details/489723/rendertargetbitmap-render-method-causes-a-memory-leak Program takes too much memory And more... Does anyway have any more ideas to solve it... static Image Method(FrameworkElement e, int width, int height) { const int dpi = 192; e.Width = width; e.Height = height; e.Arrange(new Rect(0, 0, width, height)); e.UpdateLayout(); if(element is Graph) (element as Graph).UpdateComponents(); var bitmap = new RenderTargetBitmap((int)(width*dpi/96.0), (int)(height*dpi/96.0), dpi, dpi, PixelFormats.Pbgra32); bitmap.Render(element); var encoder = new PngBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(bitmap)); using (var stream = new MemoryStream()) { encoder.Save(stream); element.Clip = null; Dispose(element); bitmap.Freeze(); DisposeRender(bitmap); bitmap.Clear(); GC.Collect(); GC.WaitForPendingFinalizers(); return System.Drawing.Image.FromStream(stream); } } public static void Dispose(FrameworkElement element) { GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); } public static void DisposeRender(RenderTargetBitmap bitmap) { if (bitmap != null) bitmap.Clear(); bitmap = null; GC.Collect(); GC.WaitForPendingFinalizers(); }

    Read the article

  • saving WPF InkCanvas to a JPG - image is getting cropped

    - by Jason
    I have a WPF InkCanvas control I'm using to capture a signature in my application. The control looks like this - it's 700x300 However, when I save it as a JPG, the resulting image looks like this, also 700x300 The code I'm using to save sigPath = System.IO.Path.GetTempFileName(); MemoryStream ms = new MemoryStream(); FileStream fs = new FileStream(sigPath, FileMode.Create); RenderTargetBitmap rtb = new RenderTargetBitmap((int)inkSig.Width, (int)inkSig.Height, 96d, 96d, PixelFormats.Default); rtb.Render(inkSig); JpegBitmapEncoder encoder = new JpegBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(rtb)); encoder.Save(fs); fs.Close(); This is the XAML I'm using: <Window x:Class="Consent.Client.SigPanel" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Background="Transparent" Topmost="True" AllowsTransparency="True" Title="SigPanel" Left="0" Top="0" Height="1024" Width="768" WindowStyle ="None" ShowInTaskbar="False" ResizeMode="NoResize" WindowStartupLocation="CenterScreen" > <Border BorderThickness="1" BorderBrush="Black" Background='#FFFFFFFF' x:Name='DocumentRoot' Width='750' Height='400' CornerRadius='10'> <StackPanel HorizontalAlignment="Center" VerticalAlignment="Center"> <TextBlock Name="txtLabel" FontSize="24" HorizontalAlignment="Center" >Label</TextBlock> <InkCanvas Opacity="1" Background="Beige" Name="inkSig" Width="700" Height="300" /> <StackPanel HorizontalAlignment="Center" Orientation="Horizontal"> <Button FontSize="24" Margin="10" Width="150" Name="btnSave" Click="btnSave_Click">Save</Button> <Button FontSize="24" Margin="10" Width="150" Name="btnCancel" Click="btnCancel_Click">Cancel</Button> <Button FontSize="24" Margin="10" Width="150" Name="btnClear" Click="btnClear_Click">Clear</Button> </StackPanel> </StackPanel> </Border> In the past this worked perfectly. I can't figure out what changed that is causing the image to shift when it is saved.

    Read the article

  • Rotate and Save Image - C#

    - by Taylor
    Hello, I'm trying to rotate and save an image, along with returning a BitmapSource. I pass in the rotation value (90 or -90) and the full path to the image I want to rotate to the method shown here. It works fine if I start and stop my application between calling this method. however, if the application calls rotate multiple times the rotate only happens once. I know the original image must be cached in memory, because if I pass values 90, 180, 270 I see the rotations work. I want to be able to pass in a value of 90 or -90 and have that rotate and save the original image. How can I make the rotate work for each call? Is there a way to clear the cached value of the image? If I don't set the BitmapCacheOption to OnLoad, I am unable to transform and save the image since the image is "being used by another process". public BitmapImage Rotate(int val, string path) { //create a new image from existing file. Image image = new Image(); BitmapImage logo = new BitmapImage(); logo.BeginInit(); logo.CacheOption = BitmapCacheOption.OnLoad; logo.UriSource = new Uri(path); logo.EndInit(); image.Source = logo; BitmapSource img = (BitmapSource)(image.Source); //rotate image and save CachedBitmap cache = new CachedBitmap(img, BitmapCreateOptions.None, BitmapCacheOption.OnLoad); TransformedBitmap tb = new TransformedBitmap(cache, new RotateTransform(val)); TiffBitmapEncoder encoder = new TiffBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(tb)); using (FileStream file = File.OpenWrite(path)) { encoder.Save(file); } //update page view BitmapImage bi = new BitmapImage(); bi.BeginInit(); bi.CacheOption = BitmapCacheOption.OnLoad; bi.UriSource = new Uri(path); bi.EndInit(); return bi; }

    Read the article

  • Why do I get completely different results when saving a BitmapSource to bmp, jpeg, and png in WPF

    - by DanM
    I wrote a little utility class that saves BitmapSource objects to image files. The image files can be either bmp, jpeg, or png. Here is the code: public class BitmapProcessor { public void SaveAsBmp(BitmapSource bitmapSource, string path) { Save(bitmapSource, path, new BmpBitmapEncoder()); } public void SaveAsJpg(BitmapSource bitmapSource, string path) { Save(bitmapSource, path, new JpegBitmapEncoder()); } public void SaveAsPng(BitmapSource bitmapSource, string path) { Save(bitmapSource, path, new PngBitmapEncoder()); } private void Save(BitmapSource bitmapSource, string path, BitmapEncoder encoder) { using (var stream = new FileStream(path, FileMode.Create)) { encoder.Frames.Add(BitmapFrame.Create(bitmapSource)); encoder.Save(stream); } } } Each of the three Save methods work, but I get unexpected results with bmp and jpeg. Png is the only format that produces an exact reproduction of what I see if I show the BitmapSource on screen using a WPF Image control. Here are the results: BMP - too dark JPEG - too saturated PNG - correct Why am I getting completely different results for different file types? I should note that the BitmapSource in my example uses an alpha value of 0.1 (which is why it appears very desaturated), but it should be possible to show the resulting colors in any image format. I know if I take a screen capture using something like HyperSnap, it will look correct regardless of what file type I save to. Here's a HyperSnap screen capture saved as a bmp: As you can see, this isn't a problem, so there's definitely something strange about WPF's image encoders. Do I have a setting wrong? Am I missing something?

    Read the article

  • Baffled by differences between WPF BitmapEncoders

    - by DanM
    I wrote a little utility class that saves BitmapSource objects to image files. The image files can be either bmp, jpeg, or png. Here is the code: public class BitmapProcessor { public void SaveAsBmp(BitmapSource bitmapSource, string path) { Save(bitmapSource, path, new BmpBitmapEncoder()); } public void SaveAsJpg(BitmapSource bitmapSource, string path) { Save(bitmapSource, path, new JpegBitmapEncoder()); } public void SaveAsPng(BitmapSource bitmapSource, string path) { Save(bitmapSource, path, new PngBitmapEncoder()); } private void Save(BitmapSource bitmapSource, string path, BitmapEncoder encoder) { using (var stream = new FileStream(path, FileMode.Create)) { encoder.Frames.Add(BitmapFrame.Create(bitmapSource)); encoder.Save(stream); } } } Each of the three Save methods work, but I get unexpected results with bmp and jpeg. Png is the only format that produces an exact reproduction of what I see if I show the BitmapSource on screen using a WPF Image control. Here are the results: BMP - too dark JPEG - too saturated PNG - correct Why am I getting completely different results for different file types? I should note that the BitmapSource in my example uses an alpha value of 0.1 (which is why it appears very desaturated), but it should be possible to show the resulting colors in any image format. I know if I take a screen capture using something like HyperSnap, it will look correct regardless of what file type I save to. Here's a HyperSnap screen capture saved as a bmp: As you can see, this isn't a problem, so there's definitely something strange about WPF's image encoders. Do I have a setting wrong? Am I missing something?

    Read the article

  • Is it OK to use WPF assemblies in a web app?

    - by Chris
    I have an ASP.NET MVC 2 app targeting .NET 4 that needs to be able to resize images on the fly and write them to the response. I have code that does this and it works. I am using System.Drawing.dll. However, I want to enhance my code so that not only am I resizing the image, but I am dropping it from 24bpp down to 4bit grayscale. I could not, for the life of me, find code on how to do this with System.Drawing.dll. But I did find a bunch of WPF stuff. This is my working/sample code (runs in LinqPad). // Load the original 24 bit image var bitmapImage = new BitmapImage(); bitmapImage.BeginInit(); bitmapImage.UriSource = new Uri(@"C:\Temp\Resized\18_appa2_015.png", UriKind.Absolute); //bitmapImage.DecodePixelWidth = 600; bitmapImage.EndInit(); // Create the destination image var formatConvertedBitmap = new FormatConvertedBitmap(); formatConvertedBitmap.BeginInit(); formatConvertedBitmap.Source = bitmapImage; formatConvertedBitmap.DestinationFormat = PixelFormats.Gray4; formatConvertedBitmap.EndInit(); // Encode and dump the image to disk var encoder = new PngBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(formatConvertedBitmap)); using (var fileStream = File.Create(@"C:\Temp\Resized\18_appa2_015_s2.png")) { encoder.Save(fileStream); } It uses System.Xaml.dll, WindowsBase.dll, PresentationCore.dll, and PresentationFramework.dll. The namespaces used are: System.Windows.Controls, System.Windows.Media, and System.Windows.Media.Imaging. Is there any problem using these namespaces in my web application? It doesn't seem right. If anyone knows how to drop the bit depth without all this WPF stuff (which I barely understand, BTW) I would be thrilled to see that too.

    Read the article

  • InPlaceBitmapMetadataWriter.TrySave() returns true but does nothing

    - by mephisto123
    On some .JPG files (EPS previews, generated by Adobe Illustrator) in Windows 7 InPlaceBitmapMetadataWriter.TrySave() returns true after some SetQuery() calls, but does nothing. Code sample: BitmapDecoder decoder; BitmapFrame frame; BitmapMetadata metadata; InPlaceBitmapMetadataWriter writer; decoder = BitmapDecoder.Create(s, BitmapCreateOptions.PreservePixelFormat | BitmapCreateOptions.IgnoreColorProfile, BitmapCacheOption.Default); frame = decoder.Frames[0]; metadata = frame.Metadata as BitmapMetadata; writer = frame.CreateInPlaceBitmapMetadataWriter(); try { writer.SetQuery("System.Title", title); writer.SetQuery(@"/app1/ifd/{ushort=" + exiftagids[0] + "} ", (title + '\0').ToCharArray()); writer.SetQuery(@"/app13/irb/8bimiptc/iptc/object name", title); return writer.TrySave(); } catch { return false; } Image sample You can reproduce problem (if you have Windows 7) by downloading image sample and using this code sample to set title on this image. Image has enough room for metadata - and this code sample works fine on my WinXP. Same code works fine on Win7 with other .JPG files. Any ideas are welcome :)

    Read the article

  • C# Read Byte [] to Image

    - by LucasGuitar
    I have an application which I'm adding pictures and these are automatically converted to binary and stored in a single file. how can I save several images, I keep in an XML file start and size of each set of refente to an image byte. But it has several images in bytes, whenever I try to select a different set of bytes just opening the same image. I would like your help to be able to fix this and open different images. Code //Add Image private void btAddImage_Click(object sender, RoutedEventArgs e) { OpenFileDialog op = new OpenFileDialog(); op.Title = "Selecione a Imagem"; op.Filter = "All supported graphics|*.jpg;*.jpeg;*.png|" + "JPEG (*.jpg;*.jpeg)|*.jpg;*.jpeg|" + "Portable Network Graphic (*.png)|*.png"; if (op.ShowDialog() == true) { imgPatch.Source = new BitmapImage(new Uri(op.FileName)); txtName.Focus(); } } //Convert Image private void btConvertImage_Click(object sender, RoutedEventArgs e) { if (String.IsNullOrEmpty(txtName.Text)) { txtName.Focus(); MessageBox.Show("Preencha o Nome", "Error"); } else { save(ConvertFileToByteArray(op.FileName), txtName.Text); } } //Image to Byte Array private static byte[] ConvertFileToByteArray(String FilePath) { return File.ReadAllBytes(FilePath); } //Save Binary File and XML File public void save(byte[] img, string nome) { FileStream f; long ini, fin = img.Length; if (!File.Exists("Escudos.bcf")) { f = new FileStream("Escudos.bcf", FileMode.Create); ini = 0; } else { f = new FileStream("Escudos.bcf", FileMode.Append); ini = f.Length + 1; bin = new TestBinarySegment(); } bin.LoadAddSave("Escudos.xml", "Brasileiro", nome, ini, fin); BinaryWriter b = new BinaryWriter(f); b.Write(img); b.Close(); f.Dispose(); } //Load Image from Byte private void btLoad_Click(object sender, RoutedEventArgs e) { getImageFromByte(); } //Byte to Image public void getImageFromByte(int start, int length) { using (FileStream fs = new FileStream("Escudos.bcf", FileMode.Open)) { byte[] iba = new byte[fs.Length+1]; fs.Read(iba, start, length); Image image = new Image(); image.Source = BitmapFrame.Create(fs, BitmapCreateOptions.None, BitmapCacheOption.OnLoad); imgPatch2.Source = image.Source; } }

    Read the article

  • Drawing a WPF UserControl with DataBinding to an Image

    - by LorenVS
    Hey Everyone, So I'm trying to use a WPF User Control to generate a ton of images from a dataset where each item in the dataset would produce an image... I'm hoping I can set it up in such a way that I can use WPF databinding, and for each item in the dataset, create an instance of my user control, set the dependency property that corresponds to my data item, and then draw the user control to an image, but I'm having problems getting it all working (not sure whether databinding or drawing to the image is my problem) Sorry for the massive code dump, but I've been trying to get this working for a couple of hours now, and WPF just doesn't like me (have to learn at some point though...) My User Control looks like this: <UserControl x:Class="Bleargh.ImageTemplate" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:c="clr-namespace:Bleargh" x:Name="ImageTemplateContainer" Height="300" Width="300"> <Canvas> <TextBlock Canvas.Left="50" Canvas.Top="50" Width="200" Height="25" FontSize="16" FontFamily="Calibri" Text="{Binding Path=Booking.Customer,ElementName=ImageTemplateContainer}" /> <TextBlock Canvas.Left="50" Canvas.Top="100" Width="200" Height="25" FontSize="16" FontFamily="Calibri" Text="{Binding Path=Booking.Location,ElementName=ImageTemplateContainer}" /> <TextBlock Canvas.Left="50" Canvas.Top="150" Width="200" Height="25" FontSize="16" FontFamily="Calibri" Text="{Binding Path=Booking.ItemNumber,ElementName=ImageTemplateContainer}" /> <TextBlock Canvas.Left="50" Canvas.Top="200" Width="200" Height="25" FontSize="16" FontFamily="Calibri" Text="{Binding Path=Booking.Description,ElementName=ImageTemplateContainer}" /> </Canvas> </UserControl> And I've added a dependency property of type "Booking" to my user control that I'm hoping will be the source for the databound values: public partial class ImageTemplate : UserControl { public static readonly DependencyProperty BookingProperty = DependencyProperty.Register("Booking", typeof(Booking), typeof(ImageTemplate)); public Booking Booking { get { return (Booking)GetValue(BookingProperty); } set { SetValue(BookingProperty, value); } } public ImageTemplate() { InitializeComponent(); } } And I'm using the following code to render the control: List<Booking> bookings = Booking.GetSome(); for(int i = 0; i < bookings.Count; i++) { ImageTemplate template = new ImageTemplate(); template.Booking = bookings[i]; RenderTargetBitmap bitmap = new RenderTargetBitmap( (int)template.Width, (int)template.Height, 120.0, 120.0, PixelFormats.Pbgra32); bitmap.Render(template); BitmapEncoder encoder = new PngBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(bitmap)); using (Stream s = File.OpenWrite(@"C:\Code\Bleargh\RawImages\" + i.ToString() + ".png")) { encoder.Save(s); } } EDIT: I should add that the process works without any errors whatsoever, but I end up with a directory full of plain-white images, not text or anything... And I have confirmed using the debugger that my Booking objects are being filled with the proper data... EDIT 2: Did something I should have done a long time ago, set a background on my canvas, but that didn't change the output image at all, so my problem is most definitely somehow to do with my drawing code (although there may be something wrong with my databinding too)

    Read the article

1