private async void ButtonCamera_Click(object sender, RoutedEventArgs e) { CameraCaptureUI captureUI = new CameraCaptureUI(); captureUI.PhotoSettings.Format = CameraCaptureUIPhotoFormat.Jpeg; captureUI.PhotoSettings.CroppedSizeInPixels = new Size(600, 600); StorageFile photo = await captureUI.CaptureFileAsync(CameraCaptureUIMode.Photo); if (photo != null) { BitmapImage bmp = new BitmapImage(); IRandomAccessStream stream = await photo. OpenAsync(FileAccessMode.Read); bmp.SetSource(stream); BBQImage.Source = bmp; FileSavePicker savePicker = new FileSavePicker(); savePicker.FileTypeChoices.Add ("jpeg image", new List<string>() { ".jpeg" }); savePicker.SuggestedFileName = "New picture"; StorageFile savedFile = await savePicker.PickSaveFileAsync(); (this.DataContext as BBQRecipeViewModel).imageSource = savedFile.Path; if (savedFile != null) { await photo.MoveAndReplaceAsync(savedFile); } } }
private async void OnCapturePhotoButtonClick(object sender, RoutedEventArgs e) { var file = await TestedControl.CapturePhotoToStorageFileAsync(ApplicationData.Current.TemporaryFolder); var bi = new BitmapImage(); IRandomAccessStreamWithContentType stream; try { stream = await TryCatchRetry.RunWithDelayAsync<Exception, IRandomAccessStreamWithContentType>( file.OpenReadAsync(), TimeSpan.FromSeconds(0.5), 10, true); } catch (Exception ex) { // Seems like a bug with WinRT not closing the file sometimes that writes the photo to. #pragma warning disable 4014 new MessageDialog(ex.Message, "Error").ShowAsync(); #pragma warning restore 4014 return; } bi.SetSource(stream); PhotoImage.Source = bi; CapturedVideoElement.Visibility = Visibility.Collapsed; PhotoImage.Visibility = Visibility.Visible; }
/// <summary> /// サムネイル画像を取得しプロパティ変更通知を行う. /// </summary> private async void GetThumbnailAsync() { if (this.DeviceItem == null) { return; } if (this.DeviceItem.Data.Information == null) { return; } var thumbnail = await this.DeviceItem.Data.Information.First().GetThumbnailAsync(); if (thumbnail == null) { return; } this.m_deviceThumbnail = thumbnail; var bmpImage = new Windows.UI.Xaml.Media.Imaging.BitmapImage(); bmpImage.SetSource(thumbnail); this.thumbnailBitmapImage = bmpImage; OnPropertyChanged("ThumbnailBitmapImage"); }
public static (Func <ImageSource> Small, Func <ImageSource> Large) BookmarkIconsExplorer() { var bmps = new Windows.UI.Xaml.Media.Imaging.BitmapImage(new Uri("ms-appx:///res/Icon/icon_bookmark_s.png")); var bmpl = new Windows.UI.Xaml.Media.Imaging.BitmapImage(new Uri("ms-appx:///res/Icon/icon_bookmark_l.png")); //async void LoadFavicon() //{ // //try // { // var image = await Managers.FaviconManager.GetMaximumIcon(bookmark.TargetUrl); // if (image is null) return; // var png = Functions.GetPngStreamFromImageMagick(image); // if (png is null) return; // var png2 = new MemoryStream(); // await png.CopyToAsync(png2); // png.Seek(0, SeekOrigin.Begin); // png2.Seek(0, SeekOrigin.Begin); // await frame.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () => // { // await bmps.SetSourceAsync(png.AsRandomAccessStream()); // await bmpl.SetSourceAsync(png2.AsRandomAccessStream()); // }); // image.Dispose(); // } // //catch // //{ // //} //} //if ((bool)Storages.SettingStorage.GetValue("ShowBookmarkFavicon")) LoadFavicon(); return(() => bmps, () => bmpl); }
public async void OdabirSlikeAsync(object parameter) { var IzbornikSlike = new Windows.Storage.Pickers.FileOpenPicker { ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail, SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.PicturesLibrary }; IzbornikSlike.FileTypeFilter.Add(".jpg"); IzbornikSlike.FileTypeFilter.Add(".jpeg"); IzbornikSlike.FileTypeFilter.Add(".png"); Windows.Storage.StorageFile Slika = await IzbornikSlike.PickSingleFileAsync(); if (Slika == null) { MessageDialog greska = new MessageDialog("Greška pri odabiru slike!"); greska.ShowAsync(); return; } else { using (Windows.Storage.Streams.IRandomAccessStream fileStream = await Slika.OpenAsync(Windows.Storage.FileAccessMode.Read)) { Windows.UI.Xaml.Media.Imaging.BitmapImage SlikaBitMapa = new Windows.UI.Xaml.Media.Imaging.BitmapImage(); SlikaBitMapa.SetSource(fileStream); PathSlike = Convert.ToString(fileStream); } } }
public static async Task<BitmapImage> getImageSource(string imageName) { if (string.IsNullOrEmpty(imageName)) { return null; } try { StorageFile sourcePhoto = await KnownFolders.CameraRoll.GetFileAsync(imageName); if (sourcePhoto != null) { using (var fileStream = await sourcePhoto.GetThumbnailAsync(ThumbnailMode.PicturesView)) { sourcePhoto = null; var img = new BitmapImage(); img.SetSource(fileStream); return img; } } } catch (Exception e) { } return null; }
private async void LoadButton_Click(object sender, RoutedEventArgs e) { Windows.Storage.Pickers.FileOpenPicker filepicker = new Windows.Storage.Pickers.FileOpenPicker(); filepicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.PicturesLibrary; filepicker.FileTypeFilter.Add(".jpg"); filepicker.FileTypeFilter.Add(".png"); filepicker.FileTypeFilter.Add(".bmp"); filepicker.ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail; Windows.Storage.StorageFile imageFile = await filepicker.PickSingleFileAsync(); if (imageFile != null) { Windows.UI.Xaml.Media.Imaging.BitmapImage bitmap = new Windows.UI.Xaml.Media.Imaging.BitmapImage(); Windows.Storage.Streams.IRandomAccessStream stream = await imageFile.OpenAsync(Windows.Storage.FileAccessMode.Read); Image newImage = new Image(); bitmap.SetSource(stream); newImage.Source = bitmap; //newImage.Height = 250; newImage.Stretch = Stretch.UniformToFill; newImage.ManipulationMode = ManipulationModes.All; this.MyCanvas.Children.Add(newImage); } }
public EditCurrentImage(Image source, int sentId, BitmapImage sentSrc) { img = source; currentAngle = 0; id = sentId; bmp = sentSrc; }
public static async Task <Windows.UI.Xaml.Media.Imaging.BitmapImage> GetBitmapAsync(byte[] data) { if (data is null) { return(null); } var bitmapImage = new Windows.UI.Xaml.Media.Imaging.BitmapImage(); using (var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream()) { using (var writer = new Windows.Storage.Streams.DataWriter(stream)) { writer.WriteBytes(data); await writer.StoreAsync(); await writer.FlushAsync(); writer.DetachStream(); } stream.Seek(0); await bitmapImage.SetSourceAsync(stream); } return(bitmapImage); }
public async void view_Activated(CoreApplicationView sender, Windows.ApplicationModel.Activation.IActivatedEventArgs args1) { FileOpenPickerContinuationEventArgs args = args1 as FileOpenPickerContinuationEventArgs; if (args != null) { if (args.Files.Count == 0) { return; } view.Activated -= view_Activated; StorageFile storfile = args.Files[0]; var stream = await storfile.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); ImageName = storfile.Name; btimg.ImageSource = bitmapImage; image.Content = ""; } }
public async Task LoadImage() { if (ImageFileName.Contains("ms-appx:Assets")) { BitmapImage bitmapImage = new BitmapImage(new Uri(ImageFileName, UriKind.RelativeOrAbsolute)); ImageBrush brush = new ImageBrush(); brush.AlignmentX = AlignmentX.Left; brush.AlignmentY = AlignmentY.Top; brush.Stretch = Stretch.UniformToFill; _picBrush.ImageSource = bitmapImage; return; } var folder = await StaticHelpers.GetSaveFolder(); var file = await folder.GetFileAsync(ImageFileName); using (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); _picBrush.ImageSource = bitmapImage; } }
public async Task<BitmapImage> Base64ToBitmapImage(string base64String) { BitmapImage img = new BitmapImage(); if (string.IsNullOrEmpty(base64String)) return img; using (var ims = new InMemoryRandomAccessStream()) { byte[] bytes = Convert.FromBase64String(base64String); base64String = ""; using (DataWriter dataWriter = new DataWriter(ims)) { dataWriter.WriteBytes(bytes); bytes = null; await dataWriter.StoreAsync(); ims.Seek(0); await img.SetSourceAsync(ims); //not in RC return img; } } }
public static async Task<BitmapImage> TileToImage(byte[] tile) { var image = await ByteArrayToRandomAccessStream(tile); var bitmapImage = new BitmapImage(); bitmapImage.SetSource(image); return bitmapImage; }
protected override async void OnNavigatedTo(NavigationEventArgs e) { FileOpenPicker opener = new FileOpenPicker(); opener.ViewMode = PickerViewMode.Thumbnail; opener.SuggestedStartLocation = PickerLocationId.PicturesLibrary; opener.FileTypeFilter.Add(".jpg"); opener.FileTypeFilter.Add(".jpeg"); opener.FileTypeFilter.Add(".png"); StorageFile file = await opener.PickSingleFileAsync(); if (file != null) { // We've now got the file. Do something with it. var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read); var bitmapImage = new Windows.UI.Xaml.Media.Imaging.BitmapImage(); await bitmapImage.SetSourceAsync(stream); bustin.Source = bitmapImage; var decoder = await Windows.Graphics.Imaging.BitmapDecoder.CreateAsync(stream); } else { //OutputTextBlock.Text = "The operation may have been cancelled."; } }
public object Convert(object value, Type targetType, object parameter, string language) { string uriString = (value == null) ? string.Empty : (string)value; string converterParam = (string)parameter; BitmapImage image = new BitmapImage(); image.DecodePixelType = DecodePixelType.Logical; if (converterParam != null) { if (converterParam.StartsWith("w")) { image.DecodePixelWidth = Int32.Parse(converterParam.Remove(0, 1)); } else if (converterParam.StartsWith("h")) { image.DecodePixelHeight = Int32.Parse(converterParam.Remove(0, 1)); } } string proxyScheme = "image://"; if (uriString.StartsWith(proxyScheme)) { image.SetProxySourceAsync(uriString); } else { Uri defaultUri = new Uri("ms-appx:///Assets/DefaultArt.jpg", UriKind.Absolute); image.UriSource = defaultUri; } return image; }
public object Convert(object value, Type targetType, object parameter, string language) { var result = new Windows.UI.Xaml.Media.Imaging.BitmapImage(); Managers.ThumbnailManager.SetToImageSourceNoWait(value.ToString(), result); return(result); }
private async void OpenFile_Click(object sender, RoutedEventArgs e) { FileOpenPicker picker = new FileOpenPicker(); picker.ViewMode = PickerViewMode.Thumbnail; picker.SuggestedStartLocation = PickerLocationId.PicturesLibrary; picker.FileTypeFilter.Add(".jpg"); picker.FileTypeFilter.Add(".jpeg"); picker.FileTypeFilter.Add(".png"); StorageFile file = await picker.PickSingleFileAsync(); if (file != null) { string name = file.Path.ToString(); using (Windows.Storage.Streams.IRandomAccessStream fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read)) { Windows.UI.Xaml.Media.Imaging.BitmapImage bitmapImage = new Windows.UI.Xaml.Media.Imaging.BitmapImage(); /*Img.Source = new BitmapImage(new Uri(name, UriKind.Relative));*/ bitmapImage.SetSource(fileStream); Img.Source = bitmapImage; } } }
public static BitmapImage GetImage(string path, bool negateResult = false) { if (string.IsNullOrEmpty(path)) { return null; } var isDarkTheme = Application.Current.RequestedTheme == ApplicationTheme.Dark; if (negateResult) { isDarkTheme = !isDarkTheme; } BitmapImage result; path = "ms-appx:" + string.Format(path, isDarkTheme ? "dark" : "light"); // Check if we already cached the image if (!ImageCache.TryGetValue(path, out result)) { result = new BitmapImage(new Uri(path, UriKind.Absolute)); ImageCache.Add(path, result); } return result; }
public static async Task<List<LocationData>> GetPhotoInDevice() { List<LocationData> mapPhotoIcons = new List<LocationData>(); IReadOnlyList<StorageFile> photos = await KnownFolders.CameraRoll.GetFilesAsync(); for (int i = 0; i < photos.Count; i++) { Geopoint geopoint = await GeotagHelper.GetGeotagAsync(photos[i]); if (geopoint != null) { //should use Thumbnail to reduce the size of images, otherwise low-end device will crashes var fileStream = await photos[i].GetThumbnailAsync(ThumbnailMode.PicturesView); var img = new BitmapImage(); img.SetSource(fileStream); mapPhotoIcons.Add(new LocationData { Position = geopoint.Position, DateCreated = photos[i].DateCreated, ImageSource = img }); } } var retMapPhotos = mapPhotoIcons.OrderBy(x => x.DateCreated).ToList(); return retMapPhotos; }
public TodoItemViewModel() { ImageSource imgSource = new Windows.UI.Xaml.Media.Imaging.BitmapImage(new Uri("ms-appx:///Assets/2017-12-17.png")); this.allItems.Add(new Models.TodoItem("完成作业", "", DateTime.Now, imgSource)); this.allItems.Add(new Models.TodoItem("完成作业", "", DateTime.Now, imgSource)); }
public void DrawImage(Point center, Size s, BitmapImage image) { Image img = new Image(); img.Source = (ImageSource)image; int imageHeight = image.PixelHeight == 0 ? 320 : image.PixelWidth; int imageWidth = image.PixelWidth == 0 ? 180 : image.PixelWidth; ScaleTransform resizeTransform = new ScaleTransform(); resizeTransform.ScaleX = (s.Width / imageHeight) * Canvas.Width; resizeTransform.ScaleY = (s.Height / imageWidth) * Canvas.Height; TranslateTransform posTransform = new TranslateTransform(); posTransform.X = center.X * Canvas.Width; posTransform.Y = center.Y * Canvas.Height; TransformGroup transform = new TransformGroup(); transform.Children.Add(resizeTransform); transform.Children.Add(posTransform); img.RenderTransform = transform; Canvas.Children.Add(img); }
/// <summary> /// Invoked when this page is about to be displayed in a Frame. /// </summary> /// <param name="e">Event data that describes how this page was reached. The Parameter /// property is typically used to configure the page.</param> protected async override void OnNavigatedTo(NavigationEventArgs e) { try { parameter = e.Parameter as FromExpositionToDiaporama; ListPhoto = new ObservableCollection<Pages.PhotoDataStructure>(); listSmallPhoto = parameter.ListPhoto; foreach (var row in listSmallPhoto) { try { StorageFile file = await Windows.Storage.StorageFile.GetFileFromPathAsync(row.PhotoData.ImagePath); StorageItemThumbnail fileThumbnail = await file.GetThumbnailAsync(ThumbnailMode.SingleItem, (uint)Constants.ScreenHeight, ThumbnailOptions.UseCurrentScale); BitmapImage bitmapImage = new BitmapImage(); bitmapImage.SetSource(fileThumbnail); ListPhoto.Add(new Pages.PhotoDataStructure() { PhotoData = row.PhotoData, Image = bitmapImage }); } catch { } } flipView.ItemsSource = ListPhoto; if (listSmallPhoto.Count > 0) pageTitle.Text = parameter.albumName; dispatcherTimer2 = new DispatcherTimer(); dispatcherTimer2.Tick += dispatcherTimer2_Tick; dispatcherTimer2.Interval = new TimeSpan(0, 0, 0, 0, 2); dispatcherTimer2.Start(); } catch (Exception excep) { Constants.ShowErrorDialog(excep, "PhotoPlayPage - OnNavigatedTo"); } }
public object Convert(object value, Type targetType, object parameter, string language) { if (value != null) { byte[] bytes = (byte[])value; BitmapImage myBitmapImage = new BitmapImage(); if (bytes.Count() > 0) { InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream(); DataWriter writer = new DataWriter(stream.GetOutputStreamAt(0)); writer.WriteBytes(bytes); writer.StoreAsync().GetResults(); myBitmapImage.SetSource(stream); } else { myBitmapImage.UriSource = new Uri("ms-appx:///Assets/firstBackgroundImage.jpg"); } return myBitmapImage; } else { return new BitmapImage(); } }
public object Convert(object value, Type targetType, object parameter, string language) { int degree = int.Parse(value.ToString()); ImageSource imgsrc; switch(degree) { case 0: imgsrc = new BitmapImage(new Uri(new Uri("ms-appx:///"), "Images/greenpin.png")); break; case 1: imgsrc = new BitmapImage(new Uri(new Uri("ms-appx:///"), "Images/yellowpin.png")); break; case 2: imgsrc = new BitmapImage(new Uri(new Uri("ms-appx:///"), "Images/orangepin.png")); break; case 3: imgsrc = new BitmapImage(new Uri(new Uri("ms-appx:///"), "Images/redpin.png")); break; default: imgsrc = new BitmapImage(new Uri(new Uri("ms-appx:///"), "Images/graypin.png")); break; } return imgsrc; }
private async void PerformFaceAnalysis(StorageFile file) { var imageInfo = await FileHelper.GetImageInfoForRendering(file.Path); NewImageSizeWidth = 300; NewImageSizeHeight = NewImageSizeWidth*imageInfo.Item2/imageInfo.Item1; var newSourceFile = await FileHelper.CreateCopyOfSelectedImage(file); var uriSource = new Uri(newSourceFile.Path); SelectedFileBitmapImage = new BitmapImage(uriSource); // start face api detection var faceApi = new FaceApiHelper(); DetectedFaces = await faceApi.StartFaceDetection(newSourceFile.Path, newSourceFile, imageInfo, "4c138b4d82b947beb2e2926c92d1e514"); // draw rectangles var color = Color.FromArgb(125, 255, 0, 0); var bg = new SolidColorBrush(color); DetectedFacesCanvas = new ObservableCollection<Canvas>(); foreach (var detectedFace in DetectedFaces) { var margin = new Thickness(detectedFace.RectLeft, detectedFace.RectTop, 0, 0); var canvas = new Canvas() { Background = bg, HorizontalAlignment = HorizontalAlignment.Left, VerticalAlignment = VerticalAlignment.Top, Height = detectedFace.RectHeight, Width = detectedFace.RectWidth, Margin = margin }; DetectedFacesCanvas.Add(canvas); } }
public object Convert(object value, Type targetType, object parameter, string language) { int size; int.TryParse(parameter as string, out size); var url = value as string; Uri uri; if (url == null) uri = value as Uri; else uri = new Uri(url); if (uri == null) return null; var bitmap = new BitmapImage(uri); if (size != 0) { bitmap.DecodePixelHeight = size; bitmap.DecodePixelWidth = size; } return bitmap; }
public MainPage() { this.InitializeComponent(); // create Flickr feed reader for unicorn images var reader = new FlickrReader("unicorn"); TimeSpan period = TimeSpan.FromSeconds(5); // display neew images every five seconds ThreadPoolTimer PeriodicTimer = ThreadPoolTimer.CreatePeriodicTimer( async (source) => { // get next image var image = await reader.GetImage(); if (image != null) { // we have to update UI in UI thread only await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { // create and load bitmap BitmapImage bitmap = new BitmapImage(); bitmap.UriSource = new Uri(image, UriKind.Absolute); // display image splashImage.Source = bitmap; } ); } }, period); }
public static async Task <Windows.Storage.Streams.IRandomAccessStream> GetStreamFromUrl(string url) { Windows.Storage.Streams.IRandomAccessStream returnStream = null; try { using (var cli = new Windows.Web.Http.HttpClient()) { var resp = await cli.GetAsync(new Uri(url)); var b = new Windows.UI.Xaml.Media.Imaging.BitmapImage(); if (resp != null && resp.StatusCode == Windows.Web.Http.HttpStatusCode.Ok) { using (var stream = await resp.Content.ReadAsInputStreamAsync()) { var memStream = new MemoryStream(); if (memStream != null) { await stream.AsStreamForRead().CopyToAsync(memStream); memStream.Position = 0; returnStream = memStream.AsRandomAccessStream(); } } } } } catch (Exception e) { System.Diagnostics.Debug.WriteLine("Error while downloading the attachment: " + e.Message); } return(returnStream); }
public static void FixUpXaml(Paragraph paragraph) { for(int i = 0; i < paragraph.Inlines.Count; i++) { Inline inline = paragraph.Inlines[i]; ImageInline imageInline; if (TryCreate(inline, out imageInline)) { BitmapImage bi = new BitmapImage(new Uri(imageInline.FilePath)); Image image = new Image(); image.Source = bi; image.Stretch = Stretch.Uniform; InlineUIContainer container = new InlineUIContainer(); image.HorizontalAlignment = Windows.UI.Xaml.HorizontalAlignment.Center; image.VerticalAlignment = Windows.UI.Xaml.VerticalAlignment.Center; image.Stretch = Stretch.Uniform; container.Child = image; paragraph.Inlines[i] = container; // if this is an image only paragraph. Center it if (paragraph.Inlines.Count == 1) { paragraph.TextAlignment = Windows.UI.Xaml.TextAlignment.Center; } } } }
private async void SelectPictureButton_Click(object sender, RoutedEventArgs e) { var picker = new Windows.Storage.Pickers.FileOpenPicker(); picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail; picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.PicturesLibrary; picker.FileTypeFilter.Add(".jpg"); picker.FileTypeFilter.Add(".jpeg"); picker.FileTypeFilter.Add(".png"); Windows.Storage.StorageFile file = await picker.PickSingleFileAsync(); if (file != null) { using (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); Background.Source = bitmapImage; } } else { this.textBlock.Text = "Operation cancelled."; } }
public async Task<BitmapImage> GetPhotoAsync(string photoUrl, string token) { using (var client = new HttpClient()) { try { var request = new HttpRequestMessage(HttpMethod.Get, new Uri(photoUrl)); BitmapImage bitmap = null; request.Headers.Add("Authorization", "Bearer " + token); var response = await client.SendAsync(request); var stream = await response.Content.ReadAsStreamAsync(); if (response.IsSuccessStatusCode) { using (var memStream = new MemoryStream()) { await stream.CopyToAsync(memStream); memStream.Seek(0, SeekOrigin.Begin); bitmap = new BitmapImage(); await bitmap.SetSourceAsync(memStream.AsRandomAccessStream()); } return bitmap; } else { Debug.WriteLine("Unable to find an image at this endpoint."); bitmap = new BitmapImage(new Uri("ms-appx:///assets/UserDefault.png", UriKind.RelativeOrAbsolute)); return bitmap; } } catch (Exception e) { Debug.WriteLine("Could not get the thumbnail photo: " + e.Message); return null; } } }
public static BitmapImage ImageFromRelativePath(FrameworkElement parent, string path) { var uri = new Uri(parent.BaseUri, path); BitmapImage result = new BitmapImage(); result.UriSource = uri; return result; }
public async void LoadData(IEnumerable<XElement> sprites, StorageFile spriteSheetFile, string appExtensionId) { var bitmapImage = new BitmapImage(); using (var stream = await spriteSheetFile.OpenReadAsync()) { await bitmapImage.SetSourceAsync(stream); } //xaml List<ImageListItem> listOfImages = new List<ImageListItem>(); foreach (var sprite in sprites) { var row = int.Parse(sprite.Attributes("Row").First().Value); var col = int.Parse(sprite.Attributes("Column").First().Value); var brush = new ImageBrush(); brush.ImageSource = bitmapImage; brush.Stretch = Stretch.UniformToFill; brush.AlignmentX = AlignmentX.Left; brush.AlignmentY = AlignmentY.Top; brush.Transform = new CompositeTransform() { ScaleX = 2.35, ScaleY = 2.35, TranslateX = col * (-140), TranslateY = row * (-87) }; listOfImages.Add(new ImageListItem() { Title = sprite.Attributes("Title").First().Value, SpriteSheetBrush = brush, File = sprite.Attributes("File").First().Value, AppExtensionId = appExtensionId }); } lbPictures.ItemsSource = listOfImages; }
public BannerControl(GridView bannerCanv, XCollection<Banner> banners, Frame frame) { _frame = frame; bannerCanv.Items?.Clear(); var deviceWidth = Window.Current.CoreWindow.Bounds.Width; foreach (var banner in banners) { var bannerBitmap = new BitmapImage {UriSource = new Uri(banner.Image, UriKind.RelativeOrAbsolute)}; var bannerImage = SystemInfoHelper.IsMobile() || deviceWidth < 800 ? new Image { Source = bannerBitmap, Stretch = Stretch.Fill, MaxWidth = deviceWidth + 5 } : new Image { Source = bannerBitmap, Stretch = Stretch.Fill, MaxHeight = bannerCanv.MaxHeight }; bannerImage.Tapped += OnBannerTap; bannerImage.Tag = banner; bannerCanv.Visibility = Visibility.Visible; bannerImage.Visibility = Visibility.Visible; bannerCanv.Items?.Add(bannerImage); } if (SystemInfoHelper.IsMobile() || deviceWidth < 800) bannerCanv.MaxHeight = deviceWidth / 2.46; }
public async static Task<BitmapImage> GetImageAsync(StorageFile storageFile) { BitmapImage bitmapImage = new BitmapImage(); FileRandomAccessStream stream = (FileRandomAccessStream)await storageFile.OpenAsync(FileAccessMode.Read); bitmapImage.SetSource(stream); return bitmapImage; }
/// <summary> /// 他のアプリケーションがこのアプリケーションを介してコンテンツの共有を求めた場合に呼び出されます。 /// </summary> /// <param name="args">Windows と連携して処理するために使用されるアクティベーション データ。</param> public async void Activate(ShareTargetActivatedEventArgs args) { this.currentModel = BookmarkerModel.GetDefault(); await this.currentModel.LoadAsync(); this._shareOperation = args.ShareOperation; // ビュー モデルを使用して、共有されるコンテンツのメタデータを通信します var shareProperties = this._shareOperation.Data.Properties; var thumbnailImage = new BitmapImage(); this.DefaultViewModel["Title"] = shareProperties.Title; this.DefaultViewModel["Description"] = shareProperties.Description; this.DefaultViewModel["Image"] = thumbnailImage; this.DefaultViewModel["Sharing"] = false; this.DefaultViewModel["ShowImage"] = false; this.DefaultViewModel["Comment"] = String.Empty; this.DefaultViewModel["SupportsComment"] = true; this.addBookmarkView.Title = shareProperties.Title; this.addBookmarkView.Uri = (await this._shareOperation.Data.GetUriAsync()).ToString(); Window.Current.Content = this; Window.Current.Activate(); // 共有されるコンテンツの縮小版イメージをバックグラウンドで更新します if (shareProperties.Thumbnail != null) { var stream = await shareProperties.Thumbnail.OpenReadAsync(); thumbnailImage.SetSource(stream); this.DefaultViewModel["ShowImage"] = true; } }
public async Task<Windows.UI.Xaml.Media.Imaging.BitmapImage> GetBitmapAsync() { var image = new Windows.UI.Xaml.Media.Imaging.BitmapImage(); stream.Seek(0); image.SetSource(stream); return image; }
/// <summary> /// Gets current users profile. /// </summary> /// <returns> /// The current users profile. /// </returns> public async Task <ProfileUser> GetProfile() { try { if (Profile != null) { return(Profile); } else { var spotify = await Authentication.GetSpotifyClientAsync(); if (spotify != null) { var user = await spotify.UserProfile.Current(); Windows.UI.Xaml.Media.ImageSource image = null; if (user.Images != null) { image = new Windows.UI.Xaml.Media.Imaging.BitmapImage(new Uri(user.Images.FirstOrDefault().Url)); } Profile = new ProfileUser(user.Id, user.DisplayName, image); return(Profile); } return(null); } } catch (Exception e) { ViewModels.Helpers.DisplayDialog("Error", e.Message); return(null); } }
public async Task<Windows.UI.Xaml.Media.ImageSource> LoadImageAsync(ImageSource imagesoure, CancellationToken cancellationToken = new CancellationToken()) { var imageLoader = imagesoure as UriImageSource; if (imageLoader?.Uri == null) return null; Stream streamImage = await imageLoader.GetStreamAsync(cancellationToken); if (streamImage == null || !streamImage.CanRead) { return null; } using (IRandomAccessStream stream = streamImage.AsRandomAccessStream()) { try { var image = new BitmapImage(); await image.SetSourceAsync(stream); return image; } catch (Exception ex) { Debug.WriteLine(ex); // Because this literally throws System.Exception // According to https://msdn.microsoft.com/library/windows/apps/jj191522 // this can happen if the image data is bad or the app is close to its // memory limit return null; } } }
/// <summary> /// Invoked when another application wants to share content through this application. /// </summary> /// <param name="args">Activation data used to coordinate the process with Windows.</param> public async void Activate(ShareTargetActivatedEventArgs args) { this._shareOperation = args.ShareOperation; // Communicate metadata about the shared content through the view model var shareProperties = this._shareOperation.Data.Properties; var thumbnailImage = new BitmapImage(); this.DefaultViewModel["Title"] = shareProperties.Title; this.DefaultViewModel["Description"] = shareProperties.Description; this.DefaultViewModel["Image"] = thumbnailImage; this.DefaultViewModel["Sharing"] = false; this.DefaultViewModel["ShowImage"] = false; this.DefaultViewModel["Comment"] = String.Empty; this.DefaultViewModel["SupportsComment"] = true; Window.Current.Content = this; Window.Current.Activate(); Detector dt = new Detector(_shareOperation.Data); dt.Detect(); this.DataContext = dt.Detected; // Update the shared content's thumbnail image in the background if (shareProperties.Thumbnail != null) { var stream = await shareProperties.Thumbnail.OpenReadAsync(); thumbnailImage.SetSource(stream); this.DefaultViewModel["ShowImage"] = true; } }
public MediaPlayer() { this.InitializeComponent(); ImageBrush IBbackground = new ImageBrush(); BitmapImage bmpBack = new BitmapImage(new Uri("ms-appx:///Assets/backG.jpg")); IBbackground.ImageSource = bmpBack; grBackGround.Background = IBbackground; ImageBrush IBback01 = new ImageBrush(); BitmapImage bmpBack01 = new BitmapImage(new Uri("ms-appx:///Assets/back01.jpg")); IBback01.ImageSource = bmpBack01; grBack01.Background = IBback01; ImageBrush IBback02 = new ImageBrush(); BitmapImage bmpBack02 = new BitmapImage(new Uri("ms-appx:///Assets/back2.jpg")); IBback02.ImageSource = bmpBack02; grBack02.Background = IBback02; ImageBrush IBback03 = new ImageBrush(); BitmapImage bmpBack03 = new BitmapImage(new Uri("ms-appx:///Assets/back3.jpg")); IBback03.ImageSource = bmpBack03; grBack03.Background = IBback03; cbSite.Items.Add("mp3.zing.vn"); cbSite.Items.Add("nhaccuatui.com"); myMedia.MediaEnded += media_MediaEnded; }
private async void BackgroundButton_Click(object sender, RoutedEventArgs e) { // Clear previous returned file name, if it exists, between iterations of this scenario OutputTextBlock.Text = ""; FileOpenPicker openPicker = new FileOpenPicker(); openPicker.ViewMode = PickerViewMode.Thumbnail; openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary; openPicker.FileTypeFilter.Add(".jpg"); openPicker.FileTypeFilter.Add(".jpeg"); openPicker.FileTypeFilter.Add(".png"); StorageFile file = await openPicker.PickSingleFileAsync(); if (file != null) { // Application now has read/write access to the picked file OutputTextBlock.Text = "Picked photo: " + file.Name; BitmapImage img = new BitmapImage(); img = await ImageHelpers.LoadImage( file ); MyPicture.Source = img; } else { OutputTextBlock.Text = "Operation cancelled."; } }
private void BlankPage_CommandsRequested(SettingsPane sender, SettingsPaneCommandsRequestedEventArgs args) { SettingsCommand cmd = new SettingsCommand("sample", "Sample Custom Setting", (x) => { SettingsFlyout settings = new SettingsFlyout(); settings.FlyoutWidth = (Callisto.Controls.SettingsFlyout.SettingsFlyoutWidth)Enum.Parse(typeof(Callisto.Controls.SettingsFlyout.SettingsFlyoutWidth), settingswidth.SelectionBoxItem.ToString()); //settings.HeaderBrush = new SolidColorBrush(Colors.Orange); //settings.Background = new SolidColorBrush(Colors.White); settings.HeaderText = "Foo Bar Custom Settings"; BitmapImage bmp = new BitmapImage(new Uri("ms-appx:///Assets/SmallLogo.png")); settings.SmallLogoImageSource = bmp; StackPanel sp = new StackPanel(); ToggleSwitch ts = new ToggleSwitch(); ts.Header = "Download updates automatically"; Button b = new Button(); b.Content = "Test"; sp.Children.Add(ts); sp.Children.Add(b); settings.Content = sp; settings.IsOpen = true; ObjectTracker.Track(settings); }); args.Request.ApplicationCommands.Add(cmd); }
/// <summary> /// Get the user's photo. /// </summary> /// <param name="user">The target user.</param> /// <returns></returns> public async Task<BitmapImage> GetUserThumbnailPhotoAsync(IUser user) { BitmapImage bitmap = null; try { // The using statement ensures that Dispose is called even if an // exception occurs while you are calling methods on the object. using (var dssr = await user.ThumbnailPhoto.DownloadAsync()) using (var stream = dssr.Stream) using (var memStream = new MemoryStream()) { await stream.CopyToAsync(memStream); memStream.Seek(0, SeekOrigin.Begin); bitmap = new BitmapImage(); await bitmap.SetSourceAsync(memStream.AsRandomAccessStream()); } } catch(ODataException) { // Something went wrong retrieving the thumbnail photo, so set the bitmap to a default image bitmap = new BitmapImage(new Uri("ms-appx:///assets/UserDefaultSignedIn.png", UriKind.RelativeOrAbsolute)); } return bitmap; }
private async void CreateClick(Object sender, RoutedEventArgs e) { //创建model并修改vm var dialog = new ContentDialog() { Title = "提示", PrimaryButtonText = "确定", }; if (Title.Text == "" || Detail.Text == "") { dialog.Content += "Title栏和Detail栏不可为空!\n"; } DateTime now = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day); if (Date.Date.CompareTo(now) < 0) { dialog.Content += "DueDate不可设为过去的日期!\n"; } if (dialog.Content != null) { await dialog.ShowAsync(); return; } if (ViewModels.currentId == -1) { ViewModels.AddItem(Title.Text, Detail.Text, Date.Date, Img.Source); } else { ViewModels.ChangeItem(ViewModels.currentId, Title.Text, Detail.Text, Date.Date, Img.Source); } ViewModels.currentId = -1; Title.Text = ""; Detail.Text = ""; Date.Date = DateTime.Now; CreateBut.Content = "Create"; Windows.UI.Xaml.Media.Imaging.BitmapImage bit = new Windows.UI.Xaml.Media.Imaging.BitmapImage(); bit.UriSource = new Uri(Img.BaseUri, "../Assets/icon.jpg"); Img.Source = bit; //磁贴 XmlDocument tilexml = new XmlDocument(); tilexml.LoadXml(File.ReadAllText("Tile.xml")); XmlNodeList tileTextAttr = tilexml.GetElementsByTagName("text"); for (int i = 0; i < tileTextAttr.Count; i++) { ((XmlElement)tileTextAttr[i]).InnerText = Viewmodels.MainPageVM.Instance.Items[Viewmodels.MainPageVM.Instance.Items.Count - 1].topic; i++; ((XmlElement)tileTextAttr[i]).InnerText = Viewmodels.MainPageVM.Instance.Items[Viewmodels.MainPageVM.Instance.Items.Count - 1].content; } TileNotification notifi = new TileNotification(tilexml); var updator = TileUpdateManager.CreateTileUpdaterForApplication(); updator.Update(notifi); updator.EnableNotificationQueue(true); }
public async Task <Windows.UI.Xaml.Media.Imaging.BitmapImage> GetBitmapAsync() { var image = new Windows.UI.Xaml.Media.Imaging.BitmapImage(); stream.Seek(0); image.SetSource(stream); return(image); }
public async Task loadFloorplan() { fp = await APIService.Instance.getFloorplan(); if (fp != null && APIService.Instance.status) { FloorplanSource = new Windows.UI.Xaml.Media.Imaging.BitmapImage(new Uri(APIService.Instance.apiURL + fp.Image)); await loadDevices(fp); } }
private async void Button_Click_3(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); displayImage.Source = bitmapImage; this.DataContext = file; } try { var db = new SQLite.SQLiteConnection(App.DBPath); var emptab = (db.Table <lawyer>().Where(em => em.username == txt1.Text)).Single(); var targetFile = await ApplicationData.Current.LocalFolder.CreateFileAsync(emptab.username + ".jpg"); if (targetFile != null) { //await file.MoveAndReplaceAsync(targetFile); await file.CopyAndReplaceAsync(targetFile); } } catch (Exception ex) { var var_name = new MessageDialog("Unable to update profile picture\nPlease try after sometime."); var_name.Commands.Add(new UICommand("OK")); var_name.ShowAsync(); } // await file.CopyAsync(ApplicationData.Current.LocalFolder); }
void InitializeME() { var me = new MediaElement(); m = me; var s = CreateSourceME(); if (s is Uri) { me.Source = (Uri)s; } else { me.SetPlaybackSource(s as IMediaPlaybackSource); } if (this.enableMTC.IsChecked.Value) { me.AreTransportControlsEnabled = true; me.TransportControls.IsNextTrackButtonVisible = true; me.TransportControls.IsPreviousTrackButtonVisible = true; //me.TransportControls.IsStopEnabled = true; me.AutoPlay = false; } if (sizeChk.IsChecked.Value) { me.Width = 200.0 * scale; me.Height = 170.0 * scale; } if (this.poster.IsChecked.Value) { var bitmapImage = new Windows.UI.Xaml.Media.Imaging.BitmapImage(); var urlStr = MediaData.PosterUrlStr; bitmapImage.UriSource = new Uri(urlStr); me.PosterSource = bitmapImage; } if (this.enableFullWindow.IsChecked.Value) { me.IsFullWindow = true; } me.Stretch = GetStretchMode(this.stretchMode.SelectedIndex); MediaPanel.Children.Add(me); Log.Text = "Legacy made it"; me.DoubleTapped += this.OnDoubleTapped; me.Tapped += this.OnTapped; me.TransportControls.DoubleTapped += this.OnDoubleTapped; me.UpdateLayout(); this.UpdateLayout(); }
public async Task <Windows.UI.Xaml.Media.Imaging.BitmapImage> GetBitmapAsync() { var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream(); await RenderToStreamAsync(stream); var result = new Windows.UI.Xaml.Media.Imaging.BitmapImage(); await result.SetSourceAsync(stream); return(result); }
private void CancelClick(Object sender, RoutedEventArgs e) { Title.Text = ""; Detail.Text = ""; Date.Date = DateTime.Now; ViewModels.currentId = -1; ListView.SelectedIndex = -1; CreateBut.Content = "Create"; Windows.UI.Xaml.Media.Imaging.BitmapImage bit = new Windows.UI.Xaml.Media.Imaging.BitmapImage(); bit.UriSource = new Uri(Img.BaseUri, "../Assets/icon.jpg"); Img.Source = bit; }
Image[,] winCombo = new Image[4, 4]; //winning combination //Lets the user choose an image from the local drive. If an image is chosen, a timer is started. //Also, this method calls the PlaceImg method to cut and shuffle. private async void Button_Click(object sender, RoutedEventArgs e) { loser.Visibility = Visibility.Collapsed; winner.Visibility = Visibility.Collapsed; // Set up the file picker. 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"); Error.Visibility = Visibility.Collapsed; // 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. // The 'using' block ensures the stream is disposed // after the image is loaded. using (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); image1.Source = bitmapImage; BitmapDecoder decoder = await BitmapDecoder.CreateAsync(fileStream); PlaceImg(decoder); } play = true; Timer1 = new Windows.UI.Xaml.DispatcherTimer(); Timer1.Interval = TimeSpan.FromMilliseconds(1000); Timer1.Tick += Timer1_Tick; if (Timer1.IsEnabled) { Timer1.Stop(); } Timer1.Start(); time = GameTime; Choose.IsEnabled = false; Capture.IsEnabled = false; } }
private void Bottom_Delete_Click(Object s, RoutedEventArgs e) { ViewModels.RemoveItem(ViewModels.currentId); Title.Text = ""; Detail.Text = ""; Date.Date = DateTimeOffset.Now; Windows.UI.Xaml.Media.Imaging.BitmapImage bit = new Windows.UI.Xaml.Media.Imaging.BitmapImage(); bit.UriSource = new Uri(Img.BaseUri, "../Assets/icon.jpg"); Img.Source = bit; CreateBut.Content = "Create"; ViewModels.currentId = -1; this.DataContext = ViewModels; }
private async void CancelButton_Click(object sender, RoutedEventArgs e) { title.Text = ""; details.Text = ""; date.Date = DateTime.Now; time.Time = DateTime.Now.TimeOfDay; RandomAccessStreamReference img = RandomAccessStreamReference.CreateFromUri(new Uri("ms-appx:///Assets/fruit.jpg")); IRandomAccessStream stream = await img.OpenReadAsync(); BitmapImage bmp = new Windows.UI.Xaml.Media.Imaging.BitmapImage(); bmp.SetSource(stream); pic.Source = bmp; }
/// <summary> /// Gets the image. /// </summary> /// <param name="source">The source</param> /// <returns></returns> internal Image GetImage(ImageSource source) { if (source == null) { return(null); } if (this.imageCaches.ContainsKey(source)) { return(this.imageCaches[source]); } Windows.UI.Xaml.Media.Imaging.BitmapImage image = source as Windows.UI.Xaml.Media.Imaging.BitmapImage; Stream stream = null; try { if ((image != null) && (image.UriSource != null)) { try { Uri uri1 = ((Windows.UI.Xaml.Media.Imaging.BitmapImage)source).UriSource; Uri uri = new Uri("ms-appx:///" + uri1.LocalPath.TrimStart(new char[] { '/' })); stream = WindowsRuntimeStreamExtensions.AsStreamForRead(StorageFile.GetFileFromApplicationUriAsync(uri).GetResultSynchronously <StorageFile>().OpenSequentialReadAsync().GetResultSynchronously <IInputStream>()); } catch (Exception) { stream = Utility.GetImageStream(source, ImageFormat.Png, PictureSerializationMode.Normal); } } else if (image != null) { stream = Utility.GetImageStream(source, ImageFormat.Png, PictureSerializationMode.Normal); } if (stream != null) { byte[] buffer = new byte[stream.Length]; stream.Read(buffer, 0, buffer.Length); Image instance = Image.GetInstance(buffer); this.imageCaches.Add(source, instance); stream.Dispose(); return(instance); } return(null); } catch { return(null); } }
private async void SetCover() { bool isBGSet = (bool)ApplicationSettingsHelper.ReadSettingsValue(AppConstants.IsBGImageSet); bool isBGCover = (bool)ApplicationSettingsHelper.ReadSettingsValue(AppConstants.ShowCoverAsBackground); BitmapImage originalCover = await Library.Current.GetOriginalCover(songs.FirstOrDefault().Path, false); if (isBGSet) { string path = ApplicationSettingsHelper.ReadSettingsValue(NextPlayerDataLayer.Constants.AppConstants.BackgroundImagePath) as string; if (path != null && path != "") { BackgroundImage = new Windows.UI.Xaml.Media.Imaging.BitmapImage(new Uri(path, UriKind.RelativeOrAbsolute)); } if (isBGCover) { if (originalCover.PixelHeight > 0) { BackgroundImage = originalCover; } } } else { BackgroundImage = new BitmapImage(); if (isBGCover) { if (originalCover.PixelHeight > 0) { BackgroundImage = originalCover; } } } if (originalCover.PixelHeight > 0) { Cover = originalCover; } else { Cover = await Library.Current.GetDefaultCover(false); if (!isBGSet) { noBGForThisView = true; ((SolidColorBrush)App.Current.Resources["TransparentAlbumInfoColor"]).Color = Windows.UI.Color.FromArgb(0, 0, 0, 0); ((SolidColorBrush)App.Current.Resources["TransparentAlbumBGImageColor"]).Color = Windows.UI.Color.FromArgb(0, 0, 0, 0); } } }
/// <summary> /// Select_Image_Click allows user to select a an image using filepicker. /// Filepath is supposed to start at PicturesLibrary /// Image selected is then sent to mediaplayer.postersource on page. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private async void Select_Image_Click(object sender, RoutedEventArgs e) { var ImagePicker = new Windows.Storage.Pickers.FileOpenPicker(); string[] ImageTypes = new string[] { ".jpg" }; //make a collection of all Pictures you want //Add your ImageTypes to the ImageTypeFilter list of ImagePicker. foreach (string ImageType in ImageTypes) { ImagePicker.FileTypeFilter.Add(ImageType); } //Set picker start location to the Saved Picture library ImagePicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary; ImagePicker.ViewMode = PickerViewMode.Thumbnail; // Filter to include a sample subset of file types. ImagePicker.FileTypeFilter.Clear(); ImagePicker.FileTypeFilter.Add(".bmp"); ImagePicker.FileTypeFilter.Add(".png"); ImagePicker.FileTypeFilter.Add(".jpeg"); ImagePicker.FileTypeFilter.Add(".jpg"); //Retrieve file from picker StorageFile file = await ImagePicker.PickSingleFileAsync(); if (file != null) { // Open a stream for the selected file. // The 'using' block ensures the stream is disposed // after the image is loaded. using (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); System.Diagnostics.Debug.WriteLine("bitmap"); //System.Diagnostics.Debug.WriteLine(bitmapImage.UriSource.ToString()); System.Diagnostics.Debug.WriteLine("bitmap"); _mediaPlayer.PosterSource = bitmapImage; System.Diagnostics.Debug.WriteLine(_mediaPlayer.PosterSource.ToString()); } } }
public bool LoadGraphicsPNGImageFromLocalStore(string filename, Image graphicsImage) { AutoResetEvent DisplayComplete = new AutoResetEvent(false); bool displayedOK = true; InvokeOnUIThread( async() => { try { if (graphicsImage.Opacity == 1) { await FadeElements.FadeElementOpacityAsync(graphicsImage, 1, 0, new TimeSpan(0, 0, 1)); } var file = await ApplicationData.Current.LocalFolder.GetFileAsync(filename); var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read); var bitmapImage = new Windows.UI.Xaml.Media.Imaging.BitmapImage(); await bitmapImage.SetSourceAsync(stream); graphicsImage.Source = bitmapImage; graphicsImage.Width = graphicsCanvas.ActualWidth; graphicsImage.Height = graphicsCanvas.ActualHeight; } catch { displayedOK = false; graphicsImage.Source = null; } finally { await FadeElements.FadeElementOpacityAsync(graphicsImage, 0, 1, new TimeSpan(0, 0, 1)); } DisplayComplete.Set(); }); DisplayComplete.WaitOne(); return(displayedOK); }
private void Add_AppBar_Button_Click(object sender, RoutedEventArgs e) { if (InlineToDoItemViewGrid.Visibility != Visibility.Visible) { Frame.Navigate(typeof(NewPage), ViewModel); } else { title.Text = ""; details.Text = ""; this.date.Date = DateTime.Now; Windows.UI.Xaml.Media.Imaging.BitmapImage bit = new Windows.UI.Xaml.Media.Imaging.BitmapImage(); bit.UriSource = new Uri(image.BaseUri, "Assets/qianyang.jpeg"); image.Source = bit; UpdateButton.Content = "Create"; } }
private async void pnlViewPhoto_Tapped(object sender, TappedRoutedEventArgs e) { FileOpenPicker openPicker = new FileOpenPicker(); openPicker.ViewMode = PickerViewMode.Thumbnail; openPicker.SuggestedStartLocation = PickerLocationId.Desktop; openPicker.FileTypeFilter.Add(".jpeg"); openPicker.FileTypeFilter.Add(".jpg"); openPicker.FileTypeFilter.Add(".png"); openPicker.FileTypeFilter.Add(".bmp"); try { var files = await openPicker.PickMultipleFilesAsync(); // File picker opened to select the files here if (files.Count > 0)//if the no of files selected is greater than zero then they are converted to bitmaps and then displayed in flipview { foreach (Windows.Storage.StorageFile file in files) { var bitmapImage = new Windows.UI.Xaml.Media.Imaging.BitmapImage(); using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite)) { await bitmapImage.SetSourceAsync(stream);// Bitmap source is set to the stream of the file } Image imgSelected = new Image(); imgSelected.Height = 350; imgSelected.Width = 350; imgSelected.Source = bitmapImage; ImageView.Items.Add(imgSelected);//Bitmap is added to display in the flipview } } } catch (Exception exp) { var msg = new MessageDialog(exp.ToString()); await msg.ShowAsync(); } }