Exemple #1
0
        private async void Update()
        {
            var writer1 = new BarcodeWriter
            {
                Format = BarcodeFormat.QR_CODE,
                Options = new ZXing.Common.EncodingOptions
                {
                    Height = 200,
                    Width = 200
                },

            };

            var image = writer1.Write(Text);//Write(text);


            using (InMemoryRandomAccessStream ms = new InMemoryRandomAccessStream())
            {
                using (DataWriter writer = new DataWriter(ms.GetOutputStreamAt(0)))
                {
                    writer.WriteBytes(image);
                    await writer.StoreAsync();
                }

                var output = new BitmapImage();
                await output.SetSourceAsync(ms);
                ImageSource = output;
            }


        }
Exemple #2
0
        private async void ReadFolderPick()
        {
            foreach (var temp in FolderStorage)
            {
                try
                {
                    temp.FolderStorage =
                        await StorageApplicationPermissions.FutureAccessList.GetFolderAsync(temp.Token);
                }
                catch (Exception)
                {

                }
            }

            foreach (var temp in FolderStorage)
            {
                //image
                try
                {
                    StorageFolder folder = temp.FolderStorage;
                    string str = "image";
                    folder = await folder.GetFolderAsync(str);
                    StorageFile file = await folder.GetFileAsync(str + ".png");
                    BitmapImage image = new BitmapImage();
                    await image.SetSourceAsync(await file.OpenAsync(FileAccessMode.Read));
                    temp.Image = image;
                }
                catch 
                {
                   
                }
            }
        }
Exemple #3
0
        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.";
            }
        }
Exemple #4
0
    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);
    }
 private static async Task<BitmapImage> AsBitmapImage(this StorageFile file)
 {
     var stream = await file.OpenAsync(FileAccessMode.Read);
     var bitmapImage = new BitmapImage();
     await bitmapImage.SetSourceAsync(stream);
     return bitmapImage;
 }
        /// <summary>
        /// Triggered when the Capture Photo button is clicked by the user
        /// </summary>
        private async void Capture_Click(object sender, RoutedEventArgs e)
        {
            // Hide the capture photo button
            CaptureButton.Visibility = Visibility.Collapsed;

            // Capture current frame from webcam, store it in temporary storage and set the source of a BitmapImage to said photo
            currentIdPhotoFile = await webcam.CapturePhoto();
            var photoStream = await currentIdPhotoFile.OpenAsync(FileAccessMode.ReadWrite);
            BitmapImage idPhotoImage = new BitmapImage();
            await idPhotoImage.SetSourceAsync(photoStream);
            

            // Set the soruce of the photo control the new BitmapImage and make the photo control visible
            IdPhotoControl.Source = idPhotoImage;
            IdPhotoControl.Visibility = Visibility.Visible;

            // Collapse the webcam feed or disabled feed grid. Make the enter user name grid visible.
            WebcamFeed.Visibility = Visibility.Collapsed;
            DisabledFeedGrid.Visibility = Visibility.Collapsed;

            UserNameGrid.Visibility = Visibility.Visible;
            

            // Dispose photo stream
            photoStream.Dispose();
        }
        private async void Page_Loaded(object sender, RoutedEventArgs e)
        {
            ClearErrorMessage();
            saveButton.Focus(FocusState.Keyboard);
            _savedAppSettings = await ApplicationUtilities.GetAppSettings();
            if (_savedAppSettings != null && _savedAppSettings.CompanyImage.Length > 0)
            {
                Uri uri = new Uri(@"ms-appdata:///local/" + _savedAppSettings.CompanyImage, UriKind.Absolute);
                try
                {
                    var file = await StorageFile.GetFileFromApplicationUriAsync(uri);
                    using (var fileStream = await file.OpenAsync(FileAccessMode.Read))
                    {
                        BitmapImage bitmapImage = new BitmapImage
                        {
                            DecodePixelHeight = 300,
                            DecodePixelWidth = 300
                        };
                        await bitmapImage.SetSourceAsync(fileStream);
                        CompanyImage.Source = bitmapImage;
                    }
                }
                catch (Exception)
                {
                }

            }
        }
