WPF 图片引起的异常
一.初始图片加载方式
public static BitmapImage GetImage11(string imagePath)
{
//图片角度判断
rotateImage(imagePath);
//图片显示
BitmapImage bitmap = new BitmapImage();
bitmap.Rotation = Rotation.Rotate0;
if (File.Exists(imagePath))
{
bitmap.BeginInit();
bitmap.CacheOption = BitmapCacheOption.OnLoad;
using (Stream ms = new MemoryStream(File.ReadAllBytes(imagePath)))
{
bitmap.StreamSource = ms;
bitmap.EndInit();
bitmap.Freeze();
}
}
return bitmap;
}
二.出现的问题
- 由于图片较大未做压缩,按上面的方式直接加载图片过大或者一定数量会出现异常内存不足的情况,导致软件报错
三.处理方式
- 对图片质量做压缩
public static void saveImageFromSource(String path, ImageSource image)
{
if (!System.IO.Directory.Exists(GlobalValue.AppFacePath)) {
System.IO.Directory.CreateDirectory(GlobalValue.AppFacePath);
}
using (FileStream fs = new FileStream(path, FileMode.Create))
{
JpegBitmapEncoder encoder = new JpegBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create((BitmapSource)image));
encoder.QualityLevel = 80;
encoder.Save(fs);
fs.Flush();
fs.Close();
}
}
- 获取图片的缩略图进行显示
public static BitmapImage GetImage11(string imagePath,bool IsScale=false)
{
//图片角度判断
rotateImage(imagePath);
//图片显示
BitmapImage bitmap = new BitmapImage();
bitmap.Rotation = Rotation.Rotate0;
if (File.Exists(imagePath))
{
bitmap.BeginInit();
bitmap.CacheOption = BitmapCacheOption.OnLoad;
using (Stream ms = new MemoryStream(File.ReadAllBytes(imagePath)))
{
bitmap.StreamSource = ms;
//主要是这行,增加对尺寸的限制
if(IsScale) bitmap.DecodePixelHeight = 200;
bitmap.EndInit();
bitmap.Freeze();
}
}
return bitmap;
}
版权声明:本文为CrossFile_TMS原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。