A Generic error occurred in GDI+ in Bitmap.Save method - c#

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");

Related

A generic error occured in GDI+

I'm attempting to resize and image using the following function and receiving this error:
Exception Details: System.Runtime.InteropServices.ExternalException: A generic error occurred in GDI+.
on this line:
imageConvertedToBitmap.Save(cachedFileName, info[1], encoderParameters);
Any ideas why this might be happening?
private byte[] GetCachedImage(string cachedFileName, string pathToImage, int width, int height)
{
if (!System.IO.File.Exists(cachedFileName) || (System.IO.File.GetLastWriteTime(pathToImage) > System.IO.File.GetLastWriteTime(cachedFileName)))
{
Image imageToResize = Image.FromFile(pathToImage);
Image imageConvertedToBitmap = new Bitmap(width, height);
Graphics graphicsController = Graphics.FromImage(imageConvertedToBitmap);
graphicsController.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphicsController.SmoothingMode = SmoothingMode.HighQuality;
graphicsController.PixelOffsetMode = PixelOffsetMode.HighQuality;
graphicsController.CompositingQuality = CompositingQuality.HighQuality;
graphicsController.DrawImage(imageToResize, 0, 0, width, height);
EncoderParameters parameters = new EncoderParameters(1);
parameters.Param[0] = new EncoderParameter(Encoder.Quality, 80L);
ImageCodecInfo[] info = ImageCodecInfo.GetImageEncoders();
EncoderParameters encoderParameters = new EncoderParameters(1);
encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, 80L);
MemoryStream memoryStream = new MemoryStream();
imageConvertedToBitmap.Save(cachedFileName, info[1], encoderParameters);
imageConvertedToBitmap.Save(memoryStream, info[1], encoderParameters);
imageToResize.Dispose();
imageConvertedToBitmap.Dispose();
graphicsController.Dispose();
parameters.Dispose();
encoderParameters.Dispose();
return memoryStream.GetBuffer();
}
byte[] buffer = null;
try
{
FileStream fileStream = new FileStream(cachedFileName, FileMode.Open, FileAccess.Read);
BinaryReader binaryReader = new BinaryReader(fileStream);
long totalBytes = new FileInfo(cachedFileName).Length;
buffer = binaryReader.ReadBytes((Int32)totalBytes);
fileStream.Close();
fileStream.Dispose();
binaryReader.Close();
}
catch { }
return buffer;
}
It was a permissions error. Had to give appropriate Write permission to the directory I was saving to. Sometimes it's the simple things. :)
From what I read, when getting this GDI+ error, the first thing to check should be permissions as it's almost always an indicator of a security problem.
Try an overload of Save that doesn't take EncoderParameters as a parameter. It should work fine and produce the resized image that you're looking for.
I had this error one time, it was because I tried to save under a locked file by a Bitmap object.
We just see your method but not how you use it.
I think there are several syntax problems in your code : you must use "using() { }" for all the disable objects in your code.
using(Image imageToResize = Image.FromFile(pathToImage))
using(Image imageConvertedToBitmap = new Bitmap(width, height))
etc.
{
}
Your got this error on another instance.
Firstly understand what this error means the other way:
When you get the error, go to task manager and navigate to Details tab.
Right click on the table headers and click select columns.
Tick the GDI objects checkbox.
Now find the name of your program in the table and check the no. of GDI objects.
It would have exceeded 10000 or must be at 10000.
The error pops up whenever the no. of GDI objects by a program exceeds
10000 as 10000 is the limit.
Check how many times the System.Drawing.... runs in your code.
Prevent objects like Fonts or Images from being created again and again.
Instead set a reference point.

Free file locked by new Bitmap(filePath)

