C#WP8.1:将图像从库转换为base64

时间:2015-07-02 10:04:43

标签: c# windows-phone-8.1

我在开发应用时遇到了一些麻烦。我现在要做的是让用户从图库(图片专辑)中选择他们的图片并显示它。此外,我想将拍摄的照片转换为Base64字符串。现在我已成功拉动并显示图库中的图片,无论如何我可以将该图片转换为base64字符串。

这里是我抓取和显示的代码

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;
        }
    }

1 个答案:

答案 0 :(得分:1)

请参阅以下代码帮助。我希望有多种方法可以做到这一点。该链接可能会帮助您

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);
    }