I am trying as a part of a bigger job to merge parts of several JPEGs into one huge BMP which will be processed further.
As a start, I tried to just copy a few JPEGs each to his own BMP file. In doing so I noticed that Visual Studio 2015 Community shows increased memory consumption if I repeat the copying of files in a single debug-run. The responsible part of the code is as follows.
Please, can you help me with this increasing memory consumption? In the future, I might need to read a few thousand JPEGs so this might be a serious issue.
private void GluePhotos(string[] files) {
foreach (string file in files) {
//Read original JPEG
Stream imageSource = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read);
JpegBitmapDecoder jpegDecoder = new JpegBitmapDecoder(imageSource, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
BitmapSource bitmapSource = jpegDecoder.Frames[0];
//Prepare memory
int stride = bitmapSource.PixelWidth * ((bitmapSource.Format.BitsPerPixel + 7) / 8);
byte[] pixels = new byte[bitmapSource.PixelHeight * stride];
//Copy JPEG into memory
bitmapSource.CopyPixels(pixels, stride, 0);
//Copy memory into a new BMP-to-be
WriteableBitmap bitmap = new WriteableBitmap(bitmapSource.PixelWidth, bitmapSource.PixelHeight, bitmapSource.DpiX, bitmapSource.DpiY, bitmapSource.Format, bitmapSource.Palette);
bitmap.WritePixels(new System.Windows.Int32Rect(0, 0, bitmapSource.PixelWidth, bitmapSource.PixelHeight), pixels, stride, 0);
//Encode it as a BMP
BmpBitmapEncoder bmpEncoder = new BmpBitmapEncoder();
BitmapFrame newBitmapFrame = BitmapFrame.Create(bitmap);
bmpEncoder.Frames.Add(newBitmapFrame);
//Prepare paths for saving, save and cleaning(?)
string dirPath = file.Insert(file.LastIndexOf('\\'), "\\ripoffs");
dirPath = dirPath.Remove(dirPath.LastIndexOf('\\'));
Directory.CreateDirectory(dirPath);
string fileName = file.Insert(file.LastIndexOf('\\'), "\\ripoffs");
fileName = fileName.Remove(fileName.LastIndexOf('.')) + "_ripoff.bmp";
Stream imageOutput = new FileStream(fileName, FileMode.Create);
bmpEncoder.Save(imageOutput);
imageOutput.Close();
imageSource.Close();
}
}
GC.Collect()
but I would advise only for debugging/testing purposes. You may be trying to chase a problem that doesn't exist, try testing with multiple files, I think you'll find that it will increase to a point and then stabilize as the GC starts collecting. \$\endgroup\$