System.Drawing.Bitmap Parameter is not valid - c#

I am having this error:
parameter is not valid.
On this line:
System.Drawing.Bitmap("~\\father\\chocolate.png");

It's very unlikely that "~\\father\\chocolate.png" is a valid filename on its own - I suspect you want to map that from an ASP.NET somewhat-relative filename to a real local filename first.
For example:
var bitmap = new Bitmap(Server.MapPath("~/father/chocolate.png"));
(I'd personally suggest using forward slashes instead of backslashes here - they work just as well under Windows; they'll still work under Linux; they don't need escaping.)

It is probably a little late for this suggestion, but for the sake of anyone else viewing this post:
If you are using/opening your image somewhere in your code, this could be a good reason.
Make sure you close any memory stream or instances of the image object after you are done.
I just came across this error in the form of: an HttpException (0x80004005): Parameter is not valid.
After debugging I realized that disposing of the image had everything to do with this error.
The amazing part was that while the image was already stored in our database and not being used, it would seem the function holds on to it.
If you have instantiated the png file as an Image object, make sure you close any MemoryStream/Stream objects and dispose of the image (set it to nothing) and perform a garbage collection to release it from memory.
hope this helps!

Related

loading lots of images causes out of memory

I swear I knew the answer to this one but I forgot.
I have this function. It loads bitmaps and draws them. it can be called in rapid succession. After about 300 or so bitmaps the application crashes with a System.OutOfMemoryException.
Please tell me what am I doing wrong again :)
private void PaintPicture()
{
string FullPath = Global.RunttimePath + EditType.FilePath;
if (File.Exists(FullPath))
{
Image i = Image.FromFile(FullPath);
//DrawImage(i, pnlPicture, pbColor.BackColor); //I disabled this so the problem is not here
i.Dispose();
//GC.Collect(); //I know I know... I should never call GC. So disabled it :)
}
else
{
//DrawImage(Properties.Resources.Fail800, pnlPicture, Color.White, true);
}
}
According to the documentation of Image.FromFile you can get an OutOfMemoryException if the bitmap is in an unknown format. Make sure your application can safely load all images you're trying to use and see if it always crashes on the same image.
If it's always the same image then you can try re-saving the image in a supported pixel format (using Photoshop or Paint.Net or some other free tool) - this should fix the particular image that breaks your application.
Also, add an exception handler around your drawing logic to make sure your application doesn't crash when it runs into a bad image - GDI+ only supports a relatively low number of image formats.
To verify if you're actually running out of memory (that is, if there is a leak), monitor memory use while your application is running. If you see signs of a memory leak, your problem is likely elsewhere.
Edit:
Read these questions / answers for advice about using Image.FromStream instead of FromFile() - doing so avoids locking the file for a long time:
File.Delete failing when Image.FromFile was called prior it, despite making copy of loaded image and destroying original one
out of memory Image.FromFile
This likely won't resolve your problem, but the Image class implements IDisposable. That means you can wrap it in a USING statement, which causes the objects inside to go out of scope faster/less objects surviving to L2 garbage collection (it shouldn't make a difference between wrapping things in a using vs. calling dispose, but we found through memory profiling that it actually does).
if (File.Exists(FullPath))
{
using(Image i = Image.FromFile(FullPath))
{
DrawImage(i, pnlPicture, pbColor.BackColor); //I disabled this so the problem is not here
//GC.Collect(); //I know I know... I should never call GC. So disabled it :)
}
}
else
{
//DrawImage(Properties.Resources.Fail800, pnlPicture, Color.White, true);
}
}

Undocumented .NET code related to Multi-Touch Manipulations throwing exception