Exemple #8
0
 // TODO: test data
 private async void OnLoaded(object sender, RoutedEventArgs e)
 {
     var file = await Package.Current.InstalledLocation.GetFileAsync(@"Assets\service-icon.png");
     var videoFile = await Package.Current.InstalledLocation.GetFileAsync(@"Assets\video-test.mp4");
     var bitmap = new BitmapImage();
     await bitmap.SetSourceAsync(
             await ConvertionExtensions.ConvertToInMemoryStream(await ConvertionExtensions.ReadFile(file)));
     Details = new RecipientDetailsInfo
     {
         Name = "Recipient",
         Age = 24,
         Description = Enumerable.Repeat("I'm so depressed...", 20).Aggregate(string.Empty, (x, y) => x + y),
         Image = bitmap,
         AdditionalImages = Enumerable.Repeat(bitmap, 10).Cast<ImageSource>().ToArray(),
         Wishes = new WishInfo[]
         {
             new ImageWishInfo {Description = "myWish", Image = bitmap},
             new VideoWishInfo
             {
                 Source = await ConvertionExtensions.ReadFile(videoFile),
                 Description = "myVideoWish",
                 MimeType = "video/mp4"
             }
         }
     };
 }
Exemple #9
0
        /// <summary>
        /// DOwnloads a picture from the specified url.
        /// </summary>
        /// <param name="uri">The url of the image.</param>
        /// <returns>The downloaded image.</returns>
        public async static Task<Image> LoadImage(Uri uri)
        {
            if (uri == null)
            {
                throw new ArgumentException("The uri object must not be null.");
            }

            try
            {                
                var streamRef = RandomAccessStreamReference.CreateFromUri(uri);

                using (IRandomAccessStreamWithContentType fileStream = await streamRef.OpenReadAsync())
                {
                    var bitmapImage = new BitmapImage(uri);                    
                    await bitmapImage.SetSourceAsync(fileStream);
                    var img = new Image();
                    img.Source = bitmapImage;
                    return img;
                }                
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Couldn't load the image: {0}", ex.Message);
            }

            return null;
        }
        /// <summary>
        /// Returns a Bitmap image for a give random access stream 
        /// </summary>
        /// <param name="stream">Random access stream for which the bitmap needs to be generated</param>
        /// <return Type="BitmapImage">Bitmap for the given stream</return>
        static async public Task<BitmapImage> GetImageFromFile(IRandomAccessStream stream)
        {
            BitmapImage bmp = new BitmapImage();

            await bmp.SetSourceAsync(stream);
            return bmp;
        }
		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;
				}
			}
		}
        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<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;
        }
      }

    }
Exemple #14
0
        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;
        }
