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

标签 c# sqlite windows-phone-8.1 filepicker

我正在添加学生并将个人资料详细信息保存到 SQLite 数据库。添加的学生资料显示在 ListView 中,如下所示。

enter image description here enter image description here

我想使用文件选择器添加学生的图片并保存。我怎样才能做到这一点?任何建议或类似示例都会更有帮助。

到目前为止我的代码

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

联系人.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();
    }
}

最佳答案

这不是一个好主意。您应该将文件保存在本地文件夹中并保存到数据库的路径。在这种方法中

您需要通过用户名或任何其他您喜欢的唯一属性将图像保存在本地文件夹中。我是这样做的。首先选择文件

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

现在用于保存文件
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 { }
    }

或者如果您想直接保存图像,那么 Base-64 是在 SQLite 中存储图像的最佳编码技术。试试下面给定的代码。一种方法将为您提供 Base-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);
}

}

希望能帮助到你。

关于c# - 在 Windows Phone 8.1 中使用文件选择器保存图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34556163/

相关文章:

c# - 从进程 ID 获取打开的 xlsx 文件名

c# - Entity Framework 代码优先无法正常工作

SQLite AUTOINCREMENT 非主键列

windows-phone-8 - WP8 AET的MIME类型

windows-phone-8.1 - 升级到最新的 windows phone 8.1 后发送证书失败

c# - 更改内容时控件显示为非事件状态

c# - C# 在内存中表示负整数并将其强制转换为未经检查的方式

sqlite - 如何使用 pyodbc 和 unixODBC 连接到 sqlite3 数据库?

java - 每次我打开新 Activity 时,Android SQLite 数据库似乎都会被清除

c# - 支持多种类型的动态磁贴