A favorable outcome would be preventing this exception, preferably, or at least handling it gracefully.
I am getting an exception thrown within Microsoft code. On top of that, the method throwing the exception is System.Windows.Input.Manipulations.ManipulationSequence.ProcessManipulators, which I can't find in Microsoft Reference Source.
When the exception is thrown, I can see that one line down in the Call Stack window it references Windows.Input.Manipulations.ManipulationProcessor2D.ProcessManipulators, which does exist in Microsoft Reference Source.
But as you can see, it doesn't have a sibling class named ManipulationSequence.
As for the exception itself, it is a System.Argument.OutOfRangeException with a value of Timestamp values must not decrease. Parameter name: timestamp Actual value was 6590630705479.
The fully qualified signature of the method throwing the exception is System.Windows.Input.Manipulations.ManipulationSequence.ProcessManipulators(long timestamp, System.Collections.Generic.IEnumerable<System.Windows.Input.Manipulations.Manipulator2D> manipulators, System.Windows.Input.Manipulations.ManipulationSequence.ISettings settings)
It appears as if one other person in the universe has had this problem, but it could not be reproduced according to the only comment.
I have 6 MediaElement objects on a canvas that are all running videos when being manipulated, so I feel as though it might have something to do with the CPU being taxed and slowing down, possibly making timestamps be sent into the method out of order (though the same problem occurs when using Image rather than MediaElement). The exception happens sporadically, sometimes it will happen after just a few seconds of messing around with the objects, sometimes it can go for a few minutes or more of manipulating the objects.
My code that does the actual manipulation within ManipulationDelta looks like this:
//Get current values to manipulate
TransformGroup group = (TransformGroup)element.RenderTransform.Clone();
TranslateTransform translate = (TranslateTransform)group.Children[0].Clone();
ScaleTransform scale = (ScaleTransform)group.Children[1].Clone();
RotateTransform rotate = (RotateTransform)group.Children[2].Clone();
//...does manipulations on each by changing values...
//Apply transformation changes
group.Children[0] = translate;
group.Children[1] = scale;
group.Children[2] = rotate;
element.RenderTransform = group;
I have a Storyboard in XAML messing with the RotateTransform, so I can't really use MatrixTransform.
I am creating this using WPF with .NET 4.5.1. The error occurs in both Windows 8.1 and Windows 7. Any ideas on how to prevent this exception from occurring?
Some thoughts as I investigate the problem:
I also have ManipulationInertiaStarting in play here as a possible
cause of this error.
I just added e.Handled = true; to the end of ManipulationCompleted, which wasn't there before. I haven't got the error since (though, again, very sporadic, so it is hard to tell when it is fixed).
If a ManipulationDelta method is not yet complete, and it is hit again from user input, could there be some sort of race condition occurring where the first method hit is starved for CPU resources and the second runs through, then when the first method finally completes the timestamp created is in the past?
Per a comment, this isn't likely.
I conferred with a co-worker to gain better understanding. He helped me realize I can't swallow the exception from within my methods that handle manipulation events because the exception is happening before it gets there, in the actual creation of the manipulation data. So the only place I can handle the exception is on App.Main() (the first place in the Call Stack where my code exists), which makes handling it gracefully all the more difficult.
I had this exact problem myself.
After a lot of testing it could be reproduced with slower machines under heavy load.
The Application was for Digital Signage and showed a lot of different items ( Video, Html , Images , etc ) and had also some animations.
I am not sure about it but it seems to be a problem of handling the input events in time.
For myself i could "solve" this issue with outsourcing code from the manipulating to other code asynchronous and also profiling and rewriting code performance-wise.( shortened the path to run inside the event as much as possible and did everything needed to do also later with a Task )
Also i added an Exceptionhandler to my application to "ignore and log" this issue, because it had no other impact.
Feel free to contact me for more info on this.
PS: this is my first answer here, so i hope it is alright the way i wrote it
I had similar problems when developing for WinRT.
It's sometimes possible to use DispatcherUnhandledException event to ignore one particular exception. To do that, add event listener, check if exception is the one you want (because it's generally bad idea to suppress all exception), and then set Handled property.

How to load a DataGridView correctly while updated happening

I implemented a DataGridView some time ago. It works nice. Now I was doing some heavy-load testing, but it failed. It throws exceptions everywhere, at least when it tries to load the data.
Problem: DataContext Refresh
There is a method where I refresh the the data inside the DataGridView.
One exception tells me there is already a DataReader open, which I have to close first.
The second exception tells me "the operation cannot be performed during a call to submitchanges".
The problem is that I am not working with DataReaders myself, I am using the approach you see below:
this.bindingSource.EndEdit();
this.bindingSource.DataSource = null;
// DataControl is my controler where the table is stored. It is a singleton.
DataControl.Instance.m_DBTable.Context.Refresh(System.Data.Linq.RefreshMode.OverwriteCurrentValues, DataControl.Instance.m_DBTable);
this.bindingSource.ResetBindings(false);
this.bindingSource.DataSource = DataControl.Instance.m_DBTable;
I hope someone can help me on this one. Feel free to ask for more details if needed.
Thanks
More exceptions thrown (not only on that method, but on the same form.)
Internal connection fatal error
Sql DateTime-Overflow (must be between 1/1/1753 and 21/31/9999) (I really do ALWAYS initialize all my date-time variables!)
Invalid reading operation when there is no data available.
No reference exception.
any time you are getting errors relating to this wrap your datareader in a using statement. This goes for any reader / writer
using(var daraReader = new DataReader())
{
// Use your data reader here, it will not be left open
}
DataContext isn't actually designed to be singleton Using a Singleton pattern to Linq to Sql Data Context. That's the first thing you should consider in your code.
If it doesn' work - try to at least dissect the problem area(http://ericlippert.com/2014/03/05/how-to-debug-small-programs/). Do not bind the data. Just try to dump them into a file or somewhere else. We will be sure that the problems are not caused by binding.
If it won't work also then it is quite possible you are having problems due to concurrency issues in LINQ to SQL and your database. Looks like standard locks and mechanisms does not work as intended. Or they work too diligently.
There are few decent articles http://blogs.msdn.com/b/matt/archive/2008/05/22/into-to-linq-to-sql-optimistic-concurrency.aspx, http://www.codeproject.com/Articles/38299/How-To-Handle-Concurrency-in-LINQ-to-SQL that explain concurrency in LINQ.
I hope that some of it could help.

