The Crop method "Attempted to read or write protected memory. This is often an indication that other memory is corrupt... "of the error will appear.

Aug 29, 2012 at 8:16 AM
Edited Aug 29, 2012 at 8:17 AM

MainPage.xaml

----------------------------------------------------------------------

<Page
    x:Class="Metro_SelectedImageCut.MainPage"
    IsTabStop="false"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:Metro_SelectedImageCut"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

<Grid x:Name="ContentPanel" >
        <Grid  Background="Transparent" VerticalAlignment="Top" HorizontalAlignment="Left" ManipulationStarted="ContentPanel_ManipulationStarted" ManipulationDelta="ContentPanel_ManipulationDelta" ManipulationMode="All">
           <Image  x:Name="Image1"  Stretch="None" />
            <Rectangle Name="Rectangle1" Visibility="Collapsed" HorizontalAlignment="Left" VerticalAlignment="Top"  StrokeDashArray="2,2" Stroke="Yellow" StrokeThickness="3"  Fill="#20000000"  ManipulationDelta="Rectangle1_ManipulationDelta"  ManipulationStarted="Rectangle1_ManipulationStarted" ManipulationMode="All"/>
       </Grid>
        <Button x:Name="Button1" Content="切り出す" HorizontalAlignment="Left" Height="63" Margin="114,505,0,0" VerticalAlignment="Top" Width="308" FontFamily="Meiryo UI" FontSize="36"/>
        <Image x:Name="resultImage" HorizontalAlignment="Left" Height="228" Margin="830,94,0,0" VerticalAlignment="Top" Width="245"/>
    </Grid>
</Page>

---------------------------------------------------------------------

MainPage.xaml.vb

----------------------------------------------------------------

Option Strict On

Imports Windows.Storage
Imports Windows.Storage.Pickers
Imports Windows.UI.Xaml.Media.Imaging

Public NotInheritable Class MainPage
    Inherits Page
    Dim myBmp As New BitmapImage
    Dim myFile As StorageFile
    Dim FileName As String
  

    Protected Overrides Async Sub OnNavigatedTo(e As Navigation.NavigationEventArgs)
        Dim myFileOpenPicker As New FileOpenPicker
        myFileOpenPicker.ViewMode = PickerViewMode.Thumbnail
        myFileOpenPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary
        myFileOpenPicker.FileTypeFilter.Add("*")
        myFile = Await myFileOpenPicker.PickSingleFileAsync()
        If myFile Is Nothing = False Then
            FileName = myFile.Path
            myBmp.SetSource(Await myFile.OpenReadAsync)
            Image1.Source = myBmp
        End If
    End Sub

    Private Sub ContentPanel_ManipulationDelta(sender As Object, e As ManipulationDeltaRoutedEventArgs) 'Handles ContentPanel.ManipulationDelta
        Rectangle1.Width = e.Cumulative.Translation.X
        Rectangle1.Height = e.Cumulative.Translation.Y
    End Sub

    Private Sub ContentPanel_ManipulationStarted(sender As Object, e As ManipulationStartedRoutedEventArgs) 'Handles ContentPanel.ManipulationStarted
        Rectangle1.Margin = New Thickness(e.Position.X, e.Position.Y, 0, 0)
        Rectangle1.Width = 0
        Rectangle1.Height = 0
        Rectangle1.Visibility = Windows.UI.Xaml.Visibility.Visible
    End Sub

    Private Sub Rectangle1_ManipulationDelta(sender As Object, e As ManipulationDeltaRoutedEventArgs) 'Handles Rectangle1.ManipulationDelta
        Rectangle1.Margin = New Thickness(Rectangle1.Margin.Left + e.Delta.Translation.X, Rectangle1.Margin.Top + e.Delta.Translation.Y, 0, 0)
        e.Handled = True
    End Sub

    Private Sub Rectangle1_ManipulationStarted(sender As Object, e As ManipulationStartedRoutedEventArgs) 'Handles Rectangle1.ManipulationStarted
        e.Handled = True
    End Sub

    Private Async Sub Button1_Click(sender As Object, e As RoutedEventArgs) Handles Button1.Click
        Dim myWriteableBitmap = New WriteableBitmap(CInt(Rectangle1.Width), CInt(Rectangle1.Height))
        myWriteableBitmap.SetSource(Await myFile.OpenReadAsync)

