DLL crashes C# application - c#

My colleague and myself wrote a DLL which we're now trying to use in another application. When we use functions from that DLL in our application when using a web cam the app crashes. When we copy and paste the exact same code the application works.
If we are using a image instead of a web cam then it also works with DLL.
We made a new app just to test it and when using that DLL is still doesn't work.
We're really confused because we get different exceptions and we really don't know what's wrong. Are there any general errors that could cause this? Is there a way we could debug this?
Code is as follows:
private glyphRecognizer recognize = new glyphRecognizer();
picturebox1.image = recognize.recognitionStep1_Grayscaling((Bitmap)picturebox1.image);
And for DLL:
public Bitmap recognitionStep1_Grayscaling(Bitmap image)
{
BitmapData data = image.LockBits(new Rectangle(0, 0, image.Width, image.Height), ImageLockMode.ReadOnly, image.PixelFormat);
UnmanagedImage originalImage = new UnmanagedImage(data);
image.UnlockBits(data);
//grayscaling
UnmanagedImage grayImage = null;
if (data.PixelFormat == PixelFormat.Format8bppIndexed)
{
grayImage = originalImage;
}
else
{
grayImage = UnmanagedImage.Create(originalImage.Width, originalImage.Height, PixelFormat.Format8bppIndexed);
Grayscale.CommonAlgorithms.BT709.Apply(originalImage, grayImage);
}
return grayImage.ToManagedImage();
}

Related

.NET Bitmap.Clone() throws OutOfMemoryException