Exemple #15
0
        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;
                }
            }

        }
        // Fetches all the data for the specified file
        public async static Task<FileItem> fromStorageFile(StorageFile f, CancellationToken ct)
        {
            FileItem item = new FileItem();
            item.Filename = f.DisplayName;
            
            // Block to make sure we only have one request outstanding
            await gettingFileProperties.WaitAsync();

            BasicProperties bp = null;
            try
            {
                bp = await f.GetBasicPropertiesAsync().AsTask(ct);
            }
            catch (Exception) { }
            finally
            {
                gettingFileProperties.Release();
            }

            ct.ThrowIfCancellationRequested();

            item.Size = (int)bp.Size;
            item.Key = f.FolderRelativeId;

            StorageItemThumbnail thumb = await f.GetThumbnailAsync(ThumbnailMode.SingleItem).AsTask(ct);
            ct.ThrowIfCancellationRequested();
            BitmapImage img = new BitmapImage();
            await img.SetSourceAsync(thumb).AsTask(ct);

            item.ImageData = img;
            return item;
        }
        public static async Task<BitmapImage> LoadAsync(StorageFolder folder, string fileName)
        {
            BitmapImage bitmap = new BitmapImage();

            var file = await folder.GetFileByPathAsync(fileName);
            return await bitmap.SetSourceAsync(file);
        }
        private async void seleccionarImagen(object sender, RoutedEventArgs e)
        {
            FileOpenPicker picker = new FileOpenPicker();
            picker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
            picker.FileTypeFilter.Add(".png");
            file = await picker.PickSingleFileAsync();

            BitmapImage image = new BitmapImage();
            try
            {
                using (var stream = await file.OpenAsync(FileAccessMode.Read))
                {
                    await image.SetSourceAsync(stream);
                }
                ImageBrush brush = new ImageBrush();
                brush.Stretch = Stretch.UniformToFill;
                brush.ImageSource = image;
                imagen.Fill = brush;
            }
            catch (Exception exception)
            {

            }
            
        }
        /// <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 AddButtonClick_OnClick(object sender, RoutedEventArgs e)
        {
            var picker = new FileOpenPicker();
            picker.FileTypeFilter.Add(".jpg");
            var files = await picker.PickMultipleFilesAsync();

            TreeMap.Children.Clear();

            var sources = new List<BitmapImage>();
            foreach (var file in files)
            {
                var stream = (await file.OpenStreamForReadAsync()).AsRandomAccessStream();//await file.GetScaledImageAsThumbnailAsync(ThumbnailMode.PicturesView, 300);
                var imageSource = new BitmapImage();
                await imageSource.SetSourceAsync(stream);

                sources.Add(imageSource);

                var image = new Image();
                image.Stretch = Stretch.UniformToFill;
                image.Source = imageSource;
                TreeMap.Children.Add(image);
            }

            MosaicImage.Source = sources;
        }
        public async void getItemFromDB()
        {
            this.allItems.Clear();
            try
            {
                var dp = App.conn;
                using (var statement = dp.Prepare(@"SELECT * FROM TaskItem"))
                {
                    while (SQLiteResult.ROW == statement.Step())
                    {
                        //do with pic
                        BitmapImage bimage = new BitmapImage();
                        StorageFile file = await StorageFile.GetFileFromPathAsync((string)statement[4]);
                        IRandomAccessStream instream = await file.OpenAsync(FileAccessMode.Read);
                        string boot = Windows.Storage.AccessCache.StorageApplicationPermissions.MostRecentlyUsedList.Add(file);
                        await bimage.SetSourceAsync(instream);
                        // 处理时间
                        DateTime dt;
                        DateTimeFormatInfo dtFormat = new DateTimeFormatInfo();
                        dtFormat.ShortDatePattern = "yyyy-MM-dd";
                        dt = Convert.ToDateTime((string)statement[3], dtFormat);
                        this.allItems.Add(new Models.TaskItem(statement[0].ToString(), statement[1].ToString(), (string)statement[2], bimage, dt, (string)statement[4], (string)statement[5], (string)statement[6]));
                    }
                }
            }
            catch
            {
                return;
            }


        }
		async void RenderPictures()
		{
			var service = new JDanielSmith.PictureOfTheDay.Service();
			var thickness = new Thickness(0, 0, 50, 100);

			foreach (var name in service.Names)
			{
				var image = new Image() { Stretch = Stretch.Fill, Margin = thickness };

				const int offset = 25;
				thickness = new Thickness(thickness.Left + offset, thickness.Top + offset, thickness.Right - offset, thickness.Bottom - offset);
				this.grid1.Children.Add(image);

				var result = await service.GetPictureAsync(name);

				//var bitmapImage = new BitmapImage(result.Url);
				var bitmapImage = new BitmapImage();
				// http://jebarson.info/post/2012/03/14/byte-array-to-bitmapimage-converter-irandomaccessstream-implementation-for-windows-8-metro.aspx (see comment)
				using (var ms = new Windows.Storage.Streams.InMemoryRandomAccessStream())
				{
					await result.Image.WriteContentAsync(ms.AsStreamForWrite());
					ms.Seek(0);

					await bitmapImage.SetSourceAsync(ms);
				}

				image.Source = bitmapImage;
			}
		}
 public async static void GetImageSize(this Stream imageStream)
 {
     var image = new BitmapImage();
     byte[] imageBytes = Convert.FromBase64String(imageStream.ToBase64String());
     MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);
     ms.Write(imageBytes, 0, imageBytes.Length);
     using (InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream())
     {
         using (DataWriter writer = new DataWriter(stream.GetOutputStreamAt(0)))
         {
             try
             {
                 writer.WriteBytes(imageBytes);
                 await writer.StoreAsync();
             }
             catch (Exception)
             {
                 // ignored
             }
         }
         try
         {
             await image.SetSourceAsync(stream);
         }
         catch (Exception)
         {
             // ignored
         }
     }
     ImageSize = new Size(image.PixelWidth, image.PixelHeight);
 }
        private async void SelectPictureButton_Click(object sender, RoutedEventArgs e)
        {
            FileOpenPicker openPicker = new FileOpenPicker();  //允许用户打开和选择文件的UI
            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();  //storageFile:提供有关文件及其内容以及操作的方式
            if (file != null)
            {
                path = file.Path;
                using (IRandomAccessStream fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read))
                {
                    // Set the image source to the selected bitmap 
                    BitmapImage bitmapImage = new BitmapImage();
                    bitmapImage.DecodePixelWidth = 600; //match the target Image.Width, not shown
                    await bitmapImage.SetSourceAsync(fileStream);
                    img.Source = bitmapImage;
                }
            }
            else
            {
                var i = new MessageDialog("error with picture").ShowAsync();
            }
        }
        public async Task<BitmapSource> LoadImageAsync(Stream imageStream, Uri uri)
        {
            if (imageStream == null)
            {
                return null;
            }

            var stream = new InMemoryRandomAccessStream();
            imageStream.CopyTo(stream.AsStreamForWrite());
            stream.Seek(0);

            BitmapImage bitmap = new BitmapImage();
            await bitmap.SetSourceAsync(stream);

            // convert to a writable bitmap so we can get the PixelBuffer back out later...
            // in case we need to edit and/or re-encode the image.
            WriteableBitmap bmp = new WriteableBitmap(bitmap.PixelHeight, bitmap.PixelWidth);
            stream.Seek(0);
            bmp.SetSource(stream);

            List<Byte> allBytes = new List<byte>();
            byte[] buffer = new byte[4000];
            int bytesRead = 0;
            while ((bytesRead = await imageStream.ReadAsync(buffer, 0, 4000)) > 0)
            {
                allBytes.AddRange(buffer.Take(bytesRead));
            }

            DataContainerHelper.Instance.WriteableBitmapToStorageFile(bmp, uri);

            return bmp;
        }
        private async Task wczytywanie_obrazkow()
        {
            var bounds = Window.Current.Bounds;

            int i = 0;
            foreach (var x in Data.Data.fileList)
            {
                using (IRandomAccessStream fileStream = await x.OpenAsync(Windows.Storage.FileAccessMode.Read))
                {

                    BitmapImage bitmapImage = new BitmapImage();

                    await bitmapImage.SetSourceAsync(fileStream);

                    int wysokosc1 = Convert.ToInt32(bounds.Height * 0.25);

                    int szerokosc1 = Convert.ToInt32(bounds.Width * 0.4);
                    int szerokosc2 = Convert.ToInt32(bounds.Width * 0.55);

                    lista.Add(new Model.lista_klasa { Nazwa = x.Name, Image = bitmapImage, id = i, wysokosc1 = wysokosc1, szerokosc1 = szerokosc1, szerokosc2 = szerokosc2 });

                }
                i++;
            }
        }
 async public Task<object> GetDocumentsBitmap(string filePath)
 {
     StorageFile imgFile = (StorageFile)await GetFile(filePath);
     IRandomAccessStream stream = await imgFile.OpenAsync(FileAccessMode.Read);
     BitmapImage img = new BitmapImage();
     await img.SetSourceAsync(stream);
     return img;
 }