Properly dispose of non referenced Image without garbage collection C#

I have a C# program which creates a List of Bitmaps from the images in a directory. It'll use the whole list of Bitmaps to generate one new image, which it will then save. When the user loads a new directory to repeat the process, the List of Bitmaps is cleared and refilled. The bitmaps are loaded upon creation of the object, "new Bitmap(path)".
I had a problem which occurred when the user performed the following steps:
Load images from directory 1
Chose not to save and instead load images from directory 2
Tries to save by overwriting an image from directory 1
Program is unable to save due to "A generic error in GDI+", because it is still "using" the image that is being overwritten.
The original List of Bitmaps loaded from directory 1 is indeed cleared and then refilled with images from directory 2. However, Bitmap.Save() refuses to overwrite an image it had previously loaded unless I call System.GC.Collect() after I perform Clear().
I'm pretty sure the problem has something to do with keeping the Bitmaps around even though there are no references, otherwise why would garbage collecting solve the problem? Is this the right way to go about solving this problem, or is there a "proper" way to dispose of Bitmaps in C#? Thanks.
You need to call Dispose on the Bitmap instances.. so they free their file handle.
var bitmap = new Bitmap(path_to_file);
// use it
bitmap.Dispose();
Or, since Bitmap inherits from Image which implements IDisposable, you can do this:
using (var bitmap = new Bitmap(path_to_file)) {
// use it..
}

Why is setting a XAML Image Source to URI faster than using HttpClient to get the Image?

I'm building a Windows Store App and learning XAML at the same time. I have remote images at a http URI that I want to show in a GridView.
My original solution involved using HttpClient to download the image byte array from the URI, get a RandomAccessStreamReference, construct a BitmapImage, and then set the XAML Image control's source property to the constructed BitmapImage. However, this solution proved to be rather slow (1-2 full seconds to get a single image).
My next solution was to bind the raw URI directly to the XAML Image control's source property directly, which the XAML engine seems to take upon itself to resolve. What used to take 10 seconds to load about 8-10 images suddenly was instant.
Does anyone know how exactly the default URI converter for the XAML Image control resolves the remote image data? It's entirely possible that my first solution was just poorly implemented, but the discrepancy is large enough to pique my curiosity.
Assuming I've found the right piece of code from the ImageSourceConverter class, when you specify the source as a string, the converter is attempting to do this:
if (((value is string) && !string.IsNullOrEmpty((string) value)) || (value is Uri))
{
UriHolder uriFromUriContext = TypeConverterHelper.GetUriFromUriContext(context, value);
return BitmapFrame.CreateFromUriOrStream(uriFromUriContext.BaseUri, uriFromUriContext.OriginalUri, null, BitmapCreateOptions.None, BitmapCacheOption.Default, null);
}
BitmapFrame in turn uses a BitmapDecoder to load the image. When the source is a Uri, the BitmapDecoder, amid a bunch of security and sanity checks, uses a WpfWebRequestHelper (undocumented) to request or "download" the image. If the resulting response stream is a valid file, it directly loads the stream into a new FileStream.
Following that, native Windows image decoding functionality takes over to get you your image. Also note that the BitmapDecoder gets cached, so if you're loading multiple images in a row, you don't have the overhead of re-initializing a new BitmapDecoder. Whether that had anything to do with your performance issue I can't say.
In conclusion, I'm guessing that the method WPF uses internally to load images is a highly optimized approach at doing so. I have not looked at the implementation of the HttpClient vs. the likely use of a simple HttpWebRequest to download the image, but I suspect that the overhead of your method was more than that of the built-in method and is what contributed to your slower performance.
If you're wondering how I was able to decipher this information, I simply inspected a few classes within the System.Windows.Media namespace in the PresentationCore assembly using a tool called Reflector.

Categories