views:

1030

answers:

2

Hi, I'm trying to resize an image in Silverlight 3 that has been submitted by a user via the OpenFileDialog control. I can grab the contents of the file and put it into a WriteableBitmap object and then display it on the screen just fine into an Image control. The Image control will even resize it to fit the size of the image control for me which is great.

The problem is the in memory image is still the original full resolution image, I kinda need to resize it in memory because I have a bunch of expensive operations I need to perform on it on a per pixel basis. So far I have the following code...

public partial class MainPage : UserControl
{
    public MainPage()
    {
        InitializeComponent();

        btnUploadPhoto.Click += new RoutedEventHandler(UploadPhoto_Click);
    }

    private void UploadPhoto_Click(object sender, RoutedEventArgs e)
    {
        OpenFileDialog dialog = new OpenFileDialog();
        dialog.Filter = "Image files (*.png;*.jpg;*.gif;*.bmp)|*.png;*.jpg;*.gif;*.bmp";

        if (dialog.ShowDialog() == true)
        {
            WriteableBitmap bitmap = new WriteableBitmap(500, 500);
            bitmap.SetSource(dialog.File.OpenRead());

            imgMainImage.Source = bitmap;

            txtMessage.Text = "Image size: " + bitmap.PixelWidth + " x " + bitmap.PixelHeight;
        }
    }
}

Problem is the WriteableBitmap class doesn't have a Resize method on it, and setting the height and width in the constructor doesn't seem to have any effect.

+1  A: 

I have used FJCore with some success, it's an open source C# imaging toolkit from Occipital. Includes in-memory resizing capability.

Also check out ImageMagick.

Dave Swersky
+1  A: 

What you can do is create a new Image element and set its source to a Writeable bitmap created from the stream. Don't add this Image element to the visual tree. Create another WriteableBitmap of the final size you want. Then call Render on this WriteableBitmap passing the Image element and a ScaleTransform to resize the image to the appropriate size. You can then use the second WriteableBitmap as the source for a second Image element and add that to the visual tree. You can then allow the first Image and WriteableBitmap objects to get GCed so you get the memory back.

KeithMahoney
Thanks, that sounds like an interesting approach I'll certainly try it. It amazes me why image resizing/manipulation functionality isn't included out of the box in some form of .ResizeBitmap(int widget, int height); method tacked onto the WritableBitmap class. It seems like a fairly common requirement.
Sunday Ironfoot