''■Attempted to read or write protected memory. This is often an indication that other memory is corrupt... "I get the error

        Dim myCrop = myWriteableBitmap.Crop(CInt(Rectangle1.Margin.Left), CInt(Rectangle1.Margin.Top), CInt(Rectangle1.Width), CInt(Rectangle1.Height))        resultImage.Source = myCrop
        myCrop.Invalidate()
    End Sub

End Class

-----------------------------------------------------------

 
In spots by using the Crop method, "Attempted to read or write protected memory. This is often an indication that other memory is corrupt "of is I get error, I don't know why.
Worked without problems in Windows 8 RP. Now to get an error in Windows 8 RTM.
In spots by using the Crop method, "Attempted to read or write protected memory. This is often an indication that other memory is corrupt "of is I get error, I don't know why.
Worked without problems in Windows 8 RP. Now to get an error in Windows 8 RTM.

Thank you.

by Kuni

Coordinator
Aug 29, 2012 at 9:36 AM

Please upload the full repro solution somewhere, so we can look at it.

 

- Rene

Aug 29, 2012 at 9:59 AM
 
Program files compressed in the URL below complete uploaded. Thank you in advance.
Coordinator
Aug 29, 2012 at 10:59 AM

The problem is not the Crop. Don't use WriteableBitmap.SetSource it will run asnyc in the background and the pixel data won't be available at this moment. Use the WBX extension method FromStream.

Instead of this line:

myWriteableBitmap.SetSource(Await myFile.OpenReadAsync)

Use this:

Await myWriteableBitmap.FromStream(Await myFile.OpenReadAsync)

It will make sure the data was really loaded after the Await.

 

- rene

Aug 29, 2012 at 11:15 AM

Thank you for your reply. I tried writing below is displayed the range that you specified. Still be somewhere wrong?. Best regards.

    Dim myWriteableBitmap = New WriteableBitmap(CInt(Rectangle1.Width), CInt(Rectangle1.Height))
        Await myWriteableBitmap.FromStream(Await myFile.OpenReadAsync)
        myWriteableBitmap.Crop(CInt(Rectangle1.Margin.Left), CInt(Rectangle1.Margin.Top), CInt(Rectangle1.Width), CInt(Rectangle1.Height))
        resultImage.Source = myWriteableBitmap
        myWriteableBitmap.Invalidate()

Thank you.

by Kuni

Coordinator
Aug 29, 2012 at 12:13 PM

You have to assign it:

myWriteableBitmap = Await myWriteableBitmap.FromStream(Await myFile.OpenReadAsync)

-rene

Aug 29, 2012 at 12:27 PM

In the following the desired processing. Thank you so much.

    Dim myWriteableBitmap = New WriteableBitmap(CInt(Rectangle1.Width), CInt(Rectangle1.Height))
        Dim myCrop = Await myWriteableBitmap.FromStream(Await myFile.OpenReadAsync)
        Dim mySelectedImage = myCrop.Crop(CInt(Rectangle1.Margin.Left), CInt(Rectangle1.Margin.Top), CInt(Rectangle1.Width), CInt(Rectangle1.Height))
        resultImage.Width = Rectangle1.Width
        resultImage.Height = Rectangle1.Height
        resultImage.Source = mySelectedImage
        myCrop.Invalidate()

by Kuni

Oct 15, 2012 at 8:39 PM

I'm trying to load an image in Windows RT using FromStream as described in this discussion, but I can't get it to work. No error, but doesn't display an image. I've tried two other techniques that display the image correctly but I would prefer to use FromStream because its simplicity. I've reduced it down to this test example:

MainPage.xaml

<Page
    x:Class="LoadImage.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:LoadImage"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
        <Image x:Name="img" Height="600" Width="800"/>
    </Grid>
</Page>

MainPage.xaml.cs

using System;
using System.IO;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading.Tasks;
using Windows.Graphics.Imaging;
using Windows.Storage;
using Windows.Storage.Streams;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media.Imaging;

// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238

