Silverlight 4 WriteableBitmap ScaleTransform Exception but was working in v3

Posted by Imran on Stack Overflow See other posts from Stack Overflow or by Imran
Published on 2010-04-30T17:25:05Z Indexed on 2010/06/15 8:42 UTC
Read the original article Hit count: 872

I am getting the following exception for code that used to work in silverlight 3 but has stopped working since upgrading to silverlight 4:

System.AccessViolationException was unhandled Message=Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

namespace SilverlightApplication1
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            var OpenFileDialog = new OpenFileDialog();
            OpenFileDialog.Filter = "*.jpg|*.jpg";

            if (OpenFileDialog.ShowDialog() == true)
            {
                var file = OpenFileDialog.Files.ToArray()[0];
                ScaleStreamAsBitmap(file.OpenRead(), 200);
            }
        }

        public static WriteableBitmap ScaleStreamAsBitmap(Stream file, int maxEdgeLength)
        {
            file.Position = 0;
            var src = new BitmapImage();
            var uiElement = new System.Windows.Controls.Image();
            WriteableBitmap b = null;
            var t = new ScaleTransform();

            src.SetSource(file);
            uiElement.Source = src;

            //force render
            uiElement.Effect = new DropShadowEffect() { ShadowDepth = 0, BlurRadius = 0 }; ;

            //calc scale
            double scaleX = 1;
            double scaleY = 1;
            if (src.PixelWidth > maxEdgeLength)
                scaleX = ((double)maxEdgeLength) / src.PixelWidth;
            if (src.PixelHeight > maxEdgeLength)
                scaleY = ((double)maxEdgeLength) / src.PixelHeight;
            double scale = Math.Min(scaleX, scaleY);
            t.ScaleX = scale;
            t.ScaleY = scale;

            b = new WriteableBitmap(uiElement, t);

            return b;
        }
    }
}

Thanks

© Stack Overflow or respective owner

Related posts about Silverlight

Related posts about silverlight-4.0