从Windows手机媒体库中选择图像并设置为页面背景

时间:2013-04-07 09:08:46

标签: c# image windows-phone-8 uri media-library

我正在尝试从手机库中检索图像,并使用以下代码将其设置为页面背景

    private void selectImageFromMediaLib()
    {
         selectphoto = new PhotoChooserTask();
         selectphoto.Completed += new EventHandler<PhotoResult>(selectphoto_Completed);
     selectphoto.Show();
    }

    private void selectphoto_Completed(object sender, PhotoResult e)
    {
        if (e.TaskResult == TaskResult.OK)
        {
            backgroundUri = new Uri(e.OriginalFileName, UriKind.Absolute);
            var bitmap = new BitmapImage(backgroundUri);
            ImageBrush imageBrush = new ImageBrush();
            imageBrush.ImageSource = bitmap;
            this.LayoutRoot.Background = imageBrush;     
     }
    }

但是,页面背景变黑,因此无法正确检索/创建照片。 URI到设备库的正确路径是什么?没有使用UriKind.Absolute吗?

enter image description here

2 个答案:

答案 0 :(得分:0)

您不能使用PhotoResult.OriginalFileName属性来读取文件,而是使用 PhotoResult.ChosenPhoto流并将其分配给代码中的bitmap.ImageSource属性。

答案 1 :(得分:0)

试试这个。它对我有用

PhotoChooserTask selectphoto;
private void selectImageFromMediaLib()
{
   selectphoto = new PhotoChooserTask();
   selectphoto.Completed += new EventHandler<PhotoResult>(selectphoto_Completed);
   selectphoto.Show();
}

private void selectphoto_Completed(object sender, PhotoResult e)
{
   if (e.TaskResult == TaskResult.OK)
   {
       var imageBytes = new byte[e.ChosenPhoto.Length];
       e.ChosenPhoto.Read(imageBytes, 0, imageBytes.Length);
       BitmapImage bitmapImage = new BitmapImage();
       MemoryStream ms = new MemoryStream(imageBytes);
       bitmapImage.SetSource(ms);
       ImageBrush imageBrush = new ImageBrush();
       imageBrush.ImageSource = bitmapImage;
       this.LayoutRoot.Background = imageBrush;
    }
}