I have the Image of a PictureBox pointing to a certain file "A". At execution time I want to change the Image of the PictureBox to a different one "B" but I get the following error:
"A first chance exception of type 'System.IO.IOException' occurred in mscorlib.dll
Additional information: The process cannot access the file "A" because it is being used by another process."
I'm setting the Image as follows:
pbAvatar.Image = new Bitmap(filePath);
How can I unlock the first file?
Here is my approach to opening an image without locking the file...
public static Image FromFile(string path)
{
var bytes = File.ReadAllBytes(path);
var ms = new MemoryStream(bytes);
var img = Image.FromStream(ms);
return img;
}
UPDATE: I did some perf tests to see which method was the fastest. I compared it to #net_progs "copy from bitmap" answer (which seems to be the closest to correct, though does have some issues). I loaded the image 10000 times for each method and calculated the average time per image. Here are the results:
Loading from bytes: ~0.26 ms per image.
Copying from bitmap: ~0.50 ms per image.
The results seem to make sense since you have to create the image twice using the copy from bitmap method.
UPDATE:
if you need a BitMap you can do:
return (Bitmap)Image.FromStream(ms);
This is a common locking question widely discussed over the web.
The suggested trick with stream will not work, actually it works initially, but causes problems later. For example, it will load the image and the file will remain unlocked, but if you try to save the loaded image via Save() method, it will throw a generic GDI+ exception.
Next, the way with per pixel replication doesn't seem to be solid, at least it is noisy.
What I found working is described here: http://www.eggheadcafe.com/microsoft/Csharp/35017279/imagefromfile--locks-file.aspx
This is how the image should be loaded:
Image img;
using (var bmpTemp = new Bitmap("image_file_path"))
{
img = new Bitmap(bmpTemp);
}
I was looking for a solution to this problem and this method works fine for me so far, so I decided to describe it, since I found that many people advise the incorrect stream approach here and over the web.
Using a filestream will unlock the file once it has been read from and disposed:
using (var fs = new System.IO.FileStream("c:\\path to file.bmp", System.IO.FileMode.Open))
{
var bmp = new Bitmap(fs);
pct.Image = (Bitmap) bmp.Clone();
}
Edit: Updated to allow the original bitmap to be disposed, and allow the FileStream to be closed.
THIS ANSWER IS NOT SAFE - See comments, and see discussion in net_prog's answer. The Edit to use Clone does not make it any safer - Clone clones all fields, including the filestream reference, which in certain circumstances will cause a problem.
You can't dispose / close a stream while a bitmap object is still using it. (Whether the bitmap object will need access to it again is only deterministic if you know what type of file you are working with and exactly what operations you will be performing. -- for example for SOME .gif format images, the stream is closed before the constructor returns.)
Clone creates an "exact copy" of the bitmap (per documentation; ILSpy shows it calling native methods, so it's too much to track down right now) likely, it copies that Stream data as well -- or else it wouldn't be an exact copy.
Your best bet is creating a pixel-perfect replica of the image -- though YMMV (with certain types of images there may be more than one frame, or you may have to copy palette data as well.) But for most images, this works:
static Bitmap LoadImage(Stream stream)
{
Bitmap retval = null;
using (Bitmap b = new Bitmap(stream))
{
retval = new Bitmap(b.Width, b.Height, b.PixelFormat);
using (Graphics g = Graphics.FromImage(retval))
{
g.DrawImage(b, Point.Empty);
g.Flush();
}
}
return retval;
}
And then you can invoke it like such:
using (Stream s = ...)
{
Bitmap x = LoadImage(s);
}
As far as I know, this is 100% safe, since the resulting image is 100% created in memory, without any linked resources, and with no open streams left behind in memory. It acts like any other Bitmap that's created from a constructor that doesn't specify any input sources, and unlike some of the other answers here, it preserves the original pixel format, meaning it can be used on indexed formats.
Based on this answer, but with extra fixes and without external library import.
/// <summary>
/// Clones an image object to free it from any backing resources.
/// Code taken from http://stackoverflow.com/a/3661892/ with some extra fixes.
/// </summary>
/// <param name="sourceImage">The image to clone</param>
/// <returns>The cloned image</returns>
public static Bitmap CloneImage(Bitmap sourceImage)
{
Rectangle rect = new Rectangle(0, 0, sourceImage.Width, sourceImage.Height);
Bitmap targetImage = new Bitmap(rect.Width, rect.Height, sourceImage.PixelFormat);
targetImage.SetResolution(sourceImage.HorizontalResolution, sourceImage.VerticalResolution);
BitmapData sourceData = sourceImage.LockBits(rect, ImageLockMode.ReadOnly, sourceImage.PixelFormat);
BitmapData targetData = targetImage.LockBits(rect, ImageLockMode.WriteOnly, targetImage.PixelFormat);
Int32 actualDataWidth = ((Image.GetPixelFormatSize(sourceImage.PixelFormat) * rect.Width) + 7) / 8;
Int32 h = sourceImage.Height;
Int32 origStride = sourceData.Stride;
Boolean isFlipped = origStride < 0;
origStride = Math.Abs(origStride); // Fix for negative stride in BMP format.
Int32 targetStride = targetData.Stride;
Byte[] imageData = new Byte[actualDataWidth];
IntPtr sourcePos = sourceData.Scan0;
IntPtr destPos = targetData.Scan0;
// Copy line by line, skipping by stride but copying actual data width
for (Int32 y = 0; y < h; y++)
{
Marshal.Copy(sourcePos, imageData, 0, actualDataWidth);
Marshal.Copy(imageData, 0, destPos, actualDataWidth);
sourcePos = new IntPtr(sourcePos.ToInt64() + origStride);
destPos = new IntPtr(destPos.ToInt64() + targetStride);
}
targetImage.UnlockBits(targetData);
sourceImage.UnlockBits(sourceData);
// Fix for negative stride on BMP format.
if (isFlipped)
targetImage.RotateFlip(RotateFlipType.Rotate180FlipX);
// For indexed images, restore the palette. This is not linking to a referenced
// object in the original image; the getter of Palette creates a new object when called.
if ((sourceImage.PixelFormat & PixelFormat.Indexed) != 0)
targetImage.Palette = sourceImage.Palette;
// Restore DPI settings
targetImage.SetResolution(sourceImage.HorizontalResolution, sourceImage.VerticalResolution);
return targetImage;
}
To call, simply use:
/// <summary>Loads an image without locking the underlying file.</summary>
/// <param name="path">Path of the image to load</param>
/// <returns>The image</returns>
public static Bitmap LoadImageSafe(String path)
{
using (Bitmap sourceImage = new Bitmap(path))
{
return CloneImage(sourceImage);
}
}
Or, from bytes:
/// <summary>Loads an image from bytes without leaving open a MemoryStream.</summary>
/// <param name="fileData">Byte array containing the image to load.</param>
/// <returns>The image</returns>
public static Bitmap LoadImageSafe(Byte[] fileData)
{
using (MemoryStream stream = new MemoryStream(fileData))
using (Bitmap sourceImage = new Bitmap(stream)) {
{
return CloneImage(sourceImage);
}
}
Here's the technique I'm currently using, and seems to work best. It has the advantage of producing a Bitmap object with the same pixel format (24-bit or 32-bit) and resolution (72 dpi, 96 dpi, whatever) as the source file.
// ImageConverter object used to convert JPEG byte arrays into Image objects. This is static
// and only gets instantiated once.
private static readonly ImageConverter _imageConverter = new ImageConverter();
This can be used as often as needed, as follows:
Bitmap newBitmap = (Bitmap)_imageConverter.ConvertFrom(File.ReadAllBytes(fileName));
Edit:
Here's an update of the above technique: https://stackoverflow.com/a/16576471/253938
(The accepted answer is wrong. When you try to LockBits(...) on the cloned bitmap eventually you will encounter GDI+ errors.)
I see only 3 ways to get out of this:
copy your file to a temporary file and open that the easy way new Bitmap(temp_filename)
open your file, read image, create a pixel-size-pixelformat copy (don't Clone()) and dispose the first bitmap
(accept the locked-file-feature)
I suggest to use PixelMap which is available on NuGet
Very easy to use and much faster than standard Bitmap from .NET
PixelMap pixelMap = new PixelMap(path);
pictureBox1.Image = pixelMap.GetBitmap();
Read it into the stream, create bitmap, close the stream.

Generic exception when trying to save uploaded image file

When trying to save an uploaded file, I get this error and are having some difficulties solving it:
ExternalException: A generic error occurred in GDI+.
It's a very specific exception message!
This is my code.
// Gets the original image.
byte[] original = new byte[file.InputStream.Length];
file.InputStream.Position = 0;
file.InputStream.Read(original, 0, (int)file.InputStream.Length);
// Redimensions the original image and saves it for each of the desired pictures classes.
foreach (ClassDetails c in picturesClasses)
{
byte[] resized = Images.Resize(original, new Size(c.Width, c.Height), c.ResizeToExactProportions);
MemoryStream stream = new MemoryStream(resized);
Image resizedImage = Image.FromStream(stream);
uniqueFilename = string.Format("{0}{1}{2}", Path.GetFileNameWithoutExtension(file.FileName), Guid.NewGuid().ToString(), ".png");
// The exception happens HERE **************************************************
resizedImage.Save(Path.Combine(c.Path, uniqueFilename), ImageFormat.Png);
}
Please, any idea of what could be wrong? Thanks.
Mmm... I love it when problems are solved fast!
The path I had was a relative one. I had to use the Server.MapPath method. See below:
resizedImage.Save(HttpContext.Current.Server.MapPath(Path.Combine(c.Path, uniqueFilename)), ImageFormat.Png);

Create a new image on the file system from System.Drawing.Image?

Ok, I'm sorry, this is probably a noob question but I'm kinda stuck.
So what I'm doing (on my asp.net application) is loading an image from the file system:
System.Drawing.Image tempImage;
tempImage = System.Drawing.Image.FromFile(HttpContext.Server.MapPath(originalPath));
Then I do some resizing:
tempImage = my awesomeResizingFunction(tempImage, newSize);
and intend to save it to the file system in another location using this:
string newPath = "/myAwesomePath/newImageName.jpg";
tempImage.Save(newPath);
and what I get is this error:
"A generic error occurred in GDI+."
I know the image is "ok" because I can write it out to the browser and see the resized image, I only get the error when I try to save it. I'm kinda new and stuck, am I doing this totally wrong? (Well, i guess that's obvious but you know what I mean...)
Try this code... I have used the same code for resizing image and saving.
System.Drawing.Bitmap bmpOut = new System.Drawing.Bitmap(NewWidth, NewHeight);
System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bmpOut);
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
g.FillRectangle(System.Drawing.Brushes.White, 0, 0, NewWidth, NewHeight);
g.DrawImage(new System.Drawing.Bitmap(fupProduct.PostedFile.InputStream), 0, 0, NewWidth, NewHeight);
MemoryStream stream = new MemoryStream();
switch (fupProduct.FileName.Substring(fupProduct.FileName.IndexOf('.') + 1).ToLower())
{
case "jpg":
bmpOut.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
break;
case "jpeg":
bmpOut.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
break;
case "tiff":
bmpOut.Save(stream, System.Drawing.Imaging.ImageFormat.Tiff);
break;
case "png":
bmpOut.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
break;
case "gif":
bmpOut.Save(stream, System.Drawing.Imaging.ImageFormat.Gif);
break;
}
String saveImagePath = Server.MapPath("../") + "Images/Thumbnail/" + fupProduct.FileName.Substring(fupProduct.FileName.IndexOf('.'));
bmpOut.Save(saveImagePath);
where fupProduct is fileupload control ID
Are you sure that the originalPath and newPath point to different files ? When you use Image.FromFile, the file remains locked until you call Dispose on the Image, which can lead to the exception you mentioned. You could load the image like that instead :
Image tempImage = null;
using (FileStream fs = new FileStream(originalPath, FileMode.Open, FileAccess.Read))
{
tempImage = Image.FromStream(fs);
}
...
This approach guarantees that the file is closed at the end of the using block
Is it possible the original stream backing the original image has been closed? If the stream behind a Bitmap has been closed, you start getting GDI+ errors. I ran into this a lot when we added image processing to our website.
If you open up the Bitmap object in the Visual Studio debugger, do you see exceptions instead of the values of the properties? If so, it's not a problem with the save operation, but the GDI+ layer has lost the ability to process the object, period.
What I found was I needed to keep track of the MemoryStreams belonging to my Bitmaps and keep them all together. Resizing an image resulted in a new MemoryStream with a new Bitmap image.
I ended up creating this simple class (trimmed some extra properties unneeded here):
public class UploadedImage : IDisposable
{
private Bitmap _img = null;
private Stream _baseStream = null;
/// <summary>
/// The image object. This must always belong to BaseStream, or weird things can happen.
/// </summary>
public Bitmap Img
{
[DebuggerStepThrough]
get { return _img; }
[DebuggerStepThrough]
set { _img = value; }
}
/// <summary>
/// The stream that stores the image. This must ALWAYS belong to Img, or weird things can happen.
/// </summary>
public Stream BaseStream
{
[DebuggerStepThrough]
get { return _baseStream; }
[DebuggerStepThrough]
set { _baseStream = value; }
}
[DebuggerStepThrough]
public void Dispose()
{
if (Img != null)
Img.Dispose();
if (BaseStream != null)
BaseStream.Close();
_attached = false;
}
}
Now, I was dealing with images uploaded to our website, and what I found was that when Asp.Net recycled the stream attached to the Request, all the sudden image operations started flipping out. So, my solution, whether this was the best way to do it or not, was to copy the data from the upload stream to my own MemoryStream, load the image from that, and stick both into this container. And wherever I created a new image from an old one, I always kept the stream and the image together.
I hope this helps.
EDIT: I'm also interested in seeing how you're doing the image resizing. This is a snippet of how I did ours:
temp = new Bitmap(newWidth, newHeight, PIXEL_FORMAT);
temp.SetResolution(newHorizontalRes, newVerticalRes);
gr = Graphics.FromImage(temp);
//
// This copies the active frame from 'img' to the new 'temp' bitmap.
// Also resizes it and makes it super shiny. Sparkle on, mr image dude.
//
Rectangle rect = new Rectangle(0, 0, newWidth, newHeight);
gr.InterpolationMode = InterpolationMode.HighQualityBicubic;
gr.SmoothingMode = SmoothingMode.HighSpeed;
gr.PageUnit = GraphicsUnit.Pixel;
gr.DrawImage(img, rect);
//
// Image copied onto the new bitmap. Save the bitmap to a fresh memory stream.
//
retval = new UploadedImage();
retval.BaseStream = (Stream)(new MemoryStream());
temp.Save(retval.BaseStream, ImageFormat.Jpeg);
retval.Img = temp;

Image.Save(..) throws a GDI+ exception because the memory stream is closed

i've got some binary data which i want to save as an image. When i try to save the image, it throws an exception if the memory stream used to create the image, was closed before the save. The reason i do this is because i'm dynamically creating images and as such .. i need to use a memory stream.
this is the code:
[TestMethod]
public void TestMethod1()
{
// Grab the binary data.
byte[] data = File.ReadAllBytes("Chick.jpg");
// Read in the data but do not close, before using the stream.
Stream originalBinaryDataStream = new MemoryStream(data);
Bitmap image = new Bitmap(originalBinaryDataStream);
image.Save(#"c:\test.jpg");
originalBinaryDataStream.Dispose();
// Now lets use a nice dispose, etc...
Bitmap2 image2;
using (Stream originalBinaryDataStream2 = new MemoryStream(data))
{
image2 = new Bitmap(originalBinaryDataStream2);
}
image2.Save(#"C:\temp\pewpew.jpg"); // This throws the GDI+ exception.
}
Does anyone have any suggestions to how i could save an image with the stream closed? I cannot rely on the developers to remember to close the stream after the image is saved. In fact, the developer would have NO IDEA that the image was generated using a memory stream (because it happens in some other code, elsewhere).
I'm really confused :(
As it's a MemoryStream, you really don't need to close the stream - nothing bad will happen if you don't, although obviously it's good practice to dispose anything that's disposable anyway. (See this question for more on this.)
However, you should be disposing the Bitmap - and that will close the stream for you. Basically once you give the Bitmap constructor a stream, it "owns" the stream and you shouldn't close it. As the docs for that constructor say:
You must keep the stream open for the
lifetime of the Bitmap.
I can't find any docs promising to close the stream when you dispose the bitmap, but you should be able to verify that fairly easily.
A generic error occurred in GDI+.
May also result from incorrect save path!
Took me half a day to notice that.
So make sure that you have double checked the path to save the image as well.
Perhaps it is worth mentioning that if the C:\Temp directory does not exist, it will also throw this exception even if your stream is still existent.
Copy the Bitmap. You have to keep the stream open for the lifetime of the bitmap.
When drawing an image: System.Runtime.InteropServices.ExternalException: A generic error occurred in GDI
public static Image ToImage(this byte[] bytes)
{
using (var stream = new MemoryStream(bytes))
using (var image = Image.FromStream(stream, false, true))
{
return new Bitmap(image);
}
}
[Test]
public void ShouldCreateImageThatCanBeSavedWithoutOpenStream()
{
var imageBytes = File.ReadAllBytes("bitmap.bmp");
var image = imageBytes.ToImage();
image.Save("output.bmp");
}
I had the same problem but actually the cause was that the application didn't have permission to save files on C. When I changed to "D:\.." the picture has been saved.
You can try to create another copy of bitmap:
using (var memoryStream = new MemoryStream())
{
// write to memory stream here
memoryStream.Position = 0;
using (var bitmap = new Bitmap(memoryStream))
{
var bitmap2 = new Bitmap(bitmap);
return bitmap2;
}
}
This error occurred to me when I was trying from Citrix. The image folder was set to C:\ in the server, for which I do not have privilege. Once the image folder was moved to a shared drive, the error was gone.
A generic error occurred in GDI+. It can occur because of image storing paths issues,I got this error because my storing path is too long, I fixed this by first storing the image in a shortest path and move it to the correct location with long path handling techniques.
I was getting this error, because the automated test I was executing, was trying to store snapshots into a folder that didn't exist. After I created the folder, the error resolved
One strange solution which made my code to work.
Open the image in paint and save it as a new file with same format(.jpg). Now try with this new file and it works. It clearly explains you that the file might be corrupted in someway.
This can help only if your code has every other bugs fixed
It has also appeared with me when I was trying to save an image into path
C:\Program Files (x86)\some_directory
and the .exe wasn't executed to run as administrator, I hope this may help someone who has same issue too.
For me the code below crashed with A generic error occurred in GDI+on the line which Saves to a MemoryStream. The code was running on a web server and I resolved it by stopping and starting the Application Pool that was running the site.
Must have been some internal error in GDI+
private static string GetThumbnailImageAsBase64String(string path)
{
if (path == null || !File.Exists(path))
{
var log = ContainerResolver.Container.GetInstance<ILog>();
log.Info($"No file was found at path: {path}");
return null;
}
var width = LibraryItemFileSettings.Instance.ThumbnailImageWidth;
using (var image = Image.FromFile(path))
{
using (var thumbnail = image.GetThumbnailImage(width, width * image.Height / image.Width, null, IntPtr.Zero))
{
using (var memoryStream = new MemoryStream())
{
thumbnail.Save(memoryStream, ImageFormat.Png); // <= crash here
var bytes = new byte[memoryStream.Length];
memoryStream.Position = 0;
memoryStream.Read(bytes, 0, bytes.Length);
return Convert.ToBase64String(bytes, 0, bytes.Length);
}
}
}
}
I came across this error when I was trying a simple image editing in a WPF app.
Setting an Image element's Source to the bitmap prevents file saving.
Even setting Source=null doesn't seem to release the file.
Now I just never use the image as the Source of Image element, so I can overwrite after editing!
EDIT
After hearing about the CacheOption property(Thanks to #Nyerguds) I found the solution:
So instead of using the Bitmap constructor I must set the Uri after setting CacheOption BitmapCacheOption.OnLoad.(Image1 below is the Wpf Image element)
Instead of
Image1.Source = new BitmapImage(new Uri(filepath));
Use:
var image = new BitmapImage();
image.BeginInit();
image.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
image.CacheOption = BitmapCacheOption.OnLoad;
image.UriSource = new Uri(filepath);
image.EndInit();
Image1.Source = image;
See this: WPF Image Caching
Try this code:
static void Main(string[] args)
{
byte[] data = null;
string fullPath = #"c:\testimage.jpg";
using (MemoryStream ms = new MemoryStream())
using (Bitmap tmp = (Bitmap)Bitmap.FromFile(fullPath))
using (Bitmap bm = new Bitmap(tmp))
{
bm.SetResolution(96, 96);
using (EncoderParameters eps = new EncoderParameters(1))
{
eps.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L);
bm.Save(ms, GetEncoderInfo("image/jpeg"), eps);
}
data = ms.ToArray();
}
File.WriteAllBytes(fullPath, data);
}
private static ImageCodecInfo GetEncoderInfo(string mimeType)
{
ImageCodecInfo[] encoders = ImageCodecInfo.GetImageEncoders();
for (int j = 0; j < encoders.Length; ++j)
{
if (String.Equals(encoders[j].MimeType, mimeType, StringComparison.InvariantCultureIgnoreCase))
return encoders[j];
}
return null;
}
I used imageprocessor to resize images and one day I got "A generic error occurred in GDI+" exception.
After looked up a while I tried to recycle the application pool and bingo it works. So I note it here, hope it help ;)
Cheers
I was getting this error today on a server when the same code worked fine locally and on our DEV server but not on PRODUCTION. Rebooting the server resolved it.
public static byte[] SetImageToByte(Image img)
{
ImageConverter converter = new ImageConverter();
return (byte[])converter.ConvertTo(img, typeof(byte[]));
}
public static Bitmap SetByteToImage(byte[] blob)
{
MemoryStream mStream = new MemoryStream();
byte[] pData = blob;
mStream.Write(pData, 0, Convert.ToInt32(pData.Length));
Bitmap bm = new Bitmap(mStream, false);
mStream.Dispose();
return bm;
}

Categories

Resources