Ошибка System.OutOfMemoryException при загрузки картинки - C#
Формулировка задачи:
Здравствуйте.
При загрузке большого изображения на pictureBox1 вылетает ошибка нехватки памяти - OutOfMemoryException.
Надеялся исправить уменьшив изображение, но эта же ошибка стала вылетать на строке:
g.DrawImage(image, 0, 0, newWidth, newHeight);
Код программы:
Подскажите, как обойти данную проблему?
private void выбратьИзображениеToolStripMenuItem1_Click(object sender, EventArgs e)
{
string NameF = "";
openFileDialog1.CheckPathExists = true;
openFileDialog1.ValidateNames = true;
openFileDialog1.Filter = "image files (*.jpg,*.bmp,*png)|*.jpg;*bmp;*png|All files (*.*)|*.*";
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK && openFileDialog1.FileName.Length > 0)
{
NameF = openFileDialog1.FileName;
}
if (NameF.Length > 0)
{
System.IO.FileStream fs = new System.IO.FileStream(NameF, System.IO.FileMode.Open);
System.Drawing.Image Im = System.Drawing.Image.FromStream(fs);
fs.Close();
if (Im.Size.Width > 1501)
{
Im = ResizeOrigImg(Im);
pictureBox1.Image = Im;
}
else
{
pictureBox1.Image = Im;
}
}
StartImage();
}
public Image ResizeOrigImg(Image image)
{
int nWidth = 1500;
double N = image.Size.Width - 1500;
double i = Convert.ToDouble(image.Size.Width) / N;
double nHeight = Convert.ToDouble(image.Size.Height) - Convert.ToDouble(image.Size.Height) / i;
int newWidth, newHeight;
var coefH = (double)nHeight / (double)image.Height;
var coefW = (double)nWidth / (double)image.Width;
if (coefW >= coefH)
{
newHeight = (int)(image.Height * coefH);
newWidth = (int)(image.Width * coefH);
}
else
{
newHeight = (int)(image.Height * coefW);
newWidth = (int)(image.Width * coefW);
}
Image result = new Bitmap(newWidth, newHeight);//, PixelFormat.Format8bppIndexed);
using (var g = Graphics.FromImage(result))
{
try
{
g.CompositingQuality = CompositingQuality.HighQuality;
g.SmoothingMode = SmoothingMode.HighQuality;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
g.DrawImage(image, 0, 0, newWidth, newHeight);
g.Dispose();
}
catch (Exception j)
{
MessageBox.Show("Ошибка - " + j.ToString());
}
}
return result;
}Решение задачи: «Ошибка System.OutOfMemoryException при загрузки картинки»
textual
Листинг программы
Image.FromFile - метод