Exemple #1
0
        private async Task WriteImageToFile(InMemoryRandomAccessStream stream, UpdateTypes type)
        {
            StorageFolder localFolder = await GetImageCacheFolder(type);

            StorageFile file = await localFolder.CreateFileAsync("cachedImage.jpg", CreationCollisionOption.GenerateUniqueName);

            using (var fileStream = await file.OpenAsync(FileAccessMode.ReadWrite))
            {
                await RandomAccessStream.CopyAndCloseAsync(stream.GetInputStreamAt(0), fileStream.GetOutputStreamAt(0));
            }
        }
Exemple #2
0
        public async Task <IFrameSource> Encode(StorageFile source)
        {
            MediaClip clip = await MediaClip.CreateFromFileAsync(source);

            var props             = clip.GetVideoEncodingProperties();
            var frameMilliseconts = 1000.0f / ((float)props.FrameRate.Numerator / (float)props.FrameRate.Denominator);
            var frameCount        = (int)(clip.OriginalDuration.TotalMilliseconds / frameMilliseconts);

            var fps = MediaHelper.MillisecondsToFPS((long)frameMilliseconts);

            var frameSource = new FrameSet(fps, (int)props.Width, (int)props.Height);

            TimeSpan frameDuration  = TimeSpan.FromMilliseconds((int)fps);
            TimeSpan frameStartTime = new TimeSpan();

            MediaComposition composition = new MediaComposition();

            composition.Clips.Add(clip);

            for (int idx = 0; idx < frameCount; idx++)
            {
                var time = TimeSpan.FromMilliseconds(idx * frameMilliseconts);

                var frame = await composition.GetThumbnailAsync(
                    time,
                    (int)props.Width,
                    (int)props.Height,
                    VideoFramePrecision.NearestFrame
                    );

                using (var stream = new InMemoryRandomAccessStream())
                {
                    await RandomAccessStream.CopyAsync(frame, stream);

                    BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream);

                    stream.Seek(0);

                    SoftwareBitmap bitmap = SoftwareBitmap.Convert(
                        await decoder.GetSoftwareBitmapAsync(),
                        BitmapPixelFormat.Rgba16,
                        BitmapAlphaMode.Premultiplied);

                    frameSource.AddFrame(new Frame(bitmap)
                    {
                        Duration = frameDuration, StartTime = frameStartTime
                    });
                    frameStartTime += frameDuration;
                }
            }

            return(frameSource);
        }
Exemple #3
0
        private async Task UpdateSourceAsync()
        {
            _gifPresenter?.StopAnimation();

            GifImage.Source = null;
            _gifPresenter   = null;

            if (UriSource != null)
            {
                var uriSource = UriSource;
                try
                {
                    var streamReference = RandomAccessStreamReference.CreateFromUri(uriSource);
                    var readStream      = await streamReference.OpenReadAsync();

                    if (readStream.ContentType.ToLowerInvariant() != "image/gif")
                    {
                        throw new ArgumentException("Unsupported content type: " + readStream.ContentType);
                    }

                    using (readStream)
                        using (var inMemoryStream = new InMemoryRandomAccessStream())
                        {
                            await RandomAccessStream.CopyAndCloseAsync(
                                readStream.GetInputStreamAt(0L),
                                inMemoryStream.GetOutputStreamAt(0L)
                                );


                            if (uriSource.Equals(UriSource))
                            {
                                var gifPresenter = new GifPresenter();
                                GifImage.Source = await gifPresenter.InitializeAsync(inMemoryStream);

                                if (uriSource.Equals(UriSource))
                                {
                                    _gifPresenter?.StopAnimation();
                                    _gifPresenter = gifPresenter;

                                    if (_isLoaded)
                                    {
                                        _gifPresenter.StartAnimation();
                                    }
                                }
                            }
                        }
                }
                catch (FileNotFoundException)
                {
                    // Just keep the empty image source.
                }
            }
        }
        private async Task EnregistrerImage(MediaFrameReference image)
        {
            using (InMemoryRandomAccessStream imageStream = new InMemoryRandomAccessStream())
            {
                await EncoderImage(image, imageStream);

                StorageFile fichierPhoto = await KnownFolders.PicturesLibrary.CreateFileAsync("GpsCam.jpg", CreationCollisionOption.GenerateUniqueName);

                using (IRandomAccessStream photoFileStream = await fichierPhoto.OpenAsync(FileAccessMode.ReadWrite))
                    await RandomAccessStream.CopyAndCloseAsync(imageStream.GetInputStreamAt(0), photoFileStream.GetOutputStreamAt(0));
            }
        }