namespace LoadImage
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            this.InitializeComponent();
            Loaded += MainPage_Loaded;
        }

        void MainPage_Loaded(object sender, Windows.UI.Xaml.RoutedEventArgs e)
        {
            ReadImage();
        }

        
        async void ReadImage()
        {
            // this displays correctly, but I don't have access to pixels because of async
            //WriteableBitmap wbm = await BitmapSetSourceAsync(new Uri("ms-appx:///Assets/Jellyfish.jpg"));

            // this does not display an image
            //WriteableBitmap wbm = await BitmapFromStreamAsync(new Uri("ms-appx:///Assets/Jellyfish.jpg"));

            // This is adapted from Microsoft's Windows 8 sample code
            // http://code.msdn.microsoft.com/windowsapps/0f5d56ae-5e57-48e1-9cd9-993115b027b9 (Scenario4.xaml.cs)
            // It displays correctly and I can access pixels, but is it necessary to be so complicated?
            WriteableBitmap wbm = await LoadImageUsingPixelBuffer(new Uri("ms-appx:///Assets/Jellyfish.jpg"));

            img.Source = wbm;
            wbm.Invalidate();
        }

        // this displays correctly, but I don't have access to pixels because of async
        async Task<WriteableBitmap> BitmapSetSourceAsync(Uri fileUri)
        {
            WriteableBitmap wbm = new WriteableBitmap(800, 600);
            StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(fileUri);
            await wbm.SetSourceAsync(await file.OpenAsync(Windows.Storage.FileAccessMode.Read));
            return wbm;
        }

        //  this does not display an image
        async Task<WriteableBitmap> BitmapFromStreamAsync(Uri fileUri)
        {
            WriteableBitmap wbm = new WriteableBitmap(800, 600);
            StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(fileUri);
            await wbm.FromStream(await file.OpenReadAsync());
            return wbm;
        }

        // This is adapted from Microsoft's Windows 8 sample code
        // http://code.msdn.microsoft.com/windowsapps/0f5d56ae-5e57-48e1-9cd9-993115b027b9 (Scenario4.xaml.cs)
        // It displays correctly and I can access pixels, but is it necessary to be so complicated?
        async Task<WriteableBitmap> LoadImageUsingPixelBuffer(Uri fileUri)
        {
            WriteableBitmap wbm = new WriteableBitmap(800, 600);
            StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(fileUri);

            using (IRandomAccessStream fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read))
            {
                BitmapDecoder decoder = await BitmapDecoder.CreateAsync(fileStream);

                // Scale image to appropriate size
                BitmapTransform transform = new BitmapTransform()
                {
                    ScaledWidth = Convert.ToUInt32(wbm.PixelWidth),
                    ScaledHeight = Convert.ToUInt32(wbm.PixelHeight)
                };

                PixelDataProvider pixelData = await decoder.GetPixelDataAsync(
                    BitmapPixelFormat.Bgra8,    // WriteableBitmap uses BGRA format
                    BitmapAlphaMode.Straight,
                    transform,
                    ExifOrientationMode.IgnoreExifOrientation, // This sample ignores Exif orientation
                    ColorManagementMode.DoNotColorManage);

                // An array containing the decoded image data, which could be modified before being displayed
                byte[] sourcePixels = pixelData.DetachPixelData();

                // Open a stream to copy the image contents to the WriteableBitmap's pixel buffer
                using (Stream stream = wbm.PixelBuffer.AsStream())
                {
                    await stream.WriteAsync(sourcePixels, 0, sourcePixels.Length);
                }
            }

            return wbm;
        }

    }
}

 

I would appreciate any help with this.

Richard

Coordinator
Oct 15, 2012 at 9:48 PM
Edited Oct 15, 2012 at 9:48 PM

You are not assigning the loaded WB back to the variable called wbm. It should be:

 

 

        //  this does not display an image
        async Task<WriteableBitmap> BitmapFromStreamAsync(Uri fileUri)
        {
            WriteableBitmap wbm = new WriteableBitmap(800, 600);
            StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(fileUri);
            wbm = await wbm.FromStream(await file.OpenReadAsync());
            return wbm;
        }

 

 

I know it's a bit weird, but it's due to nature of extension methods and you can actually write this:

 

        //  this does not display an image
        async Task<WriteableBitmap> BitmapFromStreamAsync(Uri fileUri)
        {
              StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(fileUri);
            return await new WriteableBitmap(1, 1).FromStream(await file.OpenReadAsync());
        }

 

- René Schulte

Oct 16, 2012 at 7:56 AM

Thank you René, I see my mistake now and I understand!

Richard