C# 图片加载内存不足解决方案 - 使用using语句优化代码
try { if (pictureBox1.Image != null) { pictureBox1.Image.Dispose(); pictureBox1.Image = null; } tabControl1.SelectedIndex = 2; using (Image originalImage = Image.FromFile('D:\maoyan.jpg')) { using (Image resizedImage = ResizeImage(originalImage, new Size(pictureBox1.Width, pictureBox1.Height))) { resizedImage.Save('D:\maoyan1.jpg'); pictureBox1.Image = resizedImage; } } } catch (Exception ex) { MessageBox.Show(ex.Message); }
在上述代码中,我们使用了using语句来确保在使用完后自动释放资源。同时,在调用Image.FromFile方法之前,我们可以尝试先使用Image.FromStream方法加载图片,以减少内存占用。
原文地址: https://www.cveoy.top/t/topic/nH0a 著作权归作者所有。请勿转载和采集!