我有jpeg。 我将其转换为BitmapImage。 然后我降低了质量(压缩)。 然后我转换为字节数组。 我发现任务管理器中的内存升级很快。
我确信我会尽力处理。
这是我的代码:
//I am calling this from within a timer set 500ms
byte[] datatest = JpegXr.SaveJpegXrToBytes((Bitmap)frame.Clone(), 40f);
frame.Dispose();
public static class JpegXr
{
public static Bitmap BitmapImage2Bitmap(BitmapImage bitmapImage)
{
// BitmapImage bitmapImage = new BitmapImage(new Uri("../Images/test.png", UriKind.Relative));
using (MemoryStream outStream = new MemoryStream())
{
BitmapEncoder enc = new BmpBitmapEncoder();
enc.Frames.Add(BitmapFrame.Create(bitmapImage));
enc.Save(outStream);
System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(outStream);
// return bitmap; <-- leads to problems, stream is closed/closing ...
return new Bitmap(bitmap);
}
}
public static byte[] SaveJpegXrToBytes(Bitmap bitmap, float quality)
{
byte[] data = null;
var stream = new MemoryStream();
SaveJpegXr(bitmap, quality, stream);
stream.Seek(0, SeekOrigin.Begin);
data= stream.ToArray();
stream.Close();
bitmap.Dispose();
return data;
}
private static BitmapImage Bitmap2BitmapImage(Bitmap bitmap)
{
BitmapSource bitmapSource = Imaging.CreateBitmapSourceFromHBitmap(
bitmap.GetHbitmap(),
IntPtr.Zero, System.Windows.Int32Rect.Empty,
BitmapSizeOptions.FromEmptyOptions());
//BitmapSource bitmapSource = Clipboard.GetImage();
JpegBitmapEncoder encoder = new JpegBitmapEncoder();
MemoryStream memoryStream = new MemoryStream();
BitmapImage bImg = new BitmapImage();
encoder.Frames.Add(BitmapFrame.Create(bitmapSource));
encoder.Save(memoryStream);
bImg.BeginInit();
bImg.StreamSource = new MemoryStream(memoryStream.ToArray());
bImg.EndInit();
memoryStream.Close();
bitmap.Dispose();
return bImg;
//return (BitmapImage)i;
//return i;
}
private static void SaveJpegXr(Bitmap bitmap, float quality, Stream output)
{
BitmapImage bitmapSource = Bitmap2BitmapImage((Bitmap)bitmap.Clone());
//var bitmapSource = bitmap.ToWpfBitmap();
var bitmapFrame = BitmapFrame.Create(bitmapSource);
var jpegXrEncoder = new WmpBitmapEncoder();
jpegXrEncoder.Frames.Add(bitmapFrame);
jpegXrEncoder.ImageQualityLevel = quality / 100f;
jpegXrEncoder.Save(output);
bitmap.Dispose();
}
}
是否仅仅是这样的转换本身就是内存消耗,因此在定时器中经常调用它并不能让垃圾收集器有时间正确地处理对象?
赞赏人们的智慧......