Why does the following simple piece of code (bitmap.Clone) throw an OutOfMemoryException?
List<Bitmap> bitmapList = new List<Bitmap>();
try
{
for (int i = 0; i < 1000; ++i)
{
using (Bitmap bitmap = new Bitmap(#"C:\temp\test.gif"))
//using (Bitmap bitmap = new Bitmap(bitmap2))
{
Bitmap clonedBitmap = bitmap.Clone(new Rectangle(0, 0, bitmap.Width, bitmap.Height), PixelFormat.Format8bppIndexed);
bitmapList.Add(clonedBitmap);
Debug.WriteLine("round " + i);
}
}
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
finally
{
foreach (Bitmap bitmap in bitmapList)
{
bitmap.Dispose();
}
}
The exception is first thrown around round 95 (sometimes round 94 or 96), so the code works quite a few times before failing. The original GIF image is not very big so I cannot believe it is a real out of memory condition. I know that GDI+ maps many error conditions to OutOfMemoryException but what is the real underlying cause?
If I uncomment the second using line and change the file bitmap name to bitmap2, i.e. I create a new temporary bitmap which I then clone then the code works ok. Why?
using (Bitmap bitmap2 = new Bitmap(#"C:\temp\test.gif"))
using (Bitmap bitmap = new Bitmap(bitmap2))
{
The HResult in the exception is 0x8007000e which according to Microsoft documentation can mean out of memory condition among many other things. Maybe some native resource problem but why should it manifest like this and be corrected by making an extra bitmap?
The cause is not the GIF image format either, I have tried with JPG and PNG images and the same problem appears.
My real purpose is to convert 24-bit RGB bitmaps to indexed 8-bit bitmaps. The resulting image from Clone is not very high quality though. Anybody know some better quality way to convert to 8-bit indexed bitmap or do I have to do it all myself from scratch including palette quantization?

OutOfMemoryException using Bitmap to resize large image

I want to resize the image in my website, but when I using Bitmap to load a image of 14032*19864(png extension), an OutOfMemoryException is thrown. My compiler configuration is any cpu.
I was doubting whether the running environment is x64.
the code is below:
public ActionResult BimDWGViewer()
{
Viewer.Uri uri = null;
string url = Request.Params["u"];
uri = new Viewer.Uri("image#"+url);
int width = Int32.Parse(Request.Params["w"]);
int height = Int32.Parse(Request.Params["h"]);
Nebula.Nexus.Helpers.ModelUriTranslator.TranslateUri(uri);
if (uri.IsFileProtocol)
{
string path = uri.Path;
System.Drawing.Bitmap image_source = new System.Drawing.Bitmap(path);
System.Drawing.Bitmap image_result = new System.Drawing.Bitmap(width,height);
using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(image_result))
{
g.DrawImage(image_source, new System.Drawing.Rectangle(0, 0, width, height), new System.Drawing.Rectangle(0, 0, image_source.Width, image_source.Height), System.Drawing.GraphicsUnit.Pixel);
}
MemoryStream output = new MemoryStream();
image_result.Save(output, System.Drawing.Imaging.ImageFormat.Png);
byte[] res = output.ToArray();
output.Dispose();
image_source.Dispose();
image_result.Dispose();
return new FileContentResult(res, "image/png");
}
}
The exception occurs in the line of
System.Drawing.Bitmap image_source = new System.Drawing.Bitmap(path);
Make sure you have the gcAllowVeryLargeObjects element set to true in your config file.
There's a 2 GB max for individual allocations in .NET (even when running as a 64-bit process) and it's very possible that one of the classes you're using is doing something internally that bumps into this limit. It's a pretty common problem, and fixing your config file should get you around it.
Update: Per the comments below, the problem that #majing ran into was that Visual Studio was launching his web app in a 32-bit edition of IIS Express. Configuring VS to launch IIS as a 64-bit process fixed the issue.
Have you disabled "Prefer 32 bit"?
See http://www.neovolve.com/2015/07/31/disable-prefer-32-bit/

Unusual Physical memory usage when huge number of bitmap images are created and saved as one bit per pixel image

I am trying to create large number of 1 bit per pixel bmp image from base 64 string and saving. As per the requirement a very huge number of images being created in a short period of time( an average of 50,000 to 1,00,000 in a short duration). I am using the below code.
public void CreateoneBppImageAndSave(String base64ImageString,String ImagePathToSave)
{
byte[] byteArray = Convert.FromBase64String(base64ImageString);
System.Drawing.Image img = byteArrayToImage(byteArray);
Bitmap objBitmap = new Bitmap(img);
BitmapData bmpData = objBitmap.LockBits(new Rectangle(0, 0, objBitmap.Width, objBitmap.Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format1bppIndexed);
Bitmap oneBppBitmap = new Bitmap(objBitmap.Width, objBitmap.Height, bmpData.Stride, System.Drawing.Imaging.PixelFormat.Format1bppIndexed, bmpData.Scan0);
oneBppBitmap.Save(ImagePathToSave, ImageFormat.Bmp);
img.Dispose();
objBitmap.Dispose();
objBitmap.UnlockBits(bmpData);
oneBppBitmap.Dispose();
}
private Image byteArrayToImage(byte[] byteArrayIn)
{
using (MemoryStream ms = new MemoryStream(byteArrayIn))
{
return Image.FromStream(ms);
}
}
Here the physical memory usage going very high. Usually the images are generated with size of 200x200 to 754x1024 . After certain duration physical memory usage reaching to the extreme and out of memory exception is being thrown.The physical memory is getting increased by 0.01 GB by every 5-10 seconds. Please help me to optimize the code in terms of memory usage.
You call LockBits on objBitmap however you call UnlockBits on oneBppBitmap. You should be calling unlock on the same object you called lock on.
As for using statements like I mentioned in the comments, a using statement turns this
using(SomeType obj = new SomeType())
{
// Some code
}
in to the equivalent of this
SomeType obj = new SomeType())
try
{
// Some code
}
finally
{
obj.Dispose();
}
That guarantees that even if a exception is thrown in // Some Code the dispose action will still happen. Your code, as it is right now, will not dispose any of its objects if any of your functions between the creation and dispose throws an exception.
Here is a re-written version with all the corrections I mentioned plus a few others..
public void CreateoneBppImageAndSave(String base64ImageString,String ImagePathToSave)
{
byte[] byteArray = Convert.FromBase64String(base64ImageString);
using(Image img = byteArrayToImage(byteArray))
using(Bitmap objBitmap = new Bitmap(img))
{
BitmapData bmpData = objBitmap.LockBits(new Rectangle(0, 0, objBitmap.Width, objBitmap.Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format1bppIndexed);
try
{
using(Bitmap oneBppBitmap = new Bitmap(objBitmap.Width, objBitmap.Height, bmpData.Stride, System.Drawing.Imaging.PixelFormat.Format1bppIndexed, bmpData.Scan0))
{
oneBppBitmap.Save(ImagePathToSave, ImageFormat.Bmp);
}
}
finally
{
//put the unlock in a finally to make sure it happens.
objBitmap.UnlockBits(bmpData);
}
}
}
EDIT: If this really is in your code
objBitmap.Dispose();
objBitmap.UnlockBits(bmpData);
That is the source of your problem, you should not call any methods on a class after you dispose. That is another benefit of using, you can't call methods late because the variable goes out of scope when you leave the using block.

A Generic error occurred in GDI+ in Bitmap.Save method

I am working on to upload and save a thumbnail copy of that image in a thumbnail folder.
I am using following link:
http://weblogs.asp.net/markmcdonnell/archive/2008/03/09/resize-image-before-uploading-to-server.aspx
but
newBMP.Save(directory + "tn_" + filename);
is causing exception "A generic error occurred in GDI+."
I have tried to give permission on folder, also tried to use a new separate bmp object when saving.
Edit:
protected void ResizeAndSave(PropBannerImage objPropBannerImage)
{
// Create a bitmap of the content of the fileUpload control in memory
Bitmap originalBMP = new Bitmap(fuImage.FileContent);
// Calculate the new image dimensions
int origWidth = originalBMP.Width;
int origHeight = originalBMP.Height;
int sngRatio = origWidth / origHeight;
int thumbWidth = 100;
int thumbHeight = thumbWidth / sngRatio;
int bannerWidth = 100;
int bannerHeight = bannerWidth / sngRatio;
// Create a new bitmap which will hold the previous resized bitmap
Bitmap thumbBMP = new Bitmap(originalBMP, thumbWidth, thumbHeight);
Bitmap bannerBMP = new Bitmap(originalBMP, bannerWidth, bannerHeight);
// Create a graphic based on the new bitmap
Graphics oGraphics = Graphics.FromImage(thumbBMP);
// Set the properties for the new graphic file
oGraphics.SmoothingMode = SmoothingMode.AntiAlias; oGraphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
// Draw the new graphic based on the resized bitmap
oGraphics.DrawImage(originalBMP, 0, 0, thumbWidth, thumbHeight);
Bitmap newBitmap = new Bitmap(thumbBMP);
thumbBMP.Dispose();
thumbBMP = null;
// Save the new graphic file to the server
newBitmap.Save("~/image/thumbs/" + "t" + objPropBannerImage.ImageId, ImageFormat.Jpeg);
oGraphics = Graphics.FromImage(bannerBMP);
// Set the properties for the new graphic file
oGraphics.SmoothingMode = SmoothingMode.AntiAlias; oGraphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
// Draw the new graphic based on the resized bitmap
oGraphics.DrawImage(originalBMP, 0, 0, bannerWidth, bannerHeight);
// Save the new graphic file to the server
bannerBMP.Save("~/image/" + objPropBannerImage.ImageId + ".jpg");
// Once finished with the bitmap objects, we deallocate them.
originalBMP.Dispose();
bannerBMP.Dispose();
oGraphics.Dispose();
}
When either a Bitmap object or an Image object is constructed from a
file, the file remains locked for the lifetime of the object. As a
result, you cannot change an image and save it back to the same file
where it originated.
http://support.microsoft.com/?id=814675
A generic error occurred in GDI+, JPEG Image to MemoryStream
Image.Save(..) throws a GDI+ exception because the memory stream is closed
http://alperguc.blogspot.in/2008/11/c-generic-error-occurred-in-gdi.html
EDIT:
just writing from memory...
save to an 'intermediary' memory stream, that should work
e.g. try this one - replace
Bitmap newBitmap = new Bitmap(thumbBMP);
thumbBMP.Dispose();
thumbBMP = null;
newBitmap.Save("~/image/thumbs/" + "t" + objPropBannerImage.ImageId, ImageFormat.Jpeg);
with something like:
string outputFileName = "...";
using (MemoryStream memory = new MemoryStream())
{
using (FileStream fs = new FileStream(outputFileName, FileMode.Create, FileAccess.ReadWrite))
{
thumbBMP.Save(memory, ImageFormat.Jpeg);
byte[] bytes = memory.ToArray();
fs.Write(bytes, 0, bytes.Length);
}
}
This error message is displayed if the path you pass to Bitmap.Save() is invalid (folder doesn't exist etc).
// Once finished with the bitmap objects, we deallocate them.
originalBMP.Dispose();
bannerBMP.Dispose();
oGraphics.Dispose();
This is a programming style that you'll regret sooner or later. Sooner is knocking on the door, you forgot one. You are not disposing newBitmap. Which keeps a lock on the file until the garbage collector runs. If it doesn't run then the second time you try to save to the same file you'll get the klaboom. GDI+ exceptions are too miserable to give a good diagnostic so serious head-scratching ensues. Beyond the thousands of googlable posts that mention this mistake.
Always favor using the using statement. Which never forgets to dispose an object, even if the code throws an exception.
using (var newBitmap = new Bitmap(thumbBMP)) {
newBitmap.Save("~/image/thumbs/" + "t" + objPropBannerImage.ImageId, ImageFormat.Jpeg);
}
Albeit that it is very unclear why you even create a new bitmap, saving thumbBMP should already be good enough. Anyhoo, give the rest of your disposable objects the same using love.
In my case the bitmap image file already existed in the system drive, so my app threw the error "A Generic error occured in GDI+".
Verify that the destination folder exists
Verify that there isn't already a file with the same name in the destination folder
Check your folder's permission where the image is saved
Right cLick on folder then go :
Properties > Security > Edit > Add-- select "everyone" and check Allow "Full Control"
I was facing the same issue A generic error occurred in GDI+ on saving while working on MVC app, I was getting this error because I was writing wrong path to save image, I corrected saving path and it worked fine for me.
img1.Save(Server.MapPath("/Upload/test.png", System.Drawing.Imaging.ImageFormat.Png);
--Above code need one change, as you need to put close brackets on Server.MapPath() method after writing its param.
Like this-
img1.Save(Server.MapPath("/Upload/test.png"), System.Drawing.Imaging.ImageFormat.Png);
GDI+ exceptions occured due to below points
Folder access issue
Missing properties of images
If folder issue - please provide access to application
If Missing properties then use below code
Code 1
using (Bitmap bmp = new Bitmap(webStream))
{
using (Bitmap newImage = new Bitmap(bmp))
{
newImage.Save("c:\temp\test.jpg", ImageFormat.Jpeg);
}
}
Code 2
using (Bitmap bmp = new Bitmap(webStream))
{
using (Bitmap newImage = new Bitmap(bmp))
{
newImage.SetResolution(bmp.HorizontalResolution, bmp.VerticalResolution);
Rectangle lockedRect = new Rectangle(0, 0, bmp.Width, bmp.Height);
BitmapData bmpData = newImage.LockBits(lockedRect, ImageLockMode.ReadWrite, bmp.PixelFormat);
bmpData.PixelFormat = bmp.PixelFormat;
newImage.UnlockBits(bmpData);
using (Graphics gr = Graphics.FromImage(newImage))
{
gr.SmoothingMode = SmoothingMode.HighQuality;
gr.InterpolationMode = InterpolationMode.HighQualityBicubic;
gr.PixelOffsetMode = PixelOffsetMode.HighQuality;
}
foreach (var item in bmp.PropertyItems)
{
newImage.SetPropertyItem(item);
}
newImage.Save("c:\temp\test.jpg", ImageFormat.Jpeg);
}
}
Different between code 1 and code 2
Code - 1 : it will just create image and can open it on normal image viewer
the image can't open in Photoshop
Image size will be double
Code - 2 : to open image in image edition tools use code
by using code 1 it just create images but it not assign image marks.
I always check/test these:
Does the path + filename contain illegal characters for the given filesystem?
Does the file already exist? (Bad)
Does the path already exist? (Good)
If the path is relative: am I expecting it in the right parent directory (mostly bin/Debug ;-) )?
Is the path writable for the program and as which user does it run? (Services can be tricky here!)
Does the full path really, really not contain illegal chars? (some unicode chars are close to invisible)
I never had any problems with Bitmap.Save() apart from this list.
I had a different issue with the same exception.
In short:
Make sure that the Bitmap's object Stream is not being disposed before calling .Save .
Full story:
There was a method that returned a Bitmap object, built from a MemoryStream in the following way:
private Bitmap getImage(byte[] imageBinaryData){
.
.
.
Bitmap image;
using (var stream = new MemoryStream(imageBinaryData))
{
image = new Bitmap(stream);
}
return image;
}
then someone used the returned image to save it as a file
image.Save(path);
The problem was that the original stream was already disposed when trying to save the image, throwing the GDI+ exeption.
A fix to this problem was to return the Bitmap without disposing the stream itself but the returned Bitmap object.
private Bitmap getImage(byte[] imageBinaryData){
.
.
.
Bitmap image;
var stream = new MemoryStream(imageBinaryData))
image = new Bitmap(stream);
return image;
}
then:
using (var image = getImage(binData))
{
image.Save(path);
}
I got it working using FileStream, get help from these
http://alperguc.blogspot.in/2008/11/c-generic-error-occurred-in-gdi.html
http://csharpdotnetfreak.blogspot.com/2010/02/resize-image-upload-ms-sql-database.html
System.Drawing.Image imageToBeResized = System.Drawing.Image.FromStream(fuImage.PostedFile.InputStream);
int imageHeight = imageToBeResized.Height;
int imageWidth = imageToBeResized.Width;
int maxHeight = 240;
int maxWidth = 320;
imageHeight = (imageHeight * maxWidth) / imageWidth;
imageWidth = maxWidth;
if (imageHeight > maxHeight)
{
imageWidth = (imageWidth * maxHeight) / imageHeight;
imageHeight = maxHeight;
}
Bitmap bitmap = new Bitmap(imageToBeResized, imageWidth, imageHeight);
System.IO.MemoryStream stream = new MemoryStream();
bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
stream.Position = 0;
byte[] image = new byte[stream.Length + 1];
stream.Read(image, 0, image.Length);
System.IO.FileStream fs
= new System.IO.FileStream(Server.MapPath("~/image/a.jpg"), System.IO.FileMode.Create
, System.IO.FileAccess.ReadWrite);
fs.Write(image, 0, image.Length);
For me it was a permission problem. Somebody removed write permissions on the folder for the user account under which the application was running.
Create folder path image/thumbs on your hard disk => Problem solved!
I used below logic while saving a .png format. This is to ensure the file is already existing or not.. if exist then saving it by adding 1 in the filename
Bitmap btImage = new Bitmap("D:\\Oldfoldername\\filename.png");
string path="D:\\Newfoldername\\filename.png";
int Count=0;
if (System.IO.File.Exists(path))
{
do
{
path = "D:\\Newfoldername\\filename"+"_"+ ++Count + ".png";
} while (System.IO.File.Exists(path));
}
btImage.Save(path, System.Drawing.Imaging.ImageFormat.Png);
I encountered this error while trying to convert Tiff images to Jpeg. For me the issue stemmed from the tiff dimensions being too large. Anything up to around 62000 pixels was fine, anything above this size produced the error.
for me it was a path issue when saving the image.
int count = Directory.EnumerateFiles(System.Web.HttpContext.Current.Server.MapPath("~/images/savedimages"), "*").Count();
var img = Base64ToImage(imgRaw);
string path = "images/savedimages/upImages" + (count + 1) + ".png";
img.Save(Path.Combine(System.Web.HttpContext.Current.Server.MapPath(path)));
return path;
So I fixed it by adding the following forward slash
String path = "images/savedimages....
should be
String path = "/images/savedimages....
Hope that helps anyone stuck!
from msdn: public void Save (string filename); which is quite surprising to me because we dont just have to pass in the filename, we have to pass the filename along with the path for example: MyDirectory/MyImage.jpeg, here MyImage.jpeg does not actually exist yet, but our file will be saved with this name.
Another important point here is that if you are using Save() in a web application then use Server.MapPath() along with it which basically just returns the physical path for the virtual path which is passed in. Something like: image.Save(Server.MapPath("~/images/im111.jpeg"));
I use this solution
int G = 0;
private void toolStripMenuItem17_Click(object sender, EventArgs e)
{
Directory.CreateDirectory("picture");// هذه العملية للرسم بدون ان يحذف بقية الرسومات
G = G + 1;
FormScreen();
memoryImage1.Save("picture\\picture" + G.ToString() + ".jpg");
pictureBox1.Image = Image.FromFile("picture\\picture" + G.ToString() + ".jpg");
}
The code below solved my problem
pictureBox1.Image=myImage;
Bitmap bmp = new Bitmap(pictureBox1.Image);
bmp.Save("C:\\Users/super/Desktop/robin.jpg");

Image from webcam preview throws generic GDI+ exception

I'm making a custom webcam user control.
I use Microsoft Expression Encoder, and set a PreviewWindow on a panel inside the control.
All's fine, except that when I try to grab the image, I get an exception:
Generic GDI+ exception
My first try was:
using (var bmp = new Bitmap(p.Width, p.Width))
{
panel1.DrawToBitmap(bmp, new Rectangle(0, 0, bmp.Width, bmp.Height));
bmp.Save(#"c:\test.png");
}
Another waS:
using (Bitmap bitmap = new Bitmap(panelVideoPreview.Width, panelVideoPreview.Height))
{
using (Graphics g = Graphics.FromImage(bitmap))
{
Rectangle rectanglePanelVideoPreview = panelVideoPreview.Bounds;
Point sourcePoints = panelVideoPreview.PointToScreen(new Point(panelVideoPreview.ClientRectangle.X, panelVideoPreview.ClientRectangle.Y));
g.CopyFromScreen(sourcePoints, Point.Empty, rectanglePanelVideoPreview.Size);
}
string strGrabFileName = String.Format("C:\\Snapshot.jpg", DateTime.Now);
bitmap.Save(strGrabFileName, ImageFormat.Jpeg);
The problem is in writing the file.
There may not be enough space in c:\ drive or you do not have permission to write to c:\ drive(outside a folder).
Try writing to AppData ,if you want to write to c:\ drive,you need to acquire administrative privileges by using a custom manifest.

Categories

Resources