简体   繁体   English

保存图像在Windows Phone 8.1中使用文件选择器

[英]save image Using file picker in Windows Phone 8.1

I am adding Students and save Profile details to the SQLite database. 我正在添加学生并将配置文件详细信息保存到SQLite数据库。 Added Student Profiles are Shown in a Listview as below. 添加的学生资料显示在列表视图中,如下所示。

在此处输入图片说明 在此处输入图片说明

I want to add a picture of the student using a file picker and save it. 我想使用文件选择器添加学生的照片并保存。 How can I achieve that?. 我该如何实现? Any suggestion or similar example would be more helpful. 任何建议或类似示例都将更有帮助。

So far My codes 到目前为止,我的代码

   private string mruToken = null;   
    private NavigationHelper navigationHelper;
    public AddConatct()
    {
        this.InitializeComponent();
        this.navigationHelper = new NavigationHelper(this);
        this.Loaded += LoadSchoolToCombo;
        this.navigationHelper.LoadState += navigationHelper_LoadState;
        this.navigationHelper.SaveState += navigationHelper_SaveState;

    }
    private async void navigationHelper_LoadState(object sender, LoadStateEventArgs e)
    {

        if (e.PageState != null && e.PageState.ContainsKey("mruToken"))
        {
            object value = null;
            if (e.PageState.TryGetValue("mruToken", out value))
            {
                if (value != null)
                {
                    mruToken = value.ToString();

                    // Open the file via the token that you stored when adding this file into the MRU list.
                    Windows.Storage.StorageFile file =
                        await Windows.Storage.AccessCache.StorageApplicationPermissions.MostRecentlyUsedList.GetFileAsync(mruToken);

                    if (file != null)
                    {
                        // Open a stream for the selected file.
                        Windows.Storage.Streams.IRandomAccessStream fileStream =
                            await file.OpenAsync(Windows.Storage.FileAccessMode.Read);

                        // Set the image source to a bitmap.
                        Windows.UI.Xaml.Media.Imaging.BitmapImage bitmapImage =
                            new Windows.UI.Xaml.Media.Imaging.BitmapImage();

                        bitmapImage.SetSource(fileStream);
                        img.Source = bitmapImage;

                        // Set the data context for the page.
                        this.DataContext = file;
                    }
                }
            }
        }
    }
    private void navigationHelper_SaveState(object sender, SaveStateEventArgs e)
    {
        if (!string.IsNullOrEmpty(mruToken))
        {
            e.PageState["mruToken"] = mruToken;
        }

    }


   private async void PickPhoto_Click(object sender, RoutedEventArgs e){
        Windows.Storage.Pickers.FileOpenPicker openPicker = new Windows.Storage.Pickers.FileOpenPicker();
        openPicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.PicturesLibrary;
        openPicker.ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail;

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

        // Open the file picker.
        Windows.Storage.StorageFile file = await openPicker.PickSingleFileAsync();

        // file is null if user cancels the file picker.
        if (file != null)
        {
            // Open a stream for the selected file.
            Windows.Storage.Streams.IRandomAccessStream fileStream =
                await file.OpenAsync(Windows.Storage.FileAccessMode.Read);

            // Set the image source to the selected bitmap.
            Windows.UI.Xaml.Media.Imaging.BitmapImage bitmapImage =
                new Windows.UI.Xaml.Media.Imaging.BitmapImage();

            bitmapImage.SetSource(fileStream);
            img.Source = bitmapImage;
            this.DataContext = file;

            // Add picked file to MostRecentlyUsedList.
            mruToken = Windows.Storage.AccessCache.StorageApplicationPermissions.MostRecentlyUsedList.Add(file);
        }
    }

    private async void AddContact_Click(object sender, RoutedEventArgs e)
    {
        DatabaseHelperClass Db_Helper = new DatabaseHelperClass();//Creating object for DatabaseHelperClass.cs from ViewModel/DatabaseHelperClass.cs 
        if (NametxtBx.Text != "" & AgetxtBx.Text != "" & AddresstxtBx.Text != "" & SchoolComboBx.SelectedValue.ToString() != "" & GardienttxtBx.Text != "" & PhonetxtBx.Text != "" & LattxtBx.Text != "" & LongtxtBx.Text != "")
        {
            Db_Helper.Insert(new Contacts(NametxtBx.Text, AgetxtBx.Text, AddresstxtBx.Text, SchoolComboBx.SelectedValue.ToString(), GardienttxtBx.Text, PhonetxtBx.Text, LattxtBx.Text, LongtxtBx.Text));
            Frame.Navigate(typeof(ReadContactList));//after add contact redirect to contact listbox page 
        }
        else
        {
            MessageDialog messageDialog = new MessageDialog("Please fill all fields");//Text should not be empty 
            await messageDialog.ShowAsync();
        }
    }