Exemple #28
0
        //public ObservableCollection<Thumbnail> Files { get; private set; }

        //protected override async void OnNavigatedTo(NavigationEventArgs e)
        //{
        //    base.OnNavigatedTo(e);

        //    var root = await this._controller.FileSystem.GetFolderAsync();
        //    var folder = await this._controller.FileSystem.GetFolderAsync(root.First());
        //    foreach (var file in folder)
        //    {
        //        try
        //        {
        //            var thumbnail = await this._controller.FileSystem.DownloadThumbnailAsync(file);
        //            var bitmapSource = new BitmapImage();
        //            await bitmapSource.SetSourceAsync(thumbnail.Stream.AsRandomAccessStream());
        //            this.Files.Add(new Thumbnail(file.FileName, bitmapSource));
        //        }
        //        catch (NullReferenceException)
        //        {
        //            // do nothing!
        //        }
        //    }
        //}

        private async void Capture(object sender, RoutedEventArgs e)
        {
            this.Progress.IsActive = true;
            await this._controller.SetModeAsync(CameraGenericMode.Still);
            var file = await this._controller.Still.StartCaptureAsync();

            var bitmapSource = new BitmapImage();

            var thumb = await this._controller.FileSystem.DownloadThumbnailAsync(file);
            await bitmapSource.SetSourceAsync(thumb.Stream.AsRandomAccessStream());
            this.ThumbnailImage.Source = bitmapSource;

            var full = await this._controller.FileSystem.DownloadFileAsync(file);
            await bitmapSource.SetSourceAsync(full.Stream.AsRandomAccessStream());
            this.ThumbnailImage.Source = bitmapSource;
            this.Progress.IsActive = false;
        }
        public async Task LoadControl(int fontSize, int alignment, int deltaImageMove, int deltaTextMove, int animationDuration, string imagePath)
        {
            //style text
            title.FontSize = fontSize;
            

            //predefine animations
            DoubleAnimation daBkgImageX = (DoubleAnimation)sbPlay001.Children[0];
            DoubleAnimation daBkgImageY = (DoubleAnimation)sbPlay001.Children[1];
            DoubleAnimation daTitleX = (DoubleAnimation)sbPlay001.Children[2];
            DoubleAnimation daTitleY = (DoubleAnimation)sbPlay001.Children[3];

            daBkgImageX.Duration = TimeSpan.FromSeconds(animationDuration);
            daBkgImageY.Duration = TimeSpan.FromSeconds(animationDuration);
            daTitleX.Duration = TimeSpan.FromSeconds(animationDuration);
            daTitleY.Duration = TimeSpan.FromSeconds(animationDuration);

            switch (alignment)
            {
                case 0:
                    title.VerticalAlignment = Windows.UI.Xaml.VerticalAlignment.Top;
                    daBkgImageX.To = -deltaImageMove;
                    daBkgImageY.To = -deltaImageMove / 3;
                    daTitleX.To = deltaTextMove;
                    daTitleY.To = deltaTextMove / 3;
                    break;
                case 1:
                    title.VerticalAlignment = Windows.UI.Xaml.VerticalAlignment.Center;
                    daBkgImageY.To = -deltaImageMove / 3;
                    daTitleX.To = -deltaTextMove;
                    daTitleY.To = -deltaTextMove*8;
                    break;
            }
            
            //load image
            StorageFile file = await FileExists("ModernCSApp\\large", imagePath, type: 2);
            
            if (file != null)
            {
                using (var imgSource = await file.OpenAsync(FileAccessMode.Read))
                {
                    var bi = new BitmapImage();
                    await bi.SetSourceAsync(imgSource);

                    image.Source = (ImageSource)bi;

                    //var bp = await file.Properties.GetImagePropertiesAsync();

                    sbPlay001.Begin();
                }
                
            }

           

        }
 private async void LoadThumbnail(StorageFile file)
 {
     var image = new BitmapImage();
     image.DecodePixelHeight = 72;
     using (var stream = (FileRandomAccessStream)await file.OpenAsync(FileAccessMode.Read))
     {
         await image.SetSourceAsync(stream);
     }
     Image = image;
 }
 private async void MainPage_Loaded(object sender, RoutedEventArgs e)
 {
   var file = await StorageFile.GetFileFromApplicationUriAsync(new Uri(@"ms-appx:///Assets/placeholder.png"));
   using (var stream = await file.OpenAsync(FileAccessMode.Read))
   {
     var bitmap = new BitmapImage();
     await bitmap.SetSourceAsync(stream);
     ImageTarget.Source = bitmap;
   }
 }
        /// <summary>
        /// Applys a blur to a UI element
        /// </summary>
        /// <param name="sourceElement">UIElement to blur, generally an Image control, but can be anything</param>
        /// <param name="blurAmount">Level of blur to apply</param>
        /// <returns>Blurred UIElement as BitmapImage</returns>
        public static async Task<BitmapImage> BlurElementAsync(this UIElement sourceElement, float blurAmount = 2.0f)
        {
            if (sourceElement == null)
                return null;

            var rtb = new RenderTargetBitmap();
            await rtb.RenderAsync(sourceElement);

            var buffer = await rtb.GetPixelsAsync();
            var array = buffer.ToArray();

            var displayInformation = DisplayInformation.GetForCurrentView();

            using (var stream = new InMemoryRandomAccessStream())
            {
                var pngEncoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, stream);

                pngEncoder.SetPixelData(BitmapPixelFormat.Bgra8,
                                     BitmapAlphaMode.Premultiplied,
                                     (uint) rtb.PixelWidth,
                                     (uint) rtb.PixelHeight,
                                     displayInformation.RawDpiX,
                                     displayInformation.RawDpiY,
                                     array);

                await pngEncoder.FlushAsync();
                stream.Seek(0);

                var canvasDevice = new CanvasDevice();
                var bitmap = await CanvasBitmap.LoadAsync(canvasDevice, stream);

                var renderer = new CanvasRenderTarget(canvasDevice,
                                                      bitmap.SizeInPixels.Width,
                                                      bitmap.SizeInPixels.Height,
                                                      bitmap.Dpi);

                using (var ds = renderer.CreateDrawingSession())
                {
                    var blur = new GaussianBlurEffect
                    {
                        BlurAmount = blurAmount,
                        Source = bitmap
                    };
                    ds.DrawImage(blur);
                }

                stream.Seek(0);
                await renderer.SaveAsync(stream, CanvasBitmapFileFormat.Png);

                var image = new BitmapImage();
                await image.SetSourceAsync(stream);

                return image;
            }
        }
 public static async Task<BitmapImage> AsBitmapImageAsync(this IBuffer @this)
 {
     var img = new BitmapImage();
     using (var stream = new InMemoryRandomAccessStream())
     {
         await stream.WriteAsync(@this);
         stream.Seek(0);
         await img.SetSourceAsync(stream);
     }
     return img;
 }
