A generic error occurred in GDI+ - c#

Hi frnds can anyone help me to solve this problem because i am new for .net world..
The below code is working fine in local server but whenever i try to upload in server it's
getting
"A generic error occurred in GDI+."
if (FileUpload2.PostedFile.ContentType == "image/pjpeg" || FileUpload2.PostedFile.ContentType == "image/jpg" || FileUpload2.PostedFile.ContentType == "image/gif" || FileUpload2.PostedFile.ContentType == "image/jpeg" || FileUpload2.PostedFile.ContentType == "image/png")
{
string filename = FileUpload2.FileName;
// Specify a upload directory
string directory = Server.MapPath(#"datalistimg\");
// Create a bitmap in memory of the content of the fileUpload control
Bitmap originalBMP = new Bitmap(FileUpload2.FileContent);
// Calculate the new image dimensions
int origWidth = originalBMP.Width;
int origHeight = originalBMP.Height;
int sngRatio = origWidth / origHeight;
int newWidth = 218;
int newHeight = (newWidth * origHeight) / origWidth;
// Create a new bitmap which will hold the previous resized bitmap
Bitmap newBMP = new Bitmap(originalBMP, newWidth, newHeight);
// Create a graphic based on the new bitmap
Graphics oGraphics = Graphics.FromImage(newBMP);
// 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, newWidth, newHeight);
// Save the new graphic file to the server
newBMP.Save(directory + filename);
dfn2 = #"datalistimg/" + filename;
originalBMP = null;
newBMP = null;
oGraphics = null;
fn2 = System.IO.Path.GetFileName(FileUpload2.PostedFile.FileName);
string SaveLocation = Server.MapPath("event") + "\\" + fn2;
fn2 = "event/" + fn2;
FileUpload2.PostedFile.SaveAs(SaveLocation);

Related

Resize and optimize Image before upload C#

I am using C#,MVC5 and I am uploading image from my web application but I realize that I have performance issues because I don't optimize them and I need to fix it and is important to keep the quality.
Below you can see the results of the report why is slow.
How can I do it?
I am saving the files into a path locally with the below code.
string imgpathvalue = ConfigurationManager.AppSettings["RestaurantPath"];
string path = System.IO.Path.Combine(Server.MapPath(imgpathvalue));
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
string pic = System.IO.Path.GetFileName(restaurantImg.FileName.Replace(" ", "_").Replace("%", "_"));
path = System.IO.Path.Combine(Server.MapPath(imgpathvalue), pic);
// file is uploaded
restaurantImg.SaveAs(path);
I have try the code below but I am getting the error "A generic error occurred in GDI+."
System.Drawing.Bitmap bmpPostedImage = new System.Drawing.Bitmap(restaurantImg.InputStream);
System.Drawing.Image objImage = ResizeImages.ScaleImage(bmpPostedImage, 81);
using (var ms = new MemoryStream())
{
objImage.Save(ms, objImage.RawFormat);
//ResizeImages.getImage(ms.ToArray());
}
public static System.Drawing.Image ScaleImage(System.Drawing.Image image, int maxHeight)
{
var ratio = (double)maxHeight / image.Height;
var newWidth = (int)(image.Width * ratio);
var newHeight = (int)(image.Height * ratio);
var newImage = new Bitmap(newWidth, newHeight);
using (var g = Graphics.FromImage(newImage))
{
g.DrawImage(image, 0, 0, newWidth, newHeight);
}
return newImage;
}
You are missing some of the code to resize your image correctly. Appending is a function that correctly resizes images depending on the Width and Height Values you give to it (in this example the image gets resized to 120*120 if possible).
Function Call:
ResizeImage("Path to the Image you want to resize",
"Path you want to save resizes copy into", 120, 120);
To make a function call like that possible we need to write our function. Which takes the image from the sourceImagePath and creates a new Bitmap.
Then it calculates the factor to resize the image and depending on if either the width or height is bigger it gets adjusted accordingly.
After that is done we create a new BitMap fromt he sourceImagePath and resize it. At the end we also need to dispose the sourceImage, the destImage and we also need to dispose of the Graphics Element g that we used for different Quality Settings.
Resize Function:
private void ResizeImage(string sourceImagePath, string destImagePath,
int wishImageWidth, int wishImageHeight)
{
Bitmap sourceImage = new Bitmap(sourceImagePath);
Bitmap destImage = null;
Graphics g = null;
int destImageWidth = 0;
int destImageHeight = 0;
// Calculate factor of image
double faktor = (double) sourceImage.Width / (double) sourceImage.Height;
if (faktor >= 1.0) // Landscape
{
destImageWidth = wishImageWidth;
destImageHeight = (int) (destImageWidth / faktor);
}
else // Port
{
destImageHeight = wishImageHeight;
destImageWidth = (int) (destImageHeight * faktor);
}
try
{
destImage = new Bitmap(sourceImage, destImageWidth, destImageHeight);
g = Graphics.FromImage(destImage);
g.InterpolationMode =
System.Drawing.Drawing2D.InterpolationMode.HighQualityBilinear;
g.SmoothingMode =
System.Drawing.Drawing2D.SmoothingMode.HighQuality;
g.PixelOffsetMode =
System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
g.CompositingQuality =
System.Drawing.Drawing2D.CompositingQuality.HighQuality;
g.DrawImage(sourceImage, 0, 0, destImageWidth, destImageHeight);
// Making sure that the file doesn't already exists.
if (File.Exists(destImagePath)) {
// If it does delete the old version.
File.Delete(destImagePath);
}
destImage.Save(destImagePath);
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("*** ERROR-Terror: " + ex.Message)
}
finally
{
if (g != null) { g.Dispose(); g = null; }
if (destImage != null) { destImage.Dispose(); destImage = null; }
}
sourceImage.Dispose();
sourceImage = null;
}

A generic error occurred in GDI+, Getting this exception in my code when i try to save optimized image on server

Here is my code below which i am using to redraw and save the image.
Bitmap bitmap = new Bitmap(HttpContext.Current.Server.MapPath(
filePath + Path.GetFileName(fileName)));
int newWidth = 100;
int newHeight = 100;
int iwidth = bitmap.Width;
int iheight = bitmap.Height;
if (iwidth <= 100)
newWidth = iwidth;
if (iheight <= 100)
newHeight = iheight;
bitmap.Dispose();
// ONCE WE GOT ALL THE INFORMATION, WE'll NOW PROCESS IT.
// CREATE AN IMAGE OBJECT USING ORIGINAL WIDTH AND HEIGHT.
// ALSO DEFINE A PIXEL FORMAT (FOR RICH RGB COLOR).
System.Drawing.Image objOptImage = new System.Drawing.Bitmap(newWidth, newHeight,
System.Drawing.Imaging.PixelFormat.Format16bppRgb555);
// GET THE ORIGINAL IMAGE.
using (System.Drawing.Image objImg =
System.Drawing.Image.FromFile(HttpContext.Current.Server.MapPath(filePath + fileName)))
{
// RE-DRAW THE IMAGE USING THE NEWLY OBTAINED PIXEL FORMAT.
using (System.Drawing.Graphics oGraphic = System.Drawing.Graphics.FromImage(objOptImage))
{
var _1 = oGraphic;
System.Drawing.Rectangle oRectangle = new System.Drawing.Rectangle(0, 0, newWidth, newHeight);
_1.DrawImage(objImg, oRectangle);
}
// On the below lines of code i am getting error while i try to execute
// this code after uploading image. If image size is around 10 kb it will
// not throw any error but if it exceeds then 10 kb then it will.
//SAVE THE OPTIMIZED IMAGE
objOptImage.Save(HttpContext.Current.Server.MapPath(filePath + "TempSubImages/" + fileName),
System.Drawing.Imaging.ImageFormat.Png);**
objImg.Dispose();
}
objOptImage.Dispose();
// FINALLY SHOW THE OPTIMIZED IMAGE DETAILS WITH SIZE.
Bitmap bitmap_Opt = new Bitmap(HttpContext.Current.Server.MapPath(filePath + "TempSubImages/" + Path.GetFileName(fileName)));
byte[] bytes = System.IO.File.ReadAllBytes(HttpContext.Current.Server.MapPath(filePath + "TempSubImages/" + Path.GetFileName(fileName)));
UI.BasePage.TemporaryFile = bytes;
String[] ArrContentType = new String[] { postedFile.ContentType, fileName };
UI.BasePage.TemporaryStrings = ArrContentType;
int iwidth_Opt = bitmap_Opt.Width;
int iheight_Opt = bitmap_Opt.Height;
bitmap_Opt.Dispose();

Compressing pictures in asp.net

i want to compress pictures in asp.net but the code i use those not fully compressing the files as soon are still very huge. How can i further reduce the size?
string directory = Server.MapPath("~/listingImages/" + date + filename);
// Create a bitmap of the conten t of the fileUpload control in memory
Bitmap originalBMP = new Bitmap(AsyncFileUpload1.FileContent);
// Calculate the new image dimensions
decimal origWidth = originalBMP.Width;
decimal origHeight = originalBMP.Height;
decimal sngRatio = origHeight / origWidth;
int newHeight = 300; //hight in pixels
decimal newWidth_temp = newHeight / sngRatio;
int newWidth = Convert.ToInt16(newWidth_temp);
// Create a new bitmap which will hold the previous resized bitmap
Bitmap newBMP = new Bitmap(originalBMP, newWidth, newHeight);
// Create a graphic based on the new bitmap
Graphics oGraphics = Graphics.FromImage(newBMP);
// Set the properties for the new graphic file
oGraphics.SmoothingMode = SmoothingMode.AntiAlias;
oGraphics.InterpolationMode = InterpolationMode.Bicubic;
// Draw the new graphic based on the resized bitmap
oGraphics.DrawImage(originalBMP, 0, 0, newWidth, newHeight);
// Save the new graphic file to the server
newBMP.Save(Server.MapPath("~/listingImages/" + date + filename));
Try setting the compressipn using this:
public static ImageCodecInfo GetEncoderInfo(String mimeType)
{
int j;
ImageCodecInfo[] encoders;
encoders = ImageCodecInfo.GetImageEncoders();
for (j = 0; j < encoders.Length; ++j)
{
if (encoders[j].MimeType == mimeType)
return encoders[j];
} return null;
}
EncoderParameters ep = new EncoderParameters(1);
ep.Param[0] = new EncoderParameter(Encoder.Quality, (long)70);
ImageCodecInfo ici = GetEncoderInfo("image/jpeg");
newBMP.Save(Server.MapPath("~/listingImages/" + date + filename), ici, ep);
Check this link for more details: https://msdn.microsoft.com/en-us/library/system.drawing.imaging.encoder.quality%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396.
Maybe you should specify image-format:
newBMP.Save(Server.MapPath("~/listingImages/" + date + filename), System.Drawing.Imaging.ImageFormat.Png);

How To split a big image into smaller A4 size pieces using DrawImage method of Graphics class

DrawImage method of Graphics class is not creating high quality images. In this method I am splitting a master image into multiple image but the code generating first image in very low quality. But it is generating full black images for remaining height.
public static Bitmap[] Split(byte[] ByteImage)
{
// MasterImage: there is no problem in master image. it is saving it in good quality.
MemoryStream ms = new MemoryStream(ByteImage);
System.Drawing.Image MasterImage = System.Drawing.Image.FromStream(ms);
MasterImage.Save(HttpContext.Current.Server.MapPath("../../../App_Shared/Reports/Temp/MasterImage.Bmp"), ImageFormat.Bmp);
//Split master image into multiple image according to height / 1000
Int32 ImageHeight = 1000, ImageWidth = MasterImage.Width, MasterImageHeight = MasterImage.Height;
int PageCount = 0;
Int32 TotalPages = MasterImage.Height / 1000;
Bitmap[] imgs = new Bitmap[TotalPages];
for (int y = 0; y + 1000 < MasterImageHeight; y += 1000, PageCount++)
{
imgs[PageCount] = new Bitmap(ImageWidth, ImageHeight, PixelFormat.Format32bppPArgb);
using (Graphics gr = Graphics.FromImage(imgs[PageCount]))
{
gr.CompositingQuality = CompositingQuality.HighQuality;
gr.InterpolationMode = InterpolationMode.HighQualityBicubic;
gr.SmoothingMode = SmoothingMode.HighQuality;
//First image now working with this code line
gr.DrawImage(MasterImage, new System.Drawing.Rectangle(0, y, ImageWidth, ImageHeight),new System.Drawing.Rectangle(0, 0, ImageWidth, ImageHeight), GraphicsUnit.Pixel); //new System.Drawing.Rectangle(new Point(0, y), new Size(ImageWidth, ImageHeight)));
//gr.DrawImage(MasterImage, new System.Drawing.Rectangle(0, y, ImageWidth, ImageHeight)); //new System.Drawing.Rectangle(new Point(0, y), new Size(ImageWidth, ImageHeight)));
string FilePath = HttpContext.Current.Server.MapPath("../../../App_Shared/Reports/Temp/Image" + PageCount.ToString() + ".bmp");
imgs[PageCount].Save(FilePath, System.Drawing.Imaging.ImageFormat.Bmp);
//Here it is saving images. I got first image with very poor quality but remaining in total balck color.
gr.Dispose();
}
}
return imgs;
}
As #HansPassant mentioned the source and target rectangle are reversed.
You could also change the structure of your splitting a bit so it could work a bit more flexible, and it might have a better readability at a later time.
class Program
{
static IList<Bitmap> SplitImage(Bitmap sourceBitmap, int splitHeight)
{
Size dimension = sourceBitmap.Size;
Rectangle sourceRectangle = new Rectangle(0, 0, dimension.Width, splitHeight);
Rectangle targetRectangle = new Rectangle(0, 0, dimension.Width, splitHeight);
IList<Bitmap> results = new List<Bitmap>();
while (sourceRectangle.Top < dimension.Height)
{
Bitmap pageBitmap = new Bitmap(targetRectangle.Size.Width, sourceRectangle.Bottom < dimension.Height ?
targetRectangle.Size.Height
:
dimension.Height - sourceRectangle.Top, PixelFormat.Format32bppArgb);
using (Graphics g = Graphics.FromImage(pageBitmap))
{
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBilinear;
g.DrawImage(sourceBitmap, targetRectangle, sourceRectangle, GraphicsUnit.Pixel);
}
sourceRectangle.Y += sourceRectangle.Height;
results.Add(pageBitmap);
}
return results;
}
static void Main(string[] args)
{
string sourceFilename = Environment.CurrentDirectory + #"\testimage.jpg";
Bitmap sourceBitmap = (Bitmap)Image.FromFile(sourceFilename);
var images = SplitImage(sourceBitmap, 79);
int len = images.Count;
for (int x = len; --x >= 0; )
{
var bmp = images[x];
string filename = "Images-" + x + ".bmp";
bmp.Save(Environment.CurrentDirectory + #"\" + filename, ImageFormat.Bmp);
images.RemoveAt(x);
bmp.Dispose();
Console.WriteLine("Saved " + filename);
}
Console.WriteLine("Done with the resizing");
}
}
This would also dynamically size the last image in case the page is less than your specified bitmap height at the end :)

Getting error when try to save file in Asp.net Using c#

This is the error i am getting right now
System.Runtime.InteropServices.ExternalException (0x80004005): A generic error occurred in GDI+. at System.Drawing.Image.Save(String filename, ImageCodecInfo encoder, EncoderParameters encoderParams)
i am using this same code on other website in same machine and there is no problem i really don't know what's going on please give me solution
here is my code
double newHeight = 0;
double newWidth = 0;
double scale = 0;
//create new image object
Bitmap curImage = new Bitmap(filePath);
//Determine image scaling
if (curImage.Height > curImage.Width)
{
scale = Convert.ToSingle(size) / curImage.Height;
}
else
{
scale = Convert.ToSingle(size) / curImage.Width;
}
if (scale < 0 || scale > 1) { scale = 1; }
//New image dimension
newHeight = Math.Floor(Convert.ToSingle(curImage.Height) * scale);
newWidth = Math.Floor(Convert.ToSingle(curImage.Width) * scale);
//Create new object image
Bitmap newImage = new Bitmap(curImage, Convert.ToInt32(newWidth), Convert.ToInt32(newHeight));
Graphics imgDest = Graphics.FromImage(newImage);
imgDest.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
imgDest.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
imgDest.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
imgDest.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
ImageCodecInfo[] info = ImageCodecInfo.GetImageEncoders();
EncoderParameters param = new EncoderParameters(1);
param.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L);
//Draw the object image
imgDest.DrawImage(curImage, 0, 0, newImage.Width, newImage.Height);
//Save image file
newImage.Save(saveFilePath, info[1], param);
//Dispose the image objects
curImage.Dispose();
newImage.Dispose();
imgDest.Dispose();
}
You will get a GDI error message if the account you're running under cannot save to the path at saveFilePath on this line:
newImage.Save(saveFilePath, info[1], param);

Categories

Resources