I have an windows c# forms application in which copying image from one window to another.
Getting below exception when using
public static System.Drawing.Bitmap FromHbitmap(IntPtr hbitmap) of system.drawing.image.
Exception
System.Runtime.InteropServices.ExternalException (0x80004005): A generic error occurred in GDI+.
at System.Drawing.Image.FromHbitmap(IntPtr hbitmap, IntPtr hpalette)
at System.Drawing.Image.FromHbitmap(IntPtr hbitmap)
This exception occurs only when application ran in 5MegaPixel monitor. It works well in regular monitor.
I understand GDI+ limits the maximum height of an image to 65500 pixel.
Please suggest how to support FromHbitmap in 5MP monitor or is there any alternative?
Related
I created a simple program that brings images to PictureBox when I click a button.
Please tell me why the exception occurs in the commented processed code.
Code
OpenCV_image = Cv2.ImRead(openFile_Dialog.FileName, ImreadModes.Grayscale);
// Line which raises exception
pictureBox1.Image = BitmapConverter.ToBitmap(OpenCV_image);
Exception
System.AccessViolationException
I'm studying OpenCV for the first time, and I used Google to study and copy it, but it doesn't work.
My application is recording the screen (taking screenshots) using Graphics.CopyFromScreen(...) function. The problem is that sometimes an ,,Invalid handle win32" exception is being thrown for some unknown reason. The program is running in the background (it's a console app project with hidden console). I was looking for a solution with google, but I haven't found anything helpful in my case.
The function I wrote:
static Bitmap takeScreenshot()
{
Bitmap bmpScreenCapture = new Bitmap(Screen.PrimaryScreen.Bounds.Width,
Screen.PrimaryScreen.Bounds.Height);
using (Graphics g = Graphics.FromImage(bmpScreenCapture))
{
g.CopyFromScreen(Screen.PrimaryScreen.Bounds.X,
Screen.PrimaryScreen.Bounds.Y,
0, 0,
bmpScreenCapture.Size,
CopyPixelOperation.SourceCopy);
}
return bmpScreenCapture;
}
I've just found out that the app was trying to create files that already existed. Somehow that caused an exception, but I don't know why. I deleted old files and now program seems to work properly...
I am facing a problem that I am not able to solve or google solution anywhere.
I am running service that load or saves images and uses BitmapEncoder or BitmapDecoder classes. After some time (depending how often I save/load images) service refuse to save/load images. First I see warning in event log with
heap allocation failed
I googled what does it mean and it has to do with limited number of GDI objects that Windows service has. Its possible to modify registry to increase number of these object but its not very nice solution I think and also it does not work for me.
My code throws following exception with stack trace when saving
Error while storing image : System.ComponentModel.Win32Exception (0x80004005): The operation completed successfully
at MS.Win32.HwndWrapper..ctor(Int32 classStyle, Int32 style, Int32 exStyle, Int32 x, Int32 y, Int32 width, Int32 height, String name, IntPtr parent, HwndWrapperHook[] hooks)
at System.Windows.Threading.Dispatcher..ctor()
at System.Windows.Threading.DispatcherObject..ctor()
at System.Windows.Media.Imaging.BitmapEncoder..ctor(Boolean isBuiltIn)
at Imaging.TiffReadWrite.Save(String filename, Image img)
and when loading
Error while loading image : System.ComponentModel.Win32Exception (0x80004005): The operation completed successfully
at MS.Win32.HwndWrapper..ctor(Int32 classStyle, Int32 style, Int32 exStyle, Int32 x, Int32 y, Int32 width, Int32 height, String name, IntPtr parent, HwndWrapperHook[] hooks)
at System.Windows.Threading.Dispatcher..ctor()
at System.Windows.Threading.DispatcherObject..ctor()
at System.Windows.Media.Imaging.BitmapDecoder..ctor(Stream bitmapStream, BitmapCreateOptions createOptions, BitmapCacheOption cacheOption, Guid expectedClsId)
at Imaging.TiffReadWrite.Load(String filename)
My code for saving images looks like:
public static void Save(string filename, BitmapSource img)
{
using (FileStream stream = new FileStream(filename, FileMode.Create))
{
TiffBitmapEncoder encoder = new TiffBitmapEncoder();
encoder.Compression = TiffCompressOption.None;
BitmapFrame frm = BitmapFrame.Create(img);
encoder.Frames.Add(frm);
encoder.Save(stream);
}
}
and for loading images looks like:
public static BitmapSource Load(string filename)
{
BitmapSource resultImage = null;
using (Stream imSource = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read))
{
var decoder = new TiffBitmapDecoder(imSource, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
resultImage = decoder.Frames[0];
}
return resultImage;
}
So, service refuses to save/load images. I can try/catch this exception so the service can continue running, but no images could be saved/load. Sometimes after first occurrence of this exception few images could be saved/loaded and after a while no saving/loading is performed.
My only workaround for this problem is not running this code in service but in application. Then it runs just fine, but that is not a solution I am looking for. If anyone has any better suggestion please let me know.
There are some similar posts (stack trace of exception is more or less the same) that is not actually solved:
Image Resizing : The operation completed successfully
Does that mean an object doesn't need to be cleared manually if it doesn't implement IDisposable?
Windows.Media.Imaging Thumbnail generation causing exceptions
The operation completed successfully
This mystifying message narrows down the exact code in the HwndWrapper constructor that fails. WPF has a bug in the GetStockObject pinvoke declaration. Its SetLastError = true property is wrong, GetStockObject() does not in fact produces an error code. You see the description of error code 0, "nothing went wrong".
GetStockObject() is a winapi function that never fails if it gets the correct argument. Stock objects are pre-allocated and never released. You have very strong evidence that the process state is thoroughly corrupted. Seeing a "heap allocation failed" message in the event log is certainly part of that misery.
If you have no idea what could cause this corruption, machine is known-good with reliable RAM, you are not running any dangerous native code and the machine is not running any other services that could corrupt the desktop heap, then the only alternative you have is to create a minidump of the crashed process. Call Microsoft Support, they can follow the trace from the GetStockObject() failure. Do beware that you'll have to get through the first support layers, the ones that will tell you to swap the machine out :)
I have a problem where loading or cloning an png file to an .Net (3.5) Bitmap class causes an OutOfMemoryException within the GDI framework.
This code on run inside an ThreadPool.QueueUserWorkItem, at any time the code creates up to 20 calls to the image loading method that has this code.
// The GDI may throw an OutOfMemoryException on either load or clone of an bitmap
using (var bmp = new Bitmap(filename))
{
var clone = bmp.Clone(new Rectangle(new Point(0, 0), bmp.Size), PixelFormat.Format32bppPArgb);
//post clone bitmap to main thread
}
The solution is to put and try catch around the using statement
try {
using (var bmp = new Bitmap(filename))
{ ... }
}
catch (OutOfMemoryException) { // Swallow the exception}
I have tested and shown this defect on Win7 32&64bit machines and Win8 in Normal and safe modes. This defect only shows on 5 out of 8 machines where the tests where carried out.
Machines are high end Dell and Asus workstations and laptops with different video cards.
Due to the exception coming from the GDI software stack, I don't believe this defect is related to hardware.
The exception may be thrown less than 0.1% of the time, so rare and random. The files are in good order and are not the cause of the problem.
I am looking for an explanation as to why the GDI throws this exception, so I can explain it to my software team and our customer.
Why I'm getting "A Generic Error occurred in GDI+" Exception ?
IntPtr hicon = tempBitmap.GetHicon();
Icon bitmapIcon = Icon.FromHandle(hicon);
return bitmapIcon;
The error occurred when my application has been running for more than 30 minutes. (I am converting System.Drawing.Bitmap to System.Drawing.Icon every second)
That's caused by a handle leak. You can diagnose the leak with TaskMgr.exe, Processes tab. View + Select Columns and tick Handles, GDI Objects and USER Objects. Observe these columns while your program is running. If my guess is right, you'll see the GDI Objects value for your process steadily climbing. When it reaches 10,000 then the show is over, Windows refuses to allow you to leak more objects.
The Remarks section for Icon.FromHandle says:
When using this method you must dispose of the resulting icon using the DestroyIcon method in the Win32 API to ensure the resources are released.
That's good advice but usually pretty painful to do. You can find a hack to force the Icon object to own the handle, and automatically release it, in this answer. Relevant code is after the "Invoke private Icon constructor" section.
You probably need to clean up your icon.
The example for Icon.FromHandle on MSDN shows you how. Unfortunately it requires PInvoke:
[System.Runtime.InteropServices.DllImport("user32.dll", CharSet=CharSet.Auto)]
extern static bool DestroyIcon(IntPtr handle);
And then inside your method:
IntPtr hicon = tempBitmap.GetHicon();
Icon bitmapIcon = Icon.FromHandle(hicon);
// And then somewhere later...
DestroyIcon(bitMapIcon.Handle);
If you call DestoryIcon before you use it, it may not work. For my own particular instance of this problem, I ended up keeping a reference to the last icon I created and then called DestroyIcon on it the next time I generated an icon.