在WPF框架中,使用BitmapImage经常会导致内存释放不干净,占用内存过大的问题。
最近正好遇到,记录一下。
代码我整理成了一个函数。
public static BitmapImage GetImage(string imagePath)
{
BitmapImage bitmap = new BitmapImage();
try
{
try
{
BitmapImage img = new BitmapImage();
img.BeginInit();
img.CacheOption = BitmapCacheOption.OnLoad;
img.DecodePixelHeight = 82;
img.DecodePixelWidth = 146;
img.CreateOptions = BitmapCreateOptions.None;
img.UriSource = new Uri(imagePath);
img.EndInit();
img.Freeze();
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
return img;
}
catch(Exception ex)
{
MessageBox.Show("Bitmap" + ex.ToString());
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
return bitmap;
}
这样调用就可以
GetImage(“C:\Users\admin\Pictures\Screenshots\1.png”);
会返回一个BitmapImage 的图片。
下面在记录一个png等格式转换为BMP图片的函数
//path原路径,path_bmp生成路径
public bool pngtobmp(string path, string path_bmp)
{
bool successd = true;
try
{
//创建一个新图片来操作
System.Drawing.Image PngImg = System.Drawing.Image.FromFile(path);
Bitmap myImage = new Bitmap(PngImg);
int PngImg_w = PngImg.Width;
int PngImg_h = PngImg.Height;
int BmpImg_w = 0, BmpImg_h = 0;
string BitsPerPixel = PngImg.PixelFormat.ToString();
if ((BitsPerPixel == "Format32bppArgb" || BitsPerPixel == "Format24bppRgb")&& (PngImg_w * 9 == PngImg_h * 16))
{
if (PngImg_w >= 1920)
{
BmpImg_w = 1920;
BmpImg_h = 1080;
}
else if (PngImg_w < 1920)
{
BmpImg_w = 1280;
BmpImg_h = 720;
}
Bitmap img2;
img2 = new Bitmap(BmpImg_w, BmpImg_h, PixelFormat.Format24bppRgb);
using (Graphics g = Graphics.FromImage(img2))
{
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
g.DrawImage(myImage, new Rectangle(0, 0, img2.Width, img2.Height), 0, 0, myImage.Width, myImage.Height, GraphicsUnit.Pixel);
img2.Save(path_bmp, ImageFormat.Bmp);
img2.Dispose();
g.Dispose();
}
PngImg.Dispose();
myImage.Dispose();
}
else
{
successd = false;
}
}
catch (Exception ex)
{
MessageBox.Show("PNGtoBMP"+ex.ToString());
successd = false;
}
return successd;
}