Bitmap.save(): A generic error occurred in GDI+
Try the following code
Dim oBitmap As Bitmap
oBitmap = New Bitmap("c:\\example.jpg")
Dim oGraphic As Graphics
oGraphic = Graphics.FromImage(oBitmap)
Dim oBrush As New SolidBrush(Color.Black)
Dim ofont As New Font("Arial", 8 )
oGraphic.DrawString("Some text to write", ofont, oBrush, 10, 10)
oBitmap.Save("c:\\example.jpg",ImageFormat.Jpeg)
oBitmap.Dispose()
oGraphic.Dispose()
You will get the above mentioned error:A generic error occurred in GDI+. This problem occurs because until the bitmap object is disposed, it creates a lock on the underlying image file. So you can save the newly generated file with different name but not overwrite the file because of lock. Now suppose you want to overwrite the file then create another bitmap from old bitmap. dispose the object of old bitmap, process new bitmap object and save the new bitmap object with original file name. The above chunk of code should be written in the following way.
Dim oBitmap As Bitmap
oBitmap = New Bitmap("c:\\example.jpg")
Dim oGraphic As Graphics
' Here create a new bitmap object of the same height and width of the image.
Dim bmpNew As Bitmap = New Bitmap(oBitmap.Width, oBitmap.Height)
oGraphic = Graphics.FromImage(bmpNew)
oGraphic.DrawImage(oBitmap, New Rectangle(0, 0, _
bmpNew.Width, bmpNew.Height), 0, 0, oBitmap.Width, _
oBitmap.Height, GraphicsUnit.Pixel)
' Release the lock on the image file. Of course,
' image from the image file is existing in Graphics object
oBitmap.Dispose()
oBitmap = bmpNew
Dim oBrush As New SolidBrush(Color.Black)
Dim ofont As New Font("Arial", 8 )
oGraphic.DrawString("Some text to write", ofont, oBrush, 10, 10)
oGraphic.Dispose()
ofont.Dispose()
oBrush.Dispose()
oBitmap.Save("c:\\example.jpg", ImageFormat.Jpeg)
oBitmap.Dispose()
Categories: ASP .Net

