Reputation: 1655
I try this code to resize my image:
ConvertToBitmap(txtImage.Text);
private void ConvertToBitmap(string filename)
{
if (File.Exists(filename))
{
var origImg = System.Drawing.Image.FromFile(filename);
var widthDivisor = (double)origImg.Width / (double)900;
var heightDivisor = (double)origImg.Height / (double)750;
int newWidth, newHeight;
if (widthDivisor < heightDivisor)
{
newWidth = (int)((double)origImg.Width / widthDivisor);
newHeight = (int)((double)origImg.Height / widthDivisor);
}
else
{
newWidth = (int)((double)origImg.Width / heightDivisor);
newHeight = (int)((double)origImg.Height / heightDivisor);
}
var newImg = new Bitmap(newWidth, newHeight);
Graphics g = Graphics.FromImage(newImg);
g.DrawImage(origImg, new Rectangle(0, 0, newWidth, newHeight));
System.Drawing.Imaging.EncoderParameters encoderParameters = new System.Drawing.Imaging.EncoderParameters(1);
encoderParameters.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)350);
newImg.Save(fullpath, GetImageCodeInfo("image/jpeg"), encoderParameters);
g.Dispose();
}
}
public static ImageCodecInfo GetImageCodeInfo(string mimeType)
{
ImageCodecInfo[] info = ImageCodecInfo.GetImageEncoders();
foreach (ImageCodecInfo ici in info)
if (ici.MimeType.Equals(mimeType, StringComparison.OrdinalIgnoreCase))
return ici;
return null;
}
private ImageCodecInfo GetEncoder(ImageFormat format)
{
ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();
foreach (ImageCodecInfo codec in codecs)
{
if (codec.FormatID == format.Guid)
{
return codec;
}
}
return null;
}
it's resize image but some how it shown error a generic error occurred in gdi+
.
any extra effort are welcome.
Upvotes: 1
Views: 4672
Reputation: 2377
Please note the private memory usage when the error occurs. This issue may also occur because of memory leak.
I see the code is handling graphics and other drawing objects which should be properly disposed after use.
Run this method in a loop to see if the memory consumption is drastically increasing. If yes, then there is a memory leak and you have to dig deep to find what object is not getting disposed after use.
Upvotes: 0
Reputation: 1655
Give security full permission to the folder then it's work very fine
Upvotes: 1