Exemple #5
0
        private async void GetLogFile(object sender, RoutedEventArgs e)
        {
            if (App.Storage.IsEmpty())
            {
                MessageDialog dialog = new MessageDialog(App.Eng ? "The log is empty. Cannot proceed." :
                                                         "Журнал пуст. Невозможно продолжить.");
                dialog.Commands.Add(new UICommand(App.Eng ? "Okay" : "Окей"));
                await dialog.ShowAsync();

                return;
            }
            progress.Visibility   = Visibility.Visible;
            App.DisableSelection  = true;
            App.SgstBox.IsEnabled = false;
            FileSavePicker savePicker = new FileSavePicker();

            savePicker.FileTypeChoices.Add("Event Log", new List <string> {
                ".elog"
            });
            savePicker.SuggestedFileName = "log" + DateTimeOffset.Now.ToString().Split(' ')[0];
            var dest = await savePicker.PickSaveFileAsync();

            if (dest != null)
            {
                string path = ApplicationData.Current.TemporaryFolder.Path + "\\events.elog";
                await Task.Run(() => ZipFile.CreateFromDirectory(ApplicationData.Current.LocalFolder.Path, path));

                var file = await ApplicationData.Current.TemporaryFolder.GetFileAsync("events.elog");

                using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite))
                {
                    using (DataReader reader = new DataReader(stream.GetInputStreamAt(0)))
                    {
                        await reader.LoadAsync((uint)code.Length);

                        byte[] coded = new byte[code.Length];
                        for (int i = 0; i < coded.Length; i++)
                        {
                            coded[i] = (byte)(reader.ReadByte() ^ code[i]);
                        }
                        using (DataWriter writer = new DataWriter(stream.GetOutputStreamAt(0)))
                            writer.WriteBytes(coded);
                    }

                    using (IRandomAccessStream destStream = await dest.OpenAsync(FileAccessMode.ReadWrite))
                        await RandomAccessStream.CopyAsync(stream, destStream);
                }
                await file.DeleteAsync();
            }
            App.DisableSelection  = false;
            App.SgstBox.IsEnabled = true;
            progress.Visibility   = Visibility.Collapsed;
        }
Exemple #6
0
        private async Task Save(IRandomAccessStream frame, int i)
        {
            var filename    = "ImageSequencer." + i + ".jpg";
            var folder      = Windows.Storage.ApplicationData.Current.TemporaryFolder;
            var storageFile = await folder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);

            var stream = await storageFile.OpenAsync(FileAccessMode.ReadWrite);

            await RandomAccessStream.CopyAndCloseAsync(frame, stream);

            _files.Add(storageFile);
        }
        public override async Task <IRandomAccessStream> GetStreamAsync()
        {
            var file = await StorageFile.GetFileFromApplicationUriAsync(Photo.Source);

            var thumb = await file.GetThumbnailAsync(Windows.Storage.FileProperties.ThumbnailMode.SingleItem);

            var stream = new InMemoryRandomAccessStream();
            await RandomAccessStream.CopyAsync(thumb, stream);

            Ready(this, stream);
            return(stream);
        }
