Schwin W Pinkoh
Schwin W Pinkoh

Reputation: 50

C# WP8.1:Convert image from gallery to base64

I'm having a little trouble developing my app. What I'm trying to do now is that let the user pick their picture from gallery(picture album) and display it. Furthermore, I want to convert that picture taken to Base64 string. Right now I've successfully pull and display picture from gallery, is there anyway I can convert that picture to base64 string.

Here's the code how I grab and display

private void picprofile_Tapped(object sender, TappedRoutedEventArgs e)
    {
        CoreApplicationView view;
        String ImagePath;
        view = CoreApplication.GetCurrentView();

        ImagePath = string.Empty;
        FileOpenPicker filePicker = new FileOpenPicker();
        filePicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
        filePicker.ViewMode = PickerViewMode.Thumbnail;

        // Filter to include a sample subset of file types
        filePicker.FileTypeFilter.Clear();
        filePicker.FileTypeFilter.Add(".bmp");
        filePicker.FileTypeFilter.Add(".png");
        filePicker.FileTypeFilter.Add(".jpeg");
        filePicker.FileTypeFilter.Add(".jpg");

        filePicker.PickSingleFileAndContinue();
        view.Activated += viewActivated; 
    }

    private async void viewActivated(CoreApplicationView sender, IActivatedEventArgs args1)
    {
        CoreApplicationView view;           
        view = CoreApplication.GetCurrentView();

        FileOpenPickerContinuationEventArgs args = args1 as FileOpenPickerContinuationEventArgs;

        if (args != null)
        {
            if (args.Files.Count == 0) return;

            view.Activated -= viewActivated;
            StorageFile storageFile = args.Files[0];
            var stream = await storageFile.OpenAsync(Windows.Storage.FileAccessMode.Read);
            var bitmapImage = new Windows.UI.Xaml.Media.Imaging.BitmapImage();
            await bitmapImage.SetSourceAsync(stream);

            var decoder = await Windows.Graphics.Imaging.BitmapDecoder.CreateAsync(stream);
            picprofile.ImageSource = bitmapImage;
        }
    }

Upvotes: 1

Views: 493

Answers (1)

Apoorv
Apoorv

Reputation: 2043

See this code below help . I hope there are multiple ways to do this . The link might help you

public async Task<string> ImageToBase64(StorageFile MyImageFile)
    {
        Stream ms = await MyImageFile.OpenStreamForReadAsync();
        byte[] imageBytes = new byte[(int)ms.Length];
        ms.Read(imageBytes, 0, (int)ms.Length);
        return Convert.ToBase64String(imageBytes);
    }

Upvotes: 1

Related Questions