Resizing Images in Silverlight 3 with WriteableBitmap

This is my first day with Silverlight. Im trying to prototype an application that (among other functions) should be able to resize images provided by the user. It should be able to process and display several resized images at once. The most obvious approaches I've tried seem to be a memory leak in the sense that the original bitmaps are still referenced in some way, which causes Silverlight to allocate hundreds of megabytes of memory after a while. I just want to be able to upload images one at a time, resize them and store small versions.

To be precise, I have tried the following:

  • List creation System.Windows.Controls.Image(and scaling). I am not surprised that this did not work.

  • Create a list of rectangles filled with image brushes. I'm not surprised either.

  • Display bitmaps in System.Windows.Media.Imaging.WriteableBitmap. I expected this to work well; I suggested that bitmaps are really just drawn directly and are not mentioned in any way. However, memory consumption is indicated differently.

Here is a snippet of the corresponding code snippet:

// create image source
Stream stream = file.OpenRead();
BitmapImage bmpImg = new BitmapImage();
bmpImg.SetSource(stream);
stream.Close();

// create temporary image from it
Image tmpImg = new Image();
tmpImg.Source = bmpImg;

// this is required by WriteableBitmap 
tmpImg.Measure(new Size(100, 100));
tmpImg.Arrange(new Rect(0, 0, 100, 100));

// prepare scaling to 100x100
ScaleTransform scaleTrans = new ScaleTransform();
double scale = (double)100 / (double)Math.Max(bmpImg.PixelHeight, bmpImg.PixelWidth);
scaleTrans.CenterX = 0;
scaleTrans.CenterY = 0;
scaleTrans.ScaleX = scale;
scaleTrans.ScaleY = scale;

// render
WriteableBitmap writeableBitmap = new WriteableBitmap(100, 100);
writeableBitmap.Render(tmpImg, scaleTrans);
writeableBitmap.Invalidate();

// final image
Image img = new Image();
img.Source = writeableBitmap;

I hope that I did not miss anything stupid, but it seems to me that everything is in order, and does everything right (except for the memory problem). Please keep in mind that code quality should not be product quality; its just a quick and dirty prototype.

, ; , Silverlight. , , - , Im , Silverlight - . , Silverlight .

+5
2

WriteableBitmapEx? WriteableBitmap. , :

BitmapImage image = new BitmapImage();
image.SetSource(dialog.File.OpenRead());

WriteableBitmap bitmap = new WriteableBitmap(image);
WriteableBitmap resizedBitmap = bitmap.Resize(500, 500, WriteableBitmapExtensions.Interpolation.Bilinear);

// For uploading
byte[] data = resizedBitmap.ToByteArray();
+4

, - , IDisposable. , Stream Image . - Dispose() ( "" ), , , .

+1

All Articles