locked
Set Background using file picker

    Question

  • I am new to windows store and C# development. currently working on a calculator app for windows 8.

    I have set a file picker for users to select a single image file (jpg , jpeg , tiff , png )

    I want set selected image as a background of my MainPage.xaml

        private async void PickAFile_Click(object sender, RoutedEventArgs e)
            {
    
               
                FileOpenPicker openPicker = new FileOpenPicker();
                openPicker.ViewMode = PickerViewMode.Thumbnail;
                openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
                openPicker.FileTypeFilter.Add(".jpg");
                openPicker.FileTypeFilter.Add(".jpeg");
                openPicker.FileTypeFilter.Add(".png");
                openPicker.FileTypeFilter.Add(".tiff");
                StorageFile file = await openPicker.PickSingleFileAsync();
                if (file != null)
                {
    
                    MainPageGrid.Background = file;
    
    
                }
                else
                {
                    Output.text = "operation Cancelled";
                }
                
            

    There is only one error in If Block

    Cannot implicitly convert Windows.Storage.StorageFile to Windows.UI.Xaml.Media.Brush

    Thanks In advance.


    • Edited by mac1996 Monday, November 10, 2014 7:11 AM
    Monday, November 10, 2014 7:06 AM

Answers

  • this works for me:

    FileOpenPicker openPicker = new FileOpenPicker();
                openPicker.ViewMode = PickerViewMode.Thumbnail;
                openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
                openPicker.FileTypeFilter.Add(".jpg");
                openPicker.FileTypeFilter.Add(".jpeg");
                openPicker.FileTypeFilter.Add(".png");
                openPicker.FileTypeFilter.Add(".tiff");
                StorageFile file = await openPicker.PickSingleFileAsync();
                if (file != null)
                {
                    var image = new BitmapImage();
                    await image.SetSourceAsync(await file.OpenReadAsync());
    
                    var brush = new ImageBrush();
                    brush.ImageSource = image;
                    MainPageGrid.Background = brush;
                }


    Microsoft Certified Solutions Developer - Windows Store Apps Using C#

    • Proposed as answer by Mykyta Bondarenko Monday, November 10, 2014 5:58 PM
    • Marked as answer by mac1996 Thursday, November 13, 2014 7:13 PM
    Monday, November 10, 2014 9:04 AM

All replies

  • this works for me:

    FileOpenPicker openPicker = new FileOpenPicker();
                openPicker.ViewMode = PickerViewMode.Thumbnail;
                openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
                openPicker.FileTypeFilter.Add(".jpg");
                openPicker.FileTypeFilter.Add(".jpeg");
                openPicker.FileTypeFilter.Add(".png");
                openPicker.FileTypeFilter.Add(".tiff");
                StorageFile file = await openPicker.PickSingleFileAsync();
                if (file != null)
                {
                    var image = new BitmapImage();
                    await image.SetSourceAsync(await file.OpenReadAsync());
    
                    var brush = new ImageBrush();
                    brush.ImageSource = image;
                    MainPageGrid.Background = brush;
                }


    Microsoft Certified Solutions Developer - Windows Store Apps Using C#

    • Proposed as answer by Mykyta Bondarenko Monday, November 10, 2014 5:58 PM
    • Marked as answer by mac1996 Thursday, November 13, 2014 7:13 PM
    Monday, November 10, 2014 9:04 AM
  • Thanks a lot

    its working for me

    Monday, November 10, 2014 5:31 PM
  • One More question.

    when I restart my app.

    background sets back to Static Resource.

    How to keep that in memory.

    Thursday, November 13, 2014 7:15 PM
  • Simple sample:

    public sealed partial class MainPage : Page
    {
        private byte[] bg = null;
        
        public MainPage()
        {
            this.InitializeComponent();
        }

        private void Page_Loaded(object sender, RoutedEventArgs e)
        {
            var localSettings = ApplicationData.Current.LocalSettings;

            if (localSettings.Values.ContainsKey("BG")) bg = localSettings.Values["BG"] as byte[];
        }

        private void btSet_Click(object sender, RoutedEventArgs e)
        {
            var localSettings = ApplicationData.Current.LocalSettings;

            // Simulate an image as byte[]
            string s = "MyBackGroundImage";
            byte[] bg = new byte[s.Length * sizeof(char)];
            System.Buffer.BlockCopy(s.ToCharArray(), 0, bg, 0, bg.Length);

            localSettings.Values["BG"] = bg;  // Store here your Background image as byte[]
        }
    }

    How to convert an image (storageFile) to byte[] see this sample:

    https://code.msdn.microsoft.com/How-to-Import-a-set-of-409ed7a2

    How to convert byte[] to BitmapImage:

    using System.Runtime.InteropServices.WindowsRuntime;  // For byteArray.AsBuffer()  !!!

    InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream();

    await stream.WriteAsync(bytes.AsBuffer());

    BitmapImage image = new BitmapImage();

    stream.Seek(0);

    image.SetSource(stream);

    Regards

    Torsten



    • Edited by Torsten Menzel Friday, November 14, 2014 10:04 AM improvements
    Thursday, November 13, 2014 8:23 PM
  • Remark:

    Unfortunately each setting size is limited to 8k byte (???), so you must take another way:

        <Grid x:Name="grdBackGround" Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
            <StackPanel Margin="120,120,0,0" VerticalAlignment="Top" HorizontalAlignment="Left">
                <Button x:Name="btPickImage" Height="50" Width="140" Content="Pick Image" FontSize="18" VerticalAlignment="Bottom" Margin="0" Click="btPickImage_Click"/>
            </StackPanel>
        </Grid>

        public sealed partial class MainPage : Page
        {
            private static readonly string fileName = "BG.jpg";
    
            private StorageFolder localStorageFolder = null;
    
            public MainPage()
            {
                this.InitializeComponent();
            }
    
            private async void Page_Loaded(object sender, RoutedEventArgs e)
            {
                localStorageFolder = ApplicationData.Current.LocalFolder;
    
                StorageFile file = null;
    
                try
                {
                    file = await localStorageFolder.GetFileAsync(fileName);
                }
                catch (Exception) { return; }
    
                if (file == null) return;
    
                SetBgImage(await file.OpenAsync(FileAccessMode.Read));
            }
    
            private async void btPickImage_Click(object sender, RoutedEventArgs e)
            {
                var filePicker = new FileOpenPicker
                {
                    CommitButtonText = "Pick BG image file",
                    SuggestedStartLocation = PickerLocationId.PicturesLibrary,
                    ViewMode = PickerViewMode.List
                };
    
                filePicker.FileTypeFilter.Add(".jpg");
    
                StorageFile file = await filePicker.PickSingleFileAsync();
    
                // Cancel selected
                if (file != null)
                {
                    SetBgImage(await file.OpenAsync(FileAccessMode.Read));
    
                    await file.CopyAsync(localStorageFolder, fileName, NameCollisionOption.ReplaceExisting);
                }
            }
    
            private void SetBgImage(IRandomAccessStream iraStream)
            {
                BitmapImage bitmapImage = new BitmapImage();
    
                bitmapImage.SetSource(iraStream);
    
                ImageBrush brush = new ImageBrush();
    
                brush.ImageSource = bitmapImage;
    
                grdBackGround.Background = brush;
            }
        }
    Regards

    Torsten


    Friday, November 14, 2014 4:41 PM