Exemple #34
0
        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);
        }
        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);
        }
Exemple #36
0
        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();
            }
        }
        async System.Threading.Tasks.Task <BitmapImage> GetBitapImage(MemoryStream ms)
        {
            // The implementation below follows
            // http://iamabhik.wordpress.com/2012/10/31/display-image-from-stream-in-windows-8-and-windows-phone-8/
            var   image = new Windows.UI.Xaml.Media.Imaging.BitmapImage();
            var   ras   = new Windows.Storage.Streams.InMemoryRandomAccessStream();
            var   os    = ras.GetOutputStreamAt(0);
            var   dw    = new Windows.Storage.Streams.DataWriter(os);
            var   task  = System.Threading.Tasks.Task.Factory.StartNew(() => dw.WriteBytes(ms.ToArray()));
            await task;
            await dw.StoreAsync();

            await os.FlushAsync();

            await image.SetSourceAsync(ras);

            return(image);
        }
        public bool DoDisplayFileImage(StorageFile file, Image graphicsImage)
        {
            bool result = true;

            AutoResetEvent DisplayComplete = new AutoResetEvent(false);

            InvokeOnUIThread(
                async() =>
            {
                if (graphicsImage.Opacity == 1)
                {
                    await FadeElements.FadeElementOpacityAsync(graphicsImage, 1, 0, new TimeSpan(0, 0, 1));
                }

                try
                {
                    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;

                    await FadeElements.FadeElementOpacityAsync(graphicsImage, 0, 1, new TimeSpan(0, 0, 1));
                }
                catch
                {
                    result = false;
                }
                finally
                {
                    DisplayComplete.Set();
                }
            });

            DisplayComplete.WaitOne();

            return(result);
        }