Exemple #8
0
        public async Task SendStreamAsync(MessageType messageType, InMemoryRandomAccessStream bits)
        {
            await this.SendAsync(
                messageType,
                (int)bits.Size,
                async() =>
            {
                await RandomAccessStream.CopyAsync(bits, this.socket.OutputStream);
            }
                );

            bits.Dispose();
        }
 /// <summary>Initializes a new instance of the <see cref="DownloadFileTransferInformation"/> class.</summary>
 /// <param name="peerId">The peer identifier.</param>
 /// <param name="recipientId">The recipient identifier.</param>
 /// <param name="recipientChannel">The recipient channel.</param>
 /// <param name="correlationGuid">The correlation unique identifier.</param>
 /// <param name="fileOutputPath">The file output path.</param>
 /// <param name="fileSize">Size of the file.</param>
 public DownloadFileTransferInformation(PeerId peerId,
                                        PeerId recipientId,
                                        IChannel recipientChannel,
                                        ICorrelationId correlationGuid,
                                        string fileOutputPath,
                                        ulong fileSize) :
     base(peerId, recipientId, recipientChannel,
          correlationGuid, fileOutputPath, fileSize)
 {
     _fileLock          = new object();
     RandomAccessStream = File.Open(TempPath, FileMode.CreateNew);
     RandomAccessStream.SetLength((long)fileSize);
 }
Exemple #10
0
        private async void LoadButton_Click(object sender, RoutedEventArgs e)
        {
            var mediaFile = await m_fileSavePicker.PickSaveFileAsync();

            if (mediaFile != null)
            {
                m_audioStream = new InMemoryRandomAccessStream();
                using (var inputStream = await mediaFile.OpenReadAsync())
                {
                    await RandomAccessStream.CopyAsync(inputStream, m_audioStream);
                }
            }
        }
Exemple #11
0
        private async void Panel_DragStarting(UIElement sender, DragStartingEventArgs args)
        {
            args.Data.RequestedOperation = DataPackageOperation.Copy;

            var file = await StorageFile.CreateStreamedFileAsync("test.txt", async (streamRequest) =>
            {
                // this code is called when the item is dropped
                var bytes = Encoding.UTF8.GetBytes("Hello world!");
                await RandomAccessStream.CopyAndCloseAsync(new MemoryStream(bytes, false).AsInputStream(), streamRequest);
            }, null);

            args.Data.SetStorageItems(new[] { file });
        }
        private async void CaptureSixteenByNineImage()
        {
            //declare string for filename
            var captureFileName = string.Empty;
            //declare image format
            var format = ImageEncodingProperties.CreateJpeg();

            //rotate and save the image
            using (var imageStream = new InMemoryRandomAccessStream())
            {
                //generate stream from MediaCapture
                await captureManager.CapturePhotoToStreamAsync(format, imageStream);

                //create decoder and encoder
                var dec = await BitmapDecoder.CreateAsync(imageStream);

                var enc = await BitmapEncoder.CreateForTranscodingAsync(imageStream, dec);

                //roate the image
                enc.BitmapTransform.Rotation = BitmapRotation.Clockwise90Degrees;

                //write changes to the image stream
                await enc.FlushAsync();

                //save the image
                var folder      = KnownFolders.SavedPictures;
                var capturefile =
                    await
                    folder.CreateFileAsync("photo_" + DateTime.Now.Ticks + ".jpg",
                                           CreationCollisionOption.ReplaceExisting);

                captureFileName = capturefile.Name;

                //store stream in file
                using (var fileStream = await capturefile.OpenStreamForWriteAsync())
                {
                    try
                    {
                        //because of using statement stream will be closed automatically after copying finished
                        await RandomAccessStream.CopyAsync(imageStream, fileStream.AsOutputStream());
                    }
                    catch
                    {
                    }
                }
            }
            CleanCapture();

            //load saved image
            //LoadCapturedphoto(captureFileName);
        }