Hello everyonethis is very nice code ……………………………—————————————————–BUT IT NOT SOLVED MY PROBLEM—————————————————–My Problem is i have a picture box and that picturebox i draw a multiple image ……and now i want to save that all image in onejpg or another format of image so……HOW CAN I STORE THE ALL IMAGES TO A PERTICULAR IMAGE ………………..any help apriciated ………………if found please reply ……….onlyvish4me@gmail.com
hey man thank a lot bro……u really saved my day..i search a lot on this and found many things but ur solution works for me excelent…
again thx ….
regards,
arpan shah.
Hi I m getting error-a generic error occurred in gdi+ while saving an image to stream
Bitmap b = new Bitmap( w, h, -stride, PixelFormat.Format24bppRgb, (IntPtr) scan0 );
handle.Free();
savedArray = null;
Image old = pictureBox.Image;
pictureBox.Image = b;
stream = new MemoryStream();
b.Save(stream, ImageFormat.Jpeg); // Getting error at this line.
b.Dispose();
I m unable to solve this error.
Any suggestions would be greatly appreciated.
I’m still getting the error
Below is my code,any help would be great
Private Sub savebitmap()
Dim strFile As String = Application.StartupPath + “\” + Patid.ToString + “.png”
Dim originalImage As Image = Image.FromFile(strFile)
Dim tempBmp As New Bitmap(originalImage.Width, originalImage.Height)
Dim g As Graphics = Graphics.FromImage(originalImage)
g.DrawImage(tempBmp, 0, 0, originalImage.Width, originalImage.Height)
originalImage.Dispose()
originalImage = tempBmp
g.Dispose()
originalImage.Save(strFile)
End Sub
Here Is the Sample Code which will be Solved Some Error. By Using this we can not get an Errror Of GDI+ in local host but when we Uploaded into the Web Server it can’t Gives Same error
[WebMethod]
public void SaveImage(String ImageName, Byte[] ByteArray, Int32 Catid, Int32 UserId)
{
SqlCommand cmd = new SqlCommand();
cmd.CommandText = “Insert tbl_ImgSave values(@nam,@catid,@usrid,@imgrate)”;
cmd.Parameters.Add(“@nam”, System.Data.SqlDbType.VarChar, 50).Value = SaveToFolder(ByteArray, ImageName);
cmd.Parameters.Add(“@catid”, System.Data.SqlDbType.Int).Value = Catid;
cmd.Parameters.Add(“@usrid”, System.Data.SqlDbType.Int).Value = UserId;
cmd.Parameters.Add(“@imgrate”, System.Data.SqlDbType.Int).Value = 0;
cmd.Connection = con;
cmd.ExecuteNonQuery();
cmd.Dispose();
con.Close();
}
[WebMethod]
public String SaveToFolder(Byte[] armd, String ImageName)
{
String fn = Guid.NewGuid().ToString() + ImageName.Substring(0) + “.jpg”;
Image newImage = ByteArrayToImage(armd);
//String fn = ImageName + “.jpg”;
String sd = Server.MapPath(“Images”);
if (sd.EndsWith(“\\”) == false)
{
sd += “\\”;
}
sd += fn;
newImage.Save(sd);
return fn;
}
public Image ByteArrayToImage(Byte[] ByteArray)
{
MemoryStream ms = new MemoryStream(ByteArray);
Image ReturnImage = Image.FromStream(ms);
return ReturnImage;
}
Thanks very much – this code was extremely helpful in solving a problem that has been bugging me for a very long time. The way it was written and explained way super. Thanks again
Thanks Jerry Lees. My app was working fine in my development environment, but failed with “A generic error occurred in GDI+. ” whenever I tried to run the published version on the Web server. Gave IIS_USRS write permissions on the folder and all is now good.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string strPathToImage = “captchaimg/captcha.gif”;
string strText = fncDrawCaptcha(Server.MapPath(strPathToImage));
imgCaptcha.ImageUrl = strPathToImage;
Session["strText"] = strText;
}
}
public string fncDrawCaptcha(string path)
{
int[] BackgroundColor = new int[] { 255, 255, 255 };
bool RandomBackgroundNoiseColor = true;
bool RandomTextColor = true;
int[] BackgroundNoiseColor = new int[] { 150, 150, 150 };
int[] TextColor = new int[] { 200, 200, 200 };
HatchStyle BackgroundNoiseTexture = HatchStyle.Min;
int length = 6;
int height = 100;
int width = 200;
width = width + ((length – 6) * 30);
Random ranRotate = new Random();
string strText = System.Guid.NewGuid().ToString();
strText = strText.Replace(“-”, String.Empty);
strText = strText.Substring(0, length);
Bitmap bmpCanvas = new Bitmap(width, height, PixelFormat.Format24bppRgb);
Graphics graCanvas = Graphics.FromImage(bmpCanvas);
RectangleF recF = new RectangleF(0, 0, width, height);
Brush bruBackground = default(Brush);
SolidBrush letterBrush = default(SolidBrush);
graCanvas.TextRenderingHint = TextRenderingHint.AntiAlias;
if (RandomBackgroundNoiseColor == true)
{
bruBackground = new HatchBrush(BackgroundNoiseTexture, Color.FromArgb((ranRotate.Next(0, 255)), (ranRotate.Next(0, 255)), (ranRotate.Next(0, 255))), Color.FromArgb(BackgroundColor[0], BackgroundColor[1], BackgroundColor[2]));
}
else
{
bruBackground = new HatchBrush(BackgroundNoiseTexture, Color.FromArgb(BackgroundNoiseColor[0], BackgroundNoiseColor[1], BackgroundNoiseColor[2]), Color.FromArgb(BackgroundColor[0], BackgroundColor[1], BackgroundColor[2]));
}
graCanvas.FillRectangle(bruBackground, recF);
if (RandomTextColor == true)
{
letterBrush = new SolidBrush(Color.FromArgb((ranRotate.Next(0, 255)), (ranRotate.Next(0, 255)), (ranRotate.Next(0, 255))));
}
else
{
letterBrush = new SolidBrush(Color.FromArgb(TextColor[0], TextColor[1], TextColor[2]));
}
System.Drawing.Drawing2D.Matrix matRotate = new System.Drawing.Drawing2D.Matrix();
int i = 0;
for (i = 0; i <= strText.Length – 1; i++)
{
matRotate.Reset();
int intChars = strText.Length;
int x = width / (intChars + 1) * i;
int y = height / 2;
//matRotate.RotateAt(ranRotate.Next(-30, 30), new PointF(width / (intChars + 1) * i, height * 0.5) );
matRotate.RotateAt(ranRotate.Next(-30, 30), new PointF(x, y));
graCanvas.Transform = matRotate;
if (i == 0)
{
//draw ‘the text on our image
//graCanvas.DrawString(strText.Chars(i), new Font("Comic Sans MS", 25, FontStyle.Italic), letterBrush, width / (intChars + 1) * i, height * 0.4);
graCanvas.DrawString(strText.Substring(i, 1), new Font("Comic Sans MS", 25, FontStyle.Italic), letterBrush, width / (intChars + 1) * i, 40);
}
else if (i == 1)
{
//draw ‘the text on our image
graCanvas.DrawString(strText.Substring(i, 1), new Font("Arial", 30, FontStyle.Bold), letterBrush, width / (intChars + 1) * i, 10);
}
else if (i == 2)
{
//draw ‘the text on our image
graCanvas.DrawString(strText.Substring(i, 1), new Font("Times New Roman", 25, FontStyle.Italic), letterBrush, width / (intChars + 1) * i, 40);
}
else if (i == 3)
{
//draw ‘the text on our image
graCanvas.DrawString(strText.Substring(i, 1), new Font("Georgia", 35, FontStyle.Bold), letterBrush, width / (intChars + 1) * i, 10);
}
else if (i == 4)
{
//draw ‘the text on our image
graCanvas.DrawString(strText.Substring(i, 1), new Font("Verdana", 25, FontStyle.Italic), letterBrush, width / (intChars + 1) * i, 40);
}
else if (i == 5)
{
//draw ‘the text on our image
graCanvas.DrawString(strText.Substring(i, 1), new Font("Geneva", 30, FontStyle.Bold), letterBrush, width / (intChars + 1) * i, 10);
}
else
{
//draw ‘the text on our image
graCanvas.DrawString(strText.Substring(i, 1), new Font("Verdana", 25, FontStyle.Italic), letterBrush, width / (intChars + 1) * i, 40);
}
graCanvas.ResetTransform();
}
bmpCanvas.Save(path, ImageFormat.Gif);//I got Here A generic error occurred in GDI+.
graCanvas.Dispose();
bmpCanvas.Dispose();
return strText;
}
protected void subCheckCaptcha(object sender, EventArgs e)
{
if (!(txtCaptcha.Text == Session["strText"].ToString()))
{
lbl_Msg.Text = "The characters does not match";
}
else
{
lbl_Msg.Text = "";
Response.Write("alert(‘Captcha text entered successfully’)”);
}
}
muy buen post amigo
muy buena solucion y un plus mas es que reduce el tamaño de las imagenes
sin perder calidad
Actually, the fix is to properly dispose of your objects in order. In C#, I use the using() syntax, which calls Dispose() for me at the end of the scope. So, the fix would be to end your scope before calling Save() on the bitmap.
// new image with transparent Alpha layer
using (var bitmap = new Bitmap(330, 18, PixelFormat.Format32bppArgb))
{
using (var graphics = Graphics.FromImage(bitmap))
{
// add some anti-aliasing
graphics.SmoothingMode = SmoothingMode.AntiAlias;
using (var font = new Font(“Arial”, 14.0f, GraphicsUnit.Pixel))
{
using (var brush = new SolidBrush(Color.White))
{
// draw it
graphics.DrawString(user.Email, font, brush, 0, 0);
}
}
}
// setup the response
Response.Clear();
Response.ContentType = “image/png”;
Response.BufferOutput = true;
// write it to the output stream
bitmap.Save(Response.OutputStream, ImageFormat.Png);
Response.Flush();
}