Exemple #39
0
        public static async Task <BitmapImage> LoadSnapshot(string key)
        {
            try
            {
                var uri  = new System.Uri(string.Format("ms-appdata:///local/{0}", key + ChmSnapshotEntension));
                var file = await Windows.Storage.StorageFile.GetFileFromApplicationUriAsync(uri);

                Windows.UI.Xaml.Media.Imaging.BitmapImage image = new Windows.UI.Xaml.Media.Imaging.BitmapImage();
                using (var fileStream = await file.OpenReadAsync())
                {
                    await image.SetSourceAsync(fileStream);

                    return(image);
                }
            }
            catch
            {
                return(new BitmapImage(new Uri("ms-appx:///Assets/chm.png")));
            }
        }
Exemple #40
0
        private async void Select_Click(object sender, RoutedEventArgs e)
        {
            FileOpenPicker picker = new FileOpenPicker();

            picker.ViewMode = PickerViewMode.Thumbnail;
            picker.SuggestedStartLocation = PickerLocationId.Desktop;
            picker.FileTypeFilter.Add(".jpg");
            picker.FileTypeFilter.Add(".jpeg");
            picker.FileTypeFilter.Add(".png");
            picker.FileTypeFilter.Add(".gif");
            StorageFile file = await picker.PickSingleFileAsync();

            if (file != null)
            {
                ApplicationData.Current.LocalSettings.Values["Image"] = StorageApplicationPermissions.FutureAccessList.Add(file);
                IRandomAccessStream fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);

                Windows.UI.Xaml.Media.Imaging.BitmapImage bitmapImage = new Windows.UI.Xaml.Media.Imaging.BitmapImage();
                await bitmapImage.SetSourceAsync(fileStream);

                Img.Source = bitmapImage;
            }
        }
Exemple #41
0
        private async void Click_SelectPicture(object sender, RoutedEventArgs e)
        {
            Windows.Storage.Pickers.FileOpenPicker openPicker = new Windows.Storage.Pickers.FileOpenPicker();
            openPicker.ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail;
            openPicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.PicturesLibrary;
            openPicker.FileTypeFilter.Add(".jpg");
            openPicker.FileTypeFilter.Add(".jpeg");
            openPicker.FileTypeFilter.Add(".png");

            file = await openPicker.PickSingleFileAsync();

            if (file != null)
            {
                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();
                    await bitmapImage.SetSourceAsync(fileStream);

                    image2.Source = bitmapImage;
                }
            }
        }