Exemple #13
0
        public static async Task <bool> SaveBytes(int id, String folderName, byte[] img, string extension, bool isTemp)
        {
            String fileName = String.Format("{0}.{1}", id, extension);

            try
            {
                using (var streamWeb = new InMemoryRandomAccessStream())
                {
                    using (var writer = new DataWriter(streamWeb.GetOutputStreamAt(0)))
                    {
                        writer.WriteBytes(img);
                        await writer.StoreAsync();

                        StorageFolder folder;
                        if (isTemp)
                        {
                            folder = ApplicationData.Current.TemporaryFolder;
                        }
                        else
                        {
                            folder = await ApplicationData.Current.LocalFolder.CreateFolderAsync(folderName, CreationCollisionOption.OpenIfExists);
                        }

                        var file = await folder.CreateFileAsync(fileName, CreationCollisionOption.OpenIfExists);

                        Debug.WriteLine("Writing file " + folderName + " " + id);
                        using (var raStream = await file.OpenAsync(FileAccessMode.ReadWrite))
                        {
                            using (var thumbnailStream = streamWeb.GetInputStreamAt(0))
                            {
                                using (var stream = raStream.GetOutputStreamAt(0))
                                {
                                    await RandomAccessStream.CopyAsync(thumbnailStream, stream);

                                    await stream.FlushAsync();
                                }
                            }
                            await raStream.FlushAsync();
                        }
                        await writer.FlushAsync();
                    }
                    await streamWeb.FlushAsync();
                }
                return(true);
            }
            catch (Exception e)
            {
                Debug.WriteLine("Error saving bytes: " + e);
                return(false);
            }
        }
Exemple #14
0
        /// <summary>
        /// 下载图片,不在本地缓存文件,直接返回BitmapImage对象
        /// </summary>
        /// <param name="p_path">要下载的文件路径</param>
        /// <returns></returns>
        public static async Task <BitmapImage> GetImage(string p_path)
        {
            if (string.IsNullOrEmpty(p_path))
            {
                return(null);
            }

            // 路径肯定含/
            int index = p_path.LastIndexOf('/');

            if (index <= 0)
            {
                return(null);
            }

            MemoryStream stream = new MemoryStream();
            DownloadInfo info   = new DownloadInfo
            {
                Path      = p_path,
                TgtStream = stream,
            };

            bool suc = false;

            try
            {
                suc = await GetFile(info, CancellationToken.None);

                if (suc)
                {
                    stream.Seek(0, SeekOrigin.Begin);
                    BitmapImage bmp = new BitmapImage();
#if UWP
                    var randomStream = new InMemoryRandomAccessStream();
                    var outputStream = randomStream.GetOutputStreamAt(0);
                    await RandomAccessStream.CopyAsync(stream.AsInputStream(), outputStream);

                    await bmp.SetSourceAsync(randomStream);
#else
                    await bmp.SetSourceAsync(stream);
#endif
                    return(bmp);
                }
            }
            finally
            {
                stream.Close();
            }
            return(null);
        }
Exemple #15
0
        public static async Task <IRandomAccessStream> ToRandomAccessStreamAsync(this Stream self)
        {
            Guard.NotNull(self, nameof(self));

            var result = new InMemoryRandomAccessStream();

            using (var input = self.AsInputStream())
            {
                await RandomAccessStream.CopyAsync(input, result);
            }
            result.Seek(0);

            return(result);
        }
        async void AddItem(StorageFile f)
        {
            var b = new Button()
            {
                Width = 120, Height = 85, Margin = new Thickness(5)
            };

            b.Tag    = f;
            b.Click += (s, o) =>
            {
                FileDefaultLaunch(f);
            };
            b.RightTapped += (s, e) =>
            {
                if (contextFlyout == null)
                {
                    InitContextMemu(f);
                }
                contextFlyout.ShowAt(s as UIElement, e.GetPosition(s as UIElement));
            };
            var thumbnail = await f.GetScaledImageAsThumbnailAsync(ThumbnailMode.DocumentsView);

            BitmapImage bitmapImage = new BitmapImage();
            InMemoryRandomAccessStream randomAccessStream = new InMemoryRandomAccessStream();
            await RandomAccessStream.CopyAsync(thumbnail, randomAccessStream);

            randomAccessStream.Seek(0);
            bitmapImage.SetSource(randomAccessStream);
            var im = new Image()
            {
                Source = bitmapImage
            };
            Grid g = new Grid();

            g.RowDefinitions.Add(new RowDefinition());
            g.RowDefinitions.Add(new RowDefinition()
            {
                Height = new GridLength(25)
            });
            g.Children.Add(im);
            TextBlock t = new TextBlock()
            {
                Text = f.Name
            };

            Grid.SetRow(t, 1);
            g.Children.Add(t);
            b.Content = g;
            ResourcePanel.Items.Add(b);
        }
        //play a newly synthesized audio clip
        public async static Task SpeakContentAsync(IInputStream file)
        {
            InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream();

            await RandomAccessStream.CopyAsync(file, stream);

            stream.Seek(0);

            Windows.UI.Xaml.Controls.MediaElement element = new Windows.UI.Xaml.Controls.MediaElement();
            element.SetSource(stream, "audio/x-wav");
            element.Play();

            return;
        }
Exemple #18
0
        /**
         * <summary>get a video's thumbnail by token(or a file)</summary>
         * <param name="file">a StorageFile of video</param>
         */
        public static async Task <BitmapImage> GetThumbnailOfVideo(StorageFile file)
        {
            var thumbnail = await file.GetScaledImageAsThumbnailAsync(ThumbnailMode.VideosView);

            BitmapImage bitmapImage = new BitmapImage();
            InMemoryRandomAccessStream randomAccessStream = new InMemoryRandomAccessStream();
            await RandomAccessStream.CopyAsync(thumbnail, randomAccessStream);

            randomAccessStream.Seek(0);

            await bitmapImage.SetSourceAsync(randomAccessStream);

            return(bitmapImage);
        }
Exemple #19
0
        public static async Task DownloadToFileAsync(Uri url, StorageFile file)
        {
            CachedFileManager.DeferUpdates(file);

            var resp = await HttpClient.GetAsync(url);

            var source = await resp.Content.ReadAsInputStreamAsync();

            var destination = await file.OpenAsync(FileAccessMode.ReadWrite);

            await RandomAccessStream.CopyAndCloseAsync(source, destination);

            await CachedFileManager.CompleteUpdatesAsync(file);
        }
Exemple #20
0
        public static async Task <Uri> ResizeImageFileToFile(Uri uri, uint size)
        {
            IRandomAccessStream ras = await ResizeImageFile(uri, size);

            string fileName = Path.GetRandomFileName();
            var    file     = await ApplicationData.Current.LocalFolder.CreateFileAsync(
                fileName + ".jpg", CreationCollisionOption.GenerateUniqueName);

            using (var fileStream = await file.OpenAsync(FileAccessMode.ReadWrite))
            {
                await RandomAccessStream.CopyAndCloseAsync(ras.GetInputStreamAt(0), fileStream.GetOutputStreamAt(0));
            }
            return(new Uri("ms-appdata:///local/" + file.Name));
        }
        public static async Task <Point> GetPixelWidthAndHeight(this IRandomAccessStream iRandomAccessStream)
        {
            var    tempIRandomAccessStream = iRandomAccessStream.CloneStream();
            Stream inputStream             = WindowsRuntimeStreamExtensions.AsStreamForRead(tempIRandomAccessStream.GetInputStreamAt(0));
            var    copiedBytes             = ConvertStreamTobyte(inputStream);
            Stream tempStream = new MemoryStream(copiedBytes);

            Guid      decoderId = Guid.Empty;
            ImageType type      = ImageTypeCheck.CheckImageType(copiedBytes);

            switch (type)
            {
            case ImageType.GIF:
            {
                break;
            }

            case ImageType.JPG:
            {
                decoderId = BitmapDecoder.JpegDecoderId;
                break;
            }

            case ImageType.PNG:
            {
                decoderId = BitmapDecoder.PngDecoderId;
                break;
            }

            default:
            {
                break;
            }
            }

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

            var bitDecoder = await BitmapDecoder.CreateAsync(decoderId, randomAccessStream);

            var frame = await bitDecoder.GetFrameAsync(0);

            Point point = new Point();

            point.X = frame.PixelWidth;
            point.Y = frame.PixelHeight;
            return(point);
        }
Exemple #22
0
    // TexBox의 내용을 파일에 저장하는 메소드이다.
    // FileSavePicker를 이용하여 WriteTextAsync를 통해 파일에 저장된다.
    // 또한 Compressor를 이용하여 파일 압축도 가능하다.
    public async void SaveAsync(TextBox display)
    {
        try
        {
            FileSavePicker picker = new FileSavePicker
            {
                SuggestedStartLocation = PickerLocationId.DocumentsLibrary
            };
            picker.FileTypeChoices.Add("Text File", new List <string>()
            {
                text_file_extension
            });
            picker.FileTypeChoices.Add("Compressed File", new List <string>()
            {
                compressed_file_extension
            });
            picker.DefaultFileExtension = text_file_extension;
            StorageFile file = await picker.PickSaveFileAsync();

            switch (file.FileType)
            {
            case text_file_extension:
                await FileIO.WriteTextAsync(file, display.Text);

                break;

            case compressed_file_extension:
                using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(display.Text)))
                    using (IRandomAccessStream input = stream.AsRandomAccessStream())
                        using (IRandomAccessStream output = await file.OpenAsync(FileAccessMode.ReadWrite))
                            using (Compressor compressor = new Compressor(output.GetOutputStreamAt(0), compression_algorithm, 0))
                            {
                                ulong inputSize = await RandomAccessStream.CopyAsync(input, compressor);

                                bool finished = await compressor.FinishAsync();

                                ulong outputSize = output.Size;
                                Show($"Compressed {inputSize} bytes to {outputSize} bytes", app_title);
                            }
                break;

            default:
                break;
            }
        }
        catch
        {
        }
    }
        public static async Task <string> GetPhotoFromCameraLaunch(bool isCamera)
        {
            StorageFile photo = null;

            if (isCamera)
            {
                CameraCaptureUI captureUI = new CameraCaptureUI();
                captureUI.PhotoSettings.Format = CameraCaptureUIPhotoFormat.Jpeg;

                photo = await captureUI.CaptureFileAsync(CameraCaptureUIMode.Photo);
            }
            else
            {
                FileOpenPicker openPicker = new FileOpenPicker();
                openPicker.ViewMode = PickerViewMode.Thumbnail;
                openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
                openPicker.FileTypeFilter.Add(".jpg");
                openPicker.FileTypeFilter.Add(".jpeg");
                openPicker.FileTypeFilter.Add(".png");
                photo = await openPicker.PickSingleFileAsync();
            }
            if (photo == null)
            {
                // User cancelled photo capture
                return(null);
            }
            else
            {
                if (!isCamera)
                {
                    return(photo.Name);
                }

                IRandomAccessStream stream = await photo.OpenAsync(FileAccessMode.Read);

                string      imageName       = GenerateFileName("TripTrak");
                StorageFile destinationFile = await KnownFolders.CameraRoll.CreateFileAsync(imageName);

                using (var destinationStream = await destinationFile.OpenAsync(FileAccessMode.ReadWrite))
                {
                    using (var destinationOutputStream = destinationStream.GetOutputStreamAt(0))
                    {
                        await RandomAccessStream.CopyAndCloseAsync(stream, destinationStream);
                    }
                }

                return(imageName);
            }
        }
Exemple #24
0
        public static async Task DownloadToFileWithProgressAsync(Uri url, StorageFile file, IProgress <HttpProgress> progress)
        {
            CachedFileManager.DeferUpdates(file);

            var message = new HttpRequestMessage(HttpMethod.Get, url);
            var resp    = await HttpClient.SendRequestAsync(message).AsTask(progress);

            var content = await resp.Content.ReadAsInputStreamAsync();

            var fileStream = await file.OpenAsync(FileAccessMode.ReadWrite);

            await RandomAccessStream.CopyAndCloseAsync(content, fileStream);

            await CachedFileManager.CompleteUpdatesAsync(file);
        }
Exemple #25
0
        public async static Task SpeakTranslationAsync(IInputStream file)
        {
            InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream();

            await RandomAccessStream.CopyAsync(file, stream);

            stream.Seek(0);

            MediaElement element = new MediaElement();

            element.SetSource(stream, "audio/x-wav");
            element.Play();

            return;
        }
Exemple #26
0
        protected override async void init(Stream stream, bool flip, Loader.LoadedCallbackMethod loadedCallback)
        {
            try
            {
                using (var memoryStream = new InMemoryRandomAccessStream())
                {
                    await RandomAccessStream.CopyAsync(stream.AsInputStream(), memoryStream);

                    var decoder = await BitmapDecoder.CreateAsync(memoryStream);

                    var frame = await decoder.GetFrameAsync(0);

                    var transform = new BitmapTransform();
                    transform.InterpolationMode = BitmapInterpolationMode.NearestNeighbor;
                    transform.Rotation          = BitmapRotation.None;
                    var dataProvider = await decoder.GetPixelDataAsync(BitmapPixelFormat.Rgba8, BitmapAlphaMode.Straight, transform, ExifOrientationMode.IgnoreExifOrientation, ColorManagementMode.ColorManageToSRgb);

                    var data = dataProvider.DetachPixelData();

                    int width  = (int)decoder.PixelWidth;
                    int height = (int)decoder.PixelHeight;
                    Mipmaps = new Mipmap[1];
                    Size    = new Size2(width, height);

                    Mipmaps[0] = new Mipmap(data, width, height, 1, 4);
                    if (flip)
                    {
                        Mipmaps[0].FlipVertical();
                    }
                }
            }
            catch (Exception e)
            {
                FailedToLoad = true;
                Loader.AddLoadableException(e);
                if (loadedCallback != null)
                {
                    loadedCallback(this, false);
                }
                return;
            }

            Loaded = true;
            if (loadedCallback != null)
            {
                loadedCallback(this, true);
            }
        }
Exemple #27
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;
            }
        }
 private async void GetThumbnailAsync(StorageFile file)
 {
     using (InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream())
     {
         try
         {
             await RandomAccessStream.CopyAsync(await file.GetThumbnailAsync(Windows.Storage.FileProperties.ThumbnailMode.SingleItem), stream);
         }
         catch
         {
             await RandomAccessStream.CopyAsync(await file.GetThumbnailAsync(Windows.Storage.FileProperties.ThumbnailMode.SingleItem), stream);
         }
         stream.Seek(0);
         Icon.SetSource(stream);
     }
 }
Exemple #29
0
        private async Task WriteToFile(IRandomAccessStream memStream)
        {
            var myPictures = await StorageLibrary.GetLibraryAsync(KnownLibraryId.Pictures);

            var wFile = await myPictures.Folders[0]
                        .CreateFileAsync("testYao.jpg", CreationCollisionOption.ReplaceExisting);

            var wStream = await wFile.OpenAsync(FileAccessMode.ReadWrite);

            using (var outputStream = wStream.GetOutputStreamAt(0))
            {
                memStream.Seek(0);
                await RandomAccessStream.CopyAsync(memStream, outputStream);
            }
            wStream.Dispose();
        }
        public static async Task <StorageFile> StoreToFolderAsync(string fullName, StorageFolder folder, IRandomAccessStream inputStream, CancellationToken cancelToken = default(CancellationToken))
        {
            if (fullName == "")
            {
                return(null);
            }

            var file = await folder.CreateFileAsync(fullName, CreationCollisionOption.ReplaceExisting);

            using (var stream = await file.OpenAsync(FileAccessMode.ReadWrite))
            {
                await RandomAccessStream.CopyAndCloseAsync(inputStream.GetInputStreamAt(0), stream.GetOutputStreamAt(0)).AsTask(cancelToken);
            }

            return(file);
        }