我有两个功能:一个从图像转换为字节,另一个从字节转换为bitmapImage。因此,当我打开带有该图像的窗口时,我将字节转换为bitmapImage,并且效果很好,但是当我关闭并再次打开它时,它只是保留在内存中,如果我再三重复一次,它只会抛出一个例外Out Of Memory exception
图像到字节->
private byte[] ConvertImageToBinary(Image img)
{
using (MemoryStream ss = new MemoryStream())
{
img.Save(ss, System.Drawing.Imaging.ImageFormat.Jpeg);
var s = ss.ToArray();
var jpegQuality = 50;
Image image;
using (var inputStream = new MemoryStream(s))
{
image = Image.FromStream(inputStream);
var jpegEncoder = System.Drawing.Imaging.ImageCodecInfo.GetImageDecoders()
.First(c => c.FormatID == System.Drawing.Imaging.ImageFormat.Jpeg.Guid);
var encoderParameters = new System.Drawing.Imaging.EncoderParameters(1);
encoderParameters.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, jpegQuality);
Byte[] outputBytes;
using (var outputStream = new MemoryStream())
{
image.Save(outputStream, jpegEncoder, encoderParameters);
return outputBytes = outputStream.ToArray();
}
}
}
}
字节到位图->
public BitmapImage ConvertBinaryToImage(byte[] array)
{
var image = new BitmapImage();
using (var ms = new MemoryStream(array))
{
image.BeginInit();
image.CacheOption = BitmapCacheOption.OnLoad; // here
image.StreamSource = ms;
image.EndInit();
image.Freeze();
}
return image;
}
<< img src =“ https://image.soinside.com/eyJ1cmwiOiAiaHR0cHM6Ly9pLmltZ3VyLmNvbS9GMUVQTlVOLnBuZyJ9” alt =“内存使用情况”>
当我打开WindowDragAndDrop时,它将加载所有图像
但是当我关闭它时,它仍然使用相同数量的内存
图像的确是一次性的(https://docs.microsoft.com/en-us/dotnet/api/system.drawing.image?view=netframework-4.8),所以您还需要:
using (var image = Image.FromStream(inputStream)){
}
在所有使用Image对象的地方。