Contacts.cs Contacts.cs

public class Contacts
{
    //The Id property is marked as the Primary Key
    [SQLite.PrimaryKey, SQLite.AutoIncrement]
    public int Id { get; set; }
    public string Name { get; set; }
    public string Age { get; set; }
    public string Address { get; set; }
    public string School { get; set; }
    public string Gardient { get; set; }
    public string PhoneNumber { get; set; }
    public string Latitude { get; set; }
    public string Longitude { get; set; }
    public string CreationDate { get; set; }
    public Contacts()
    {
        //empty constructor
    }
    public Contacts( string name, string age, string address, string school, string gardient, string phone_no, string latitude, string longitude)
    {

        Name = name;
        Age = age;
        Address = address;
        School = school;
        Gardient = gardient;
        PhoneNumber = phone_no;
        Latitude = latitude;
        Longitude = longitude;
        CreationDate = DateTime.Now.ToString();
    }
}

It's not a good idea. 这不是一个好主意。 You should save files in local folder and save path to database. 您应该将文件保存在本地文件夹中,并保存到数据库的路径。 In this approach 用这种方法

You need to save images in local folder by username or any other unique attribute as you like. 您需要根据用户名或任何其他唯一属性将图像保存在本地文件夹中。 I did it this way. 我是这样做的。 First pick the file 首先选择文件

private void choose_galary_pic_tapped(object sender, TappedRoutedEventArgs e)
    {
        try
        {
            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.PickSingleFileAndContinue();
        }
        catch { }
    }

and now for saving the file 现在用于保存文件

public async void ContinueFileOpenPicker(FileOpenPickerContinuationEventArgs args)
    {
        try
        {
            if (args.Files.Count > 0)
            {
                StorageFile sf = args.Files[0];
                await sf.CopyAsync(ApplicationData.Current.LocalFolder, args.Files[0].Name, NameCollisionOption.ReplaceExisting);
                System.Diagnostics.Debug.WriteLine(sf.Name);
                ApplicationData.Current.LocalSettings.Values["GImage"] = sf.Name;
                var stream = await args.Files[0].OpenAsync(Windows.Storage.FileAccessMode.Read);
                await bitmapImage.SetSourceAsync(stream);
                userImage.Source = bitmapImage;      
            }
            else
            {

            }
        }
        catch { }
    }

or if you want to directly save images then Base-64 is best encoding technique to store images in SQLite. 或者,如果您想直接保存图像,则Base-64是将图像存储在SQLite中的最佳编码技术。 Try the below given code. 尝试以下给定的代码。 One method will give you base-64 encoded string of StorageFile & other one will return you BitmapImage object, which can be set as source of <Image /> . 一种方法将为您提供以64为基数编码的StorageFile字符串,另一种方法将返回BitmapImage对象,可以将其设置为<Image />源。

private async Task<BitmapImage> Base64StringToBitmap(string source)
{
    var ims = new InMemoryRandomAccessStream();
    var bytes = Convert.FromBase64String(source);
    var dataWriter = new DataWriter(ims);
    dataWriter.WriteBytes(bytes);
    await dataWriter.StoreAsync();
    ims.Seek(0);
    var img = new BitmapImage();
    img.SetSource(ims);
    return img;
}

private async Task<string> ConvertStorageFileToBase64String(StorageFile imageFile)
{
var stream = await imageFile.OpenReadAsync();

using (var dataReader = new DataReader(stream))
{
    var bytes = new byte[stream.Size];
    await dataReader.LoadAsync((uint)stream.Size);
    dataReader.ReadBytes(bytes);

    return Convert.ToBase64String(bytes);
}

} }

Hope it helps. 希望能帮助到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM