コード例 #1
0
 public Stream OpenRead(string path)
 {
     try
     {
         StorageFile storageFile = NativeFile(path);
         IRandomAccessStreamWithContentType streamWithContentType = storageFile.OpenReadAsync().Await();
         return(streamWithContentType.AsStreamForRead());
     }
     catch
     {
         return(null);
     }
 }
コード例 #2
0
        /// <summary>
        /// Loads the byte data from a StorageFile
        /// </summary>
        /// <param name="file">The file to read</param>
        public async Task <byte[]> ReadFile(StorageFile file)
        {
            using (IRandomAccessStreamWithContentType stream = await file.OpenReadAsync())
            {
                stream.Seek((ulong)0);
                byte[]  fileBytes = new byte[stream.Size];
                var     buffer    = CryptographicBuffer.CreateFromByteArray(fileBytes);
                IBuffer rd        = await stream.ReadAsync(buffer, (uint)fileBytes.Length, InputStreamOptions.None);

                rd.CopyTo(fileBytes);
                return(fileBytes);
            }
        }
コード例 #3
0
        public async System.Threading.Tasks.Task ShowImage(StorageFile file)
        {
            var bitmap = new BitmapImage();

            using (IRandomAccessStreamWithContentType stream = await file.OpenReadAsync())
            {
                stream.Seek(0);
                await bitmap.SetSourceAsync(stream);

                this.img.Source = bitmap;
                this.img.Name   = file.DisplayName;
            }
        }
コード例 #4
0
ファイル: Common.cs プロジェクト: yunfandev/waslibs
        public static async Task <string> ReadAssetFile(string fileName)
        {
            var uri = new Uri(string.Format("ms-appx://{0}", fileName));

            StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(uri);

            IRandomAccessStreamWithContentType randomStream = await file.OpenReadAsync();

            using (StreamReader r = new StreamReader(randomStream.AsStreamForRead()))
            {
                return(await r.ReadToEndAsync());
            }
        }
コード例 #5
0
ファイル: NativeMediaOpen.cs プロジェクト: AREA-AR/areaPlus
        private async Task <bool> LoadFile(StorageFile file)
        {
            if (file != null)
            {
                _fileStream = await file.OpenReadAsync();

                if (_fileStream != null)
                {
                    _fileName = file.Name;
                }
            }
            return(true);
        }
コード例 #6
0
        public override async Task <IEnumerable <T> > LoadDataAsync()
        {
            var uri = new Uri(string.Format("ms-appx://{0}", _config.FilePath));

            StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(uri);

            IRandomAccessStreamWithContentType randomStream = await file.OpenReadAsync();

            using (StreamReader r = new StreamReader(randomStream.AsStreamForRead()))
            {
                return(_parser.Parse(await r.ReadToEndAsync()));
            }
        }
コード例 #7
0
        protected override async Task <IEnumerable <TSchema> > GetDataAsync <TSchema>(LocalStorageDataConfig config, int maxRecords, IParser <TSchema> parser)
        {
            var uri = new Uri(string.Format("ms-appx://{0}", config.FilePath));

            StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(uri);

            IRandomAccessStreamWithContentType randomStream = await file.OpenReadAsync();

            using (StreamReader r = new StreamReader(randomStream.AsStreamForRead()))
            {
                return(parser.Parse(await r.ReadToEndAsync()));
            }
        }
コード例 #8
0
        private static async Task <IEnumerable <PhotoDataItem> > GetPhotosAsync(bool online)
        {
            var         prefix = online ? "Online" : string.Empty;
            var         uri    = new Uri($"ms-appx:///Assets/Photos/{prefix}Photos.json");
            StorageFile file   = await StorageFile.GetFileFromApplicationUriAsync(uri);

            IRandomAccessStreamWithContentType randomStream = await file.OpenReadAsync();

            using (StreamReader r = new StreamReader(randomStream.AsStreamForRead()))
            {
                return(Parse(await r.ReadToEndAsync()));
            }
        }
コード例 #9
0
        //发送录音
        private async void accept_Tapped(object sender, TappedRoutedEventArgs e)
        {
            HttpClient httpClient = new HttpClient();
            IRandomAccessStreamWithContentType stream1 = await _recordStorageFile.OpenReadAsync();

            HttpStreamContent            streamContent1 = new HttpStreamContent(stream1);
            HttpMultipartFormDataContent fileContent    = new HttpMultipartFormDataContent();

            fileContent.Add(streamContent1, "song", _recordStorageFile.Name);
            string uri = Config.apiChatRecord;
            HttpResponseMessage response = await httpClient.PostAsync(new Uri(uri), fileContent);

            string msgRecord = await response.Content.ReadAsStringAsync();


            MessageModel message = new MessageModel();

            message.myImage = Config.UserImage;
            message.myPhone = Config.UserPhone;
            message.myName  = Config.UserName;
            message.myDream = Config.UserDream;
            message.type    = 1;
            message.msg     = msgRecord;
            message.toPhone = User.uid;
            message.toImage = User.image;
            message.time    = HelpMethods.GetTimeNow();


            messageList.Add(message);
            if (myChat.Items.Count > 0)
            {
                myChat.ScrollIntoView(myChat.Items.Last(), ScrollIntoViewAlignment.Leading);
            }
            string messageJSON = JsonConvert.SerializeObject(message);

            SocKetHelp.socket.Emit("chat", messageJSON);

            DbService.Current.Add(message);
            gridRecord.Visibility = Visibility.Collapsed;
            record.IsTapEnabled   = true;
            myChat.Visibility     = Visibility.Visible;
            stop.Visibility       = Visibility.Visible;
            cancel.Visibility     = Visibility.Collapsed;
            accept.Visibility     = Visibility.Collapsed;

            if (_mediaCaptureManager != null)
            {
                _mediaCaptureManager.Dispose();
                _mediaCaptureManager = null;
            }
        }
コード例 #10
0
        // https://docs.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/dependency-service/photo-picker
        public async Task <FileChooserResult> GetFileAsync(bool imagesOnly = false) // TODO: image chooser result?
        {
            try
            {
                // Create and initialize the FileOpenPicker
                FileOpenPicker openPicker = new FileOpenPicker
                {
                    ViewMode = PickerViewMode.Thumbnail
                };

                if (imagesOnly)
                {
                    foreach (var imageType in Core.StaticVariables.ImageFormats)
                    {
                        openPicker.FileTypeFilter.Add(imageType.Extension);
                    }

                    openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
                }
                else
                {
                    openPicker.FileTypeFilter.Add("*");
                    openPicker.SuggestedStartLocation = PickerLocationId.ComputerFolder;
                }

                // Get a file and return a Stream
                StorageFile storageFile = await openPicker.PickSingleFileAsync();

                if (storageFile == null)
                {
                    return(null);
                }

                IRandomAccessStreamWithContentType raStream = await storageFile.OpenReadAsync();

                return(new FileChooserResult()
                {
                    FileName = storageFile.Path,
                    Stream = raStream.AsStreamForRead(),
                    NativeRepresentation = storageFile,
                    CarrierImageFormat = new ImageFormat(storageFile.Path)
                });
            }
            catch (Exception ex)
            {
                return(new FileChooserResult()
                {
                    ErrorMessage = ex.Message
                });
            }
        }
コード例 #11
0
        public static async Task <byte[]> ImageToByteArray(StorageFile file)
        {
            byte[] fileBytes = null;
            using (IRandomAccessStreamWithContentType stream = await file.OpenReadAsync())
            {
                BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream);

                PixelDataProvider pixelData = await decoder.GetPixelDataAsync();

                fileBytes = pixelData.DetachPixelData();
            }

            return(fileBytes);
        }
コード例 #12
0
ファイル: MainPage.xaml.cs プロジェクト: webabcd/Windows10
        // 显示图片
        async private void ShowBitmap(IRandomAccessStreamReference bitmap)
        {
            await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() =>
            {
                if (bitmap != null)
                {
                    IRandomAccessStreamWithContentType bitmapStream = await bitmap.OpenReadAsync();
                    BitmapImage bitmapImage = new BitmapImage();
                    bitmapImage.SetSource(bitmapStream);

                    imgBitmap.Source = bitmapImage;
                }
            });
        }
コード例 #13
0
ファイル: MainPage.xaml.cs プロジェクト: webabcd/Windows10
        // 显示图片
        async private void ShowThumbnail(IRandomAccessStreamReference thumbnail)
        {
            await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() =>
            {
                if (thumbnail != null)
                {
                    IRandomAccessStreamWithContentType thumbnailStream = await thumbnail.OpenReadAsync();
                    BitmapImage bitmapImage = new BitmapImage();
                    bitmapImage.SetSource(thumbnailStream);

                    imgThumbnail.Source = bitmapImage;
                }
            });
        }
コード例 #14
0
        public async Task <IZipArchive> OpenReadAsync(string filePath)
        {
            var localFolder = await Windows.Storage.ApplicationData.Current.LocalFolder.GetFolderAsync(booksFolderName);

            var file = await localFolder.GetFileAsync(filePath);

            IRandomAccessStreamWithContentType randomStream = await file.OpenReadAsync();

            Stream             stream             = randomStream.AsStream();
            ZipArchive         archive            = new ZipArchive(stream);
            WinPhoneZipArchive winPhoneZipArchive = new WinPhoneZipArchive(archive);

            return(winPhoneZipArchive);
        }
コード例 #15
0
        /// <summary>
        /// Gets app package and image and returns them as a new "finalAppItem" which will be used for the app control template.
        /// <para>WARNING: Only use this method when it's REQUIRED. Otherwise use the Async version below this one.</para>
        /// </summary>


        public static ObservableCollection <finalAppItem> getAllApps()
        {
            var            listOfInstalledPackages = pkgManager.FindPackagesForUserWithPackageTypes("", PackageTypes.Main);
            List <Package> allPackages             = new List <Package>();
            List <Package> packages = new List <Package>();

            allPackages = listOfInstalledPackages.ToList();
            int count = allPackages.Count();

            for (int i = 0; i < count; i++)
            {
                packages.Add(allPackages[i]);
            }


            ObservableCollection <finalAppItem> finalAppItems = new ObservableCollection <finalAppItem>();

            count = packages.Count();

            //Loop will get app entry and logo for each app and create finalAppItem objects with that data.
            for (int i = 0; i < count; i++)
            {
                try
                {
                    List <AppListEntry> singleAppListEntries = new List <AppListEntry>();
                    Task <IReadOnlyList <AppListEntry> > getAppEntriesTask = packages[i].GetAppListEntriesAsync().AsTask();
                    getAppEntriesTask.Wait();
                    singleAppListEntries = getAppEntriesTask.Result.ToList();


                    BitmapImage logo       = new BitmapImage();
                    var         logoStream = singleAppListEntries[0].DisplayInfo.GetLogo(new Size(50, 50));
                    Task <IRandomAccessStreamWithContentType> logoStreamTask = logoStream.OpenReadAsync().AsTask();
                    logoStreamTask.Wait();
                    IRandomAccessStreamWithContentType logoStreamResult = logoStreamTask.Result;
                    logo.SetSource(logoStreamResult);
                    finalAppItems.Add(new finalAppItem
                    {
                        appEntry = singleAppListEntries[0],
                        appLogo  = logo
                    });
                }

                catch (Exception e)
                {
                    Debug.WriteLine(e.Message);
                }
            }
            return(finalAppItems);
        }
コード例 #16
0
        public static async Task <Color> GetStationBackgroundDominantColorAsync(StationItem station)
        {
            if (station == null)
            {
                throw new ArgumentNullException(nameof(station));
            }

            if (station.Background == null)
            {
                return(Colors.Transparent);
            }

            string colorKey = "BgColor|" + station.Name;
            Color  color    = default(Color);

            if (await CookieJar.DeviceCache.ContainsObjectAsync(colorKey))
            {
                var hexCode = await CookieJar.DeviceCache.PeekObjectAsync <string>(colorKey);

                return(ColorUtilities.ParseFromHexString(hexCode));
            }

            IRandomAccessStreamWithContentType stationBgStream = null;

            try
            {
                var streamRef = RandomAccessStreamReference.CreateFromUri(new Uri(station.Background));
                stationBgStream = await streamRef.OpenReadAsync();

                color = await ColorUtilities.GetDominantColorAsync(stationBgStream);
            }
            catch (Exception ex)
            {
                Dictionary <string, string> data = new Dictionary <string, string>();
                data.Add("StationName", station.Name);
                data.Add("StationBackgroundURL", station.Background?.ToString());
                data.Add("StationURL", station.Site);

                Microsoft.HockeyApp.HockeyClient.Current.TrackException(ex, data);
            }
            finally
            {
                stationBgStream?.Dispose();
            }

            await CookieJar.DeviceCache.PushObjectAsync <string>(colorKey, color.ToString());

            return(color);
        }
コード例 #17
0
        /// <summary>
        /// Converts the specified file to a byte array.
        /// </summary>
        /// <param name="storageFile">The file to convert.</param>
        /// <returns>A byte array representation of the file.</returns>
        private async Task <byte[]> ConvertToBinary(StorageFile storageFile)
        {
            IRandomAccessStreamWithContentType stream = await storageFile.OpenReadAsync();

            using (DataReader reader = new DataReader(stream))
            {
                byte[] buffer = new byte[stream.Size];

                await reader.LoadAsync((uint)stream.Size);

                reader.ReadBytes(buffer);

                return(buffer);
            }
        }
コード例 #18
0
        private async Task <string> GetBase64(StorageFile file)
        {
            byte[] fileBytes = null;
            using (IRandomAccessStreamWithContentType stream = await file.OpenReadAsync())
            {
                fileBytes = new byte[stream.Size];
                using (DataReader reader = new DataReader(stream))
                {
                    await reader.LoadAsync((uint)stream.Size);

                    reader.ReadBytes(fileBytes);
                }
            }
            return(Convert.ToBase64String(fileBytes));
        }
コード例 #19
0
ファイル: MainPage.xaml.cs プロジェクト: tuxuser/parallaX
        // READFiLE>BYTES
        public async Task <byte[]> ReadFile(StorageFile file)
        {
            byte[] fileBytes = null;
            using (IRandomAccessStreamWithContentType stream = await file.OpenReadAsync())
            {
                fileBytes = new byte[stream.Size];
                using (DataReader reader = new DataReader(stream))
                {
                    await reader.LoadAsync((uint)stream.Size);

                    reader.ReadBytes(fileBytes);
                }
            }
            return(fileBytes);
        }
コード例 #20
0
        private static async Task <string> toBase64Async(RandomAccessStreamReference imageStream)
        {
            //FileStream fs = new FileStream(image.Path,FileMode.);
            IRandomAccessStreamWithContentType a = await imageStream.OpenReadAsync();

            byte[] bytes  = new byte[a.Size];
            var    buffer = await a.ReadAsync(bytes.AsBuffer(), (uint)a.Size, InputStreamOptions.None);

            bytes = buffer.ToArray();
            //buffer.ToArray();
            String base64 = Convert.ToBase64String(bytes);

            //base64 = HttpUtility.UrlEncode(base64);
            return(base64);
        }
コード例 #21
0
ファイル: ImageHelp.cs プロジェクト: x01673/dreaming
 public static async Task<BitmapDecoder> GetProperDecoder(IRandomAccessStreamWithContentType stream, StorageFile file)
 {
     string ext = Path.GetExtension(file.Path);
     switch (ext)
     {
         case ".jpg":
         case ".jpeg":
             return await BitmapDecoder.CreateAsync(BitmapDecoder.JpegDecoderId, stream);
         case ".png":
             return await BitmapDecoder.CreateAsync(BitmapDecoder.PngDecoderId, stream);
         case ".gif":
             return await BitmapDecoder.CreateAsync(BitmapDecoder.GifDecoderId, stream);
     }
     return null;
 }
コード例 #22
0
ファイル: WindowsFileStore.cs プロジェクト: Xcdify/MoneyFox
        public override Stream OpenRead(string path)
        {
            try
            {
                StorageFile storageFile = StorageFileFromRelativePath(path);
                IRandomAccessStreamWithContentType streamWithContentType = storageFile.OpenReadAsync().Await();

                return(streamWithContentType.AsStreamForRead());
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                return(null);
            }
        }
コード例 #23
0
        public IAsyncAction UploadFileAsync(IRecord record, StorageFile file)
        {
            if (file == null)
            {
                throw new ArgumentNullException("file");
            }

            return(AsyncInfo.Run(cancelToken => Task.Run(async() =>
            {
                using (IRandomAccessStreamWithContentType stream = await file.OpenReadAsync())
                {
                    await UploadAsync(record, stream.ContentType, stream).AsTask(cancelToken);
                }
            })));
        }
コード例 #24
0
        public byte[] ReadFile(StorageFile file)
        {
            byte[] fileBytes = null;
            using (IRandomAccessStreamWithContentType stream = file.OpenReadAsync().GetResults())
            {
                fileBytes = new byte[stream.Size];
                using (DataReader reader = new DataReader(stream))
                {
                    reader.LoadAsync((uint)stream.Size).GetResults();
                    reader.ReadBytes(fileBytes);
                }
            }

            return(fileBytes);
        }
コード例 #25
0
        /// <summary>
        /// 输入Uri开始播放Gif图片
        /// </summary>
        /// <param name="Uri"></param>
        private async void Start(string uri)
        {
            var   reg   = @"http(s)?://([\w-]+\.)+[\w-]+(/[\w-./?%&=]*)?";
            Regex regex = new Regex(reg, RegexOptions.IgnoreCase);
            RandomAccessStreamReference rass = null;

            if (regex.IsMatch(this.Source))
            {
                rass = RandomAccessStreamReference.CreateFromUri(new Uri(uri, UriKind.RelativeOrAbsolute));
            }
            else
            {
                rass = RandomAccessStreamReference.CreateFromUri(new Uri(this.baseUri, uri));
            }
            try
            {
                IRandomAccessStreamWithContentType streamRandom = await rass.OpenReadAsync();

                Stream tempStream         = streamRandom.GetInputStreamAt(0).AsStreamForRead();
                var    randomAccessStream = new InMemoryRandomAccessStream();
                var    outputStream       = randomAccessStream.GetOutputStreamAt(0);
                await RandomAccessStream.CopyAsync(tempStream.AsInputStream(), outputStream);

                try
                {
                    await CreateGifBitFrame(randomAccessStream);

                    PlayGif();
                }
                catch
                {
                    JpegAndPng(randomAccessStream);
                }
            }
            catch
            {
                BitmapImage bi = new BitmapImage();
                if (regex.IsMatch(this.Source))
                {
                    bi.UriSource = new Uri(uri, UriKind.RelativeOrAbsolute);
                }
                else
                {
                    bi.UriSource = new Uri(this.baseUri, uri);
                }
                //imageGif.Source = bi;
            }
        }
コード例 #26
0
        public static async void HttpUserPost(string phone, string name, string content, string picPath, string tag)
        {
            HttpClient httpClient = new HttpClient();

            try
            {
                string      posturi = Config.apiUserUpdate;
                StorageFile file1   = await StorageFile.GetFileFromPathAsync(picPath);

                IRandomAccessStreamWithContentType stream1 = await file1.OpenReadAsync();

                HttpStreamContent streamContent1 = new HttpStreamContent(stream1);
                HttpStringContent stringContent  = new HttpStringContent(content);
                HttpStringContent stringTitle    = new HttpStringContent(phone);
                HttpStringContent stringName     = new HttpStringContent(name);
                HttpStringContent stringTag      = new HttpStringContent(tag);

                HttpMultipartFormDataContent fileContent = new HttpMultipartFormDataContent();
                fileContent.Add(stringContent, "dream");
                fileContent.Add(stringTitle, "phone");
                fileContent.Add(stringTag, "tag");
                fileContent.Add(stringName, "name");
                fileContent.Add(streamContent1, "picture", "pic.jpg");
                HttpResponseMessage response = await httpClient.PostAsync(new Uri(posturi), fileContent);

                string responString = await response.Content.ReadAsStringAsync();



                if ((int)response.StatusCode == 200)
                {
                    JsonObject user = JsonObject.Parse(responString);


                    Config.UserName  = user.GetNamedString("name");
                    Config.UserImage = Config.apiFile + user.GetNamedString("image");
                    Config.UserPhone = user.GetNamedString("phone");
                    Config.UserDream = user.GetNamedString("dream");
                    Config.UserTag   = user.GetNamedString("tag");

                    NavigationHelp.NavigateTo(typeof(Main));
                }
            }
            catch (Exception ex)
            {
                HelpMethods.Msg(ex.Message.ToString());
            }
        }
コード例 #27
0
        public static async Task <ImageFile> FileToImageFileAsync(IStorageFile storageFile, bool readStream = true)
        {
            Stream imageStream = null;

            if (readStream)
            {
                IRandomAccessStreamWithContentType RandomAccessStream = await storageFile?.OpenReadAsync();

                imageStream = RandomAccessStream?.AsStreamForWrite();
            }
            ImageProperties imageProp;
            int             width    = 0;
            int             height   = 0;
            string          filepath = String.Empty;

            if (storageFile is StorageFile sFile)
            {
                if (sFile.Properties != null)
                {
                    imageProp = await sFile.Properties.GetImagePropertiesAsync();

                    width  = (int)imageProp.Width;
                    height = (int)imageProp.Height;
                }
                //path can be empty if from the file picker dialog
                //a image path from the internet was enterted
                if (String.IsNullOrEmpty(storageFile.Path))
                {
                    filepath = sFile.FolderRelativeId;
                }
                else
                {
                    filepath = storageFile.Path;
                }
            }

            if (String.IsNullOrEmpty(filepath))
            {
                filepath = storageFile.Path;
            }

            FileInfo  fileInfo  = String.IsNullOrEmpty(filepath) ? null : new FileInfo(filepath);
            ImageFile imageFile = new ImageFile(filepath, imageStream, width, height, fileInfo);

            imageFile.Tag        = storageFile;
            imageFile.IsReadOnly = (Windows.Storage.FileAttributes.ReadOnly & storageFile.Attributes) == Windows.Storage.FileAttributes.ReadOnly;
            return(imageFile);
        }
コード例 #28
0
ファイル: FileIndexer.cs プロジェクト: Losses/DarkPlayer
        void FillMetadataBagStub(FileInformation fileInfo, ConcurrentBag <MediaMetadata> bag)
        {
            // Prep metadata and cover.
            IRandomAccessStreamWithContentType stream = null;

            try
            {
                IMediaInfo info;
                // Workaround for mojibake in id3v2 tags: use system code page.
                if (string.Compare(fileInfo.FileType, ".mp3", true) == 0)
                {
                    var        fInfo = MusicPropertiesMediaInfo.Create(fileInfo.MusicProperties);
                    IMediaInfo extraInfo;
                    using (stream = fileInfo.OpenReadAsync().AsTask().Result)
                    {
                        var result =
                            NativeMethods.GetMediaInfoFromStream(stream, out extraInfo);
                    }
                    fInfo.TrackNumber   = extraInfo.TrackNumber;
                    fInfo.TotalTracks   = extraInfo.TotalTracks;
                    fInfo.DiscNumber    = extraInfo.DiscNumber;
                    fInfo.TotalDiscs    = extraInfo.TotalDiscs;
                    fInfo.Date          = extraInfo.Date;
                    fInfo.Genre         = extraInfo.Genre;
                    fInfo.AllProperties = extraInfo.AllProperties;
                    info = fInfo;
                }
                else
                {
                    using (stream = fileInfo.OpenReadAsync().AsTask().Result)
                    {
                        var result =
                            NativeMethods.GetMediaInfoFromStream(stream, out info);
                    }
                }
                // Ignore all entities with empty title field.
                if (string.IsNullOrEmpty(info?.Title))
                {
                    return;
                }
                bag.Add(new MediaMetadata(info, fileInfo.Path, fileInfo.BasicProperties.DateModified));
            }
            catch (Exception ex)
            {
                // TODO: Handle exceptions
                Debug.WriteLine(ex);
            }
        }
コード例 #29
0
        async Task LoadBitmaps(CanvasControl sender)
        {
            var bitmapType   = CurrentBitmapType;
            var bitmapSource = CurrentBitmapSource;

            var newTestBitmaps = new ICanvasImage[fileNames.Length];

            for (int i = 0; i < fileNames.Length; i++)
            {
                Package       package           = Package.Current;
                StorageFolder installedLocation = package.InstalledLocation;
                string        pathName          = installedLocation.Path + "\\" + "BitmapOrientation" + "\\" + fileNames[i];

                if (bitmapSource == BitmapSourceOption.FromStream)
                {
                    StorageFile storageFile = await StorageFile.GetFileFromPathAsync(pathName);

                    using (IRandomAccessStreamWithContentType stream = await storageFile.OpenReadAsync())
                    {
                        if (bitmapType == BitmapType.CanvasBitmap)
                        {
                            newTestBitmaps[i] = await CanvasBitmap.LoadAsync(sender, stream);
                        }
#if WINDOWS_UWP
                        else
                        {
                            newTestBitmaps[i] = await CanvasVirtualBitmap.LoadAsync(sender, stream);
                        }
#endif
                    }
                }
                else
                {
                    if (bitmapType == BitmapType.CanvasBitmap)
                    {
                        newTestBitmaps[i] = await CanvasBitmap.LoadAsync(sender, pathName);
                    }
#if WINDOWS_UWP
                    else
                    {
                        newTestBitmaps[i] = await CanvasVirtualBitmap.LoadAsync(sender, pathName);
                    }
#endif
                }
            }

            testBitmaps = newTestBitmaps;
        }
コード例 #30
0
        public async Task testUploadPhoto()
        {
            string token = await getAppToken();

            PropertySet parameters = new PropertySet();

            parameters.Add("access_token", Uri.EscapeUriString(token));
            parameters.Add("permissions", FBTestPhotoUploadPermissions);

            FBTestUser user = await createTestUser(parameters);

            StorageFolder appFolder =
                Windows.ApplicationModel.Package.Current.InstalledLocation;
            StorageFile f = await appFolder.GetFileAsync(
                FBTestImagePath);

            IRandomAccessStreamWithContentType stream = await f.OpenReadAsync();

            Assert.IsNotNull(stream);

            FBMediaStream fbStream = new FBMediaStream(FBTestImageName,
                                                       stream);

            // Switch to user access token to post photo.
            parameters.Remove("access_token");
            parameters.Add("access_token", user.AccessToken);

            parameters.Add("source", fbStream);

            string path = "/" + user.Id + "/photos";

            FBSingleValue sval = new FBSingleValue(path, parameters,
                                                   new FBJsonClassFactory(FBPhoto.FromJson));

            FBResult result = await sval.Post();

            Assert.IsTrue(result.Succeeded);

            try
            {
                FBPhoto pic = (FBPhoto)result.Object;
            }
            catch (InvalidCastException)
            {
                Assert.IsFalse(true, "Object returned was not of the " +
                               "expected type (FBPhoto).");
            }
        }
コード例 #31
0
        async public static Task <IInputStream> MakeStreamFromLocalPath(Uri localPath)
        {
            if (null == localPath)
            {
                return(null);
            }

            StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(localPath);

            RandomAccessStreamReference        stream         = RandomAccessStreamReference.CreateFromFile(file);
            IRandomAccessStreamWithContentType streamWithType = await stream.OpenReadAsync();

            IInputStream inputStream = streamWithType;

            return(inputStream);
        }
コード例 #32
0
 private static async Task<int> FileReadStreamSeekTestAsync(IRandomAccessStreamWithContentType fileStream, long streamReadSize, byte[] bufferToCompare)
 {
     int attempts = 1;
     ulong position = 0;
     Assert.AreEqual(position, fileStream.Position);
     position += await FileReadStreamSeekAndCompareAsync(fileStream, bufferToCompare, position, 1024, 1024);
     attempts++;
     Assert.AreEqual(position, fileStream.Position);
     position += await FileReadStreamSeekAndCompareAsync(fileStream, bufferToCompare, position, 512, 512);
     Assert.AreEqual(position, fileStream.Position);
     position = (ulong)(bufferToCompare.Length - 128);
     fileStream.Seek(position);
     Assert.AreEqual(position, fileStream.Position);
     position += await FileReadStreamSeekAndCompareAsync(fileStream, bufferToCompare, position, 1024, 128);
     attempts++;
     Assert.AreEqual(position, fileStream.Position);
     position = 4096;
     fileStream.Seek(position);
     Assert.AreEqual(position, fileStream.Position);
     position += await FileReadStreamSeekAndCompareAsync(fileStream, bufferToCompare, position, 1024, 1024);
     attempts++;
     Assert.AreEqual(position, fileStream.Position);
     position += 4096;
     fileStream.Seek(position);
     Assert.AreEqual(position, fileStream.Position);
     position += await FileReadStreamSeekAndCompareAsync(fileStream, bufferToCompare, position, 1024, 1024);
     Assert.AreEqual(position, fileStream.Position);
     position -= 4096;
     fileStream.Seek(position);
     Assert.AreEqual(position, fileStream.Position);
     position += await FileReadStreamSeekAndCompareAsync(fileStream, bufferToCompare, position, 128, 128);
     Assert.AreEqual(position, fileStream.Position);
     position = (ulong)(streamReadSize + 4096 - 512);
     fileStream.Seek(position);
     Assert.AreEqual(position, fileStream.Position);
     position += await FileReadStreamSeekAndCompareAsync(fileStream, bufferToCompare, position, 1024, 1024);
     attempts++;
     Assert.AreEqual(position, fileStream.Position);
     position += await FileReadStreamSeekAndCompareAsync(fileStream, bufferToCompare, position, 1024, 1024);
     Assert.AreEqual(position, fileStream.Position);
     position -= 1024;
     fileStream.Seek(position);
     Assert.AreEqual(position, fileStream.Position);
     position += await FileReadStreamSeekAndCompareAsync(fileStream, bufferToCompare, position, 2048, 2048);
     Assert.AreEqual(position, fileStream.Position);
     position = (ulong)(bufferToCompare.Length - 128);
     fileStream.Seek(position);
     Assert.AreEqual(position, fileStream.Position);
     position += await FileReadStreamSeekAndCompareAsync(fileStream, bufferToCompare, position, 1024, 128);
     Assert.AreEqual(position, fileStream.Position);
     return attempts;
 }
コード例 #33
0
        private static async Task<uint> FileReadStreamSeekAndCompareAsync(IRandomAccessStreamWithContentType fileStream, byte[] bufferToCompare, ulong offset, uint readSize, uint expectedReadCount)
        {
            byte[] testBuffer = new byte[readSize];

            IBuffer testBufferAsIBuffer = testBuffer.AsBuffer();
            await fileStream.ReadAsync(testBufferAsIBuffer, readSize, InputStreamOptions.None);
            Assert.AreEqual(expectedReadCount, testBufferAsIBuffer.Length);

            long bufferOffset = (long)offset;
            for (int i = 0; i < expectedReadCount; i++, bufferOffset++)
            {
                Assert.AreEqual(bufferToCompare[bufferOffset], testBuffer[i]);
            }

            return expectedReadCount;
        }
コード例 #34
0
 private static async Task<int> FileReadStreamSeekTestAsync(IRandomAccessStreamWithContentType fileStream, long streamReadSize, byte[] bufferToCompare)
コード例 #35
0
 private static async Task<uint> FileReadStreamSeekAndCompareAsync(IRandomAccessStreamWithContentType fileStream, byte[] bufferToCompare, ulong offset, uint readSize, uint expectedReadCount)
コード例 #36
0
        public static async void ImagetoIsolatedStorageSaver(IRandomAccessStreamWithContentType stream, string filename)
        {
            try
            {
                //WriteableBitmap is used to save our image to our desired location, which in this case is the LocalStorage of app
                var image = new WriteableBitmap(50, 50);
                image.SetSource(stream);

                //Saving to roaming folder so that it can sync the profile pic to other devices
                var saveAsTarget =
                    await
                        ApplicationData.Current.RoamingFolder.CreateFileAsync(filename,
                            CreationCollisionOption.ReplaceExisting);

                //Encoding with Bitmap Encoder to jpeg format
                var encoder = await BitmapEncoder.CreateAsync(
                    BitmapEncoder.JpegEncoderId,
                    await saveAsTarget.OpenAsync(FileAccessMode.ReadWrite));
                //Saving as a stream
                var pixelStream = image.PixelBuffer.AsStream();
                var pixels = new byte[pixelStream.Length];
                await pixelStream.ReadAsync(pixels, 0, pixels.Length);
                encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint) image.PixelWidth,
                    (uint) image.PixelHeight, 96.0, 96.0, pixels);
                await encoder.FlushAsync();
                await pixelStream.FlushAsync();
                pixelStream.Dispose();
                
            }
            catch (Exception e)
            {
                Debug.Write(e);
            }
        }
コード例 #37
0
        public async Task LoadImageAsync(IRandomAccessStreamWithContentType stream)
        {
            var decoder = await BitmapDecoder.CreateAsync(BitmapDecoder.GifDecoderId, stream);
            var imageProperties = await _gifPropertiesHelper.RetrieveImagePropertiesAsync(decoder);
            var frameProperties = new List<FrameProperties>();

            for (var i = 0; i < decoder.FrameCount; i++)
            {
                var bitmapFrame = await decoder.GetFrameAsync((uint)i);
                frameProperties.Add(await _gifPropertiesHelper.RetrieveFramePropertiesAsync(bitmapFrame, i));
            }

            _decoder = decoder;
            _imageProperties = imageProperties;
            _frameProperties = frameProperties;

            CreateImageBuffer();
        }
コード例 #38
0
        private static async Task<uint> BlobReadStreamSeekAndCompareAsync(IRandomAccessStreamWithContentType blobStream, byte[] bufferToCompare, ulong offset, uint readSize, uint expectedReadCount)
#endif
        {
            byte[] testBuffer = new byte[readSize];

#if ASPNET_K
            int actualReadSize = await blobStream.ReadAsync(testBuffer, 0, (int) readSize);
            Assert.AreEqual(expectedReadCount, actualReadSize);
#else
            IBuffer testBufferAsIBuffer = testBuffer.AsBuffer();
            await blobStream.ReadAsync(testBufferAsIBuffer, readSize, InputStreamOptions.None);
            Assert.AreEqual(expectedReadCount, testBufferAsIBuffer.Length);
#endif

            long bufferOffset = (long)offset;
            for (int i = 0; i < expectedReadCount; i++, bufferOffset++)
            {
                Assert.AreEqual(bufferToCompare[bufferOffset], testBuffer[i]);
            }

            return expectedReadCount;
        }
コード例 #39
0
        private static async Task<int> FileReadStreamSeekTestAsync(IRandomAccessStreamWithContentType fileStream, long streamReadSize, byte[] bufferToCompare)
#endif
        {
            int attempts = 1;
            ulong position = 0;
            Assert.AreEqual(position, fileStream.Position);
            position += await FileReadStreamSeekAndCompareAsync(fileStream, bufferToCompare, position, 1024, 1024);
            attempts++;
            Assert.AreEqual(position, fileStream.Position);
            position += await FileReadStreamSeekAndCompareAsync(fileStream, bufferToCompare, position, 512, 512);
            Assert.AreEqual(position, fileStream.Position);
            position = (ulong)(bufferToCompare.Length - 128);
            fileStream.Seek(position);
            Assert.AreEqual(position, fileStream.Position);
            position += await FileReadStreamSeekAndCompareAsync(fileStream, bufferToCompare, position, 1024, 128);
            attempts++;
            Assert.AreEqual(position, fileStream.Position);
            position = 4096;
            fileStream.Seek(position);
            Assert.AreEqual(position, fileStream.Position);
            position += await FileReadStreamSeekAndCompareAsync(fileStream, bufferToCompare, position, 1024, 1024);
            attempts++;
            Assert.AreEqual(position, fileStream.Position);
            position += 4096;
            fileStream.Seek(position);
            Assert.AreEqual(position, fileStream.Position);
            position += await FileReadStreamSeekAndCompareAsync(fileStream, bufferToCompare, position, 1024, 1024);
            Assert.AreEqual(position, fileStream.Position);
            position -= 4096;
            fileStream.Seek(position);
            Assert.AreEqual(position, fileStream.Position);
            position += await FileReadStreamSeekAndCompareAsync(fileStream, bufferToCompare, position, 128, 128);
            Assert.AreEqual(position, fileStream.Position);
            position = (ulong)(streamReadSize + 4096 - 512);
            fileStream.Seek(position);
#if ASPNET_K
            //don't know why adding these two line will pass, but this this the same as the desktop test
            Assert.AreEqual(position, fileStream.Position);
            position += await FileReadStreamSeekAndCompareAsync(fileStream, bufferToCompare, position, 1024, 512);
#endif
            Assert.AreEqual(position, fileStream.Position);
            position += await FileReadStreamSeekAndCompareAsync(fileStream, bufferToCompare, position, 1024, 1024);
            attempts++;
            Assert.AreEqual(position, fileStream.Position);
            position += await FileReadStreamSeekAndCompareAsync(fileStream, bufferToCompare, position, 1024, 1024);
            Assert.AreEqual(position, fileStream.Position);
            position -= 1024;
            fileStream.Seek(position);
            Assert.AreEqual(position, fileStream.Position);
            position += await FileReadStreamSeekAndCompareAsync(fileStream, bufferToCompare, position, 2048, 2048);
            Assert.AreEqual(position, fileStream.Position);
            position = (ulong)(bufferToCompare.Length - 128);
            fileStream.Seek(position);
            Assert.AreEqual(position, fileStream.Position);
            position += await FileReadStreamSeekAndCompareAsync(fileStream, bufferToCompare, position, 1024, 128);
            Assert.AreEqual(position, fileStream.Position);
            return attempts;
        }
コード例 #40
0
 public static SourceReader CreateFromStream(IRandomAccessStreamWithContentType stream)
 {
     return new SourceReader(SourceReaderNative.CreateFromByteStream(stream));
 }