private async Task OpenFilePDFViewer(IStorageFile file, FileAccessMode mode)
        {
            if (file == null)
            {
                return;
            }

            Windows.Storage.Streams.IRandomAccessStream stream;
            try
            {
                stream = await file.OpenAsync(mode);
            }
            catch (Exception e)
            {
                // NOTE: If file already opened it will cause an exception
                var msg = new MessageDialog(e.Message);
                _ = msg.ShowAsync();
                return;
            }

            PDFDoc doc = new PDFDoc(stream);

            doc.InitSecurityHandler();

            // Set loaded doc to PDFView Controler
            PDFViewCtrl.SetDoc(doc);

            ThumbnailViewer = new ThumbnailViewer(PDFViewCtrl, file.Path);
        }
Пример #2
0
 public async static Task <T> DeserializeFromFileAsync(IStorageFile file)
 {
     using (var stream = (await file.OpenAsync(FileAccessMode.Read)).GetInputStreamAt(0).AsStreamForRead()) {
         XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
         return((T)xmlSerializer.Deserialize(stream));
     }
 }
Пример #3
0
        public static async Task<string> Hash(IStorageFile file)
        {
            string res = string.Empty;

            using(var streamReader = await file.OpenAsync(FileAccessMode.Read))
            {
                var alg = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Md5);
                var algHash = alg.CreateHash();

                using(BinaryReader reader = new BinaryReader(streamReader.AsStream(), Encoding.UTF8))
                {
                    byte[] chunk;

                    chunk = reader.ReadBytes(CHUNK_SIZE);
                    while(chunk.Length > 0)
                    {
                        algHash.Append(CryptographicBuffer.CreateFromByteArray(chunk));
                        chunk = reader.ReadBytes(CHUNK_SIZE);
                    }
                }

                res = CryptographicBuffer.EncodeToHexString(algHash.GetValueAndReset());
                return res;
            }
        }
Пример #4
0
 public async static void SerializeToFileAsync(T objectToSerialize, IStorageFile file)
 {
     using (var stream = (await file.OpenAsync(FileAccessMode.ReadWrite)).GetOutputStreamAt(0).AsStreamForWrite()) {
         XmlSerializer serializer = new XmlSerializer(typeof(T));
         serializer.Serialize(stream, objectToSerialize);
     }
 }
Пример #5
0
        public async void ReadHistoryData()
        {
            try
            {
                _historyFile = await _currentFolder.GetFileAsync(HistoryDataFilename);
            }
            catch (FileNotFoundException e)
            {
                Log.E(e.Message);
                Log.D(e.StackTrace);
                Log.D(e.Source);
                HistoryData = new HistoryData();
                return;
            }

            using (var stream = await _historyFile.OpenAsync(FileAccessMode.ReadWrite))
            {
                lock (_thisLock)
                {
                    using (var reader = stream.AsStreamForRead())
                    {
                        var obj = _serializer.ReadObject(reader);
                        if (obj is HistoryData)
                        {
                            HistoryData = obj as HistoryData;
                        }
                        else
                        {
                            throw new SerializationException(nameof(obj) + " is not " + nameof(HistoryData));
                        }
                    }
                }
            }
        }
        public void WriteAllText(string filename, string text, Action completed)
        {
            StorageFolder localFolder =
                ApplicationData.Current.LocalFolder;
            IAsyncOperation <StorageFile> createOp =
                localFolder.CreateFileAsync(filename,
                                            CreationCollisionOption.ReplaceExisting);

            createOp.Completed = (asyncInfo1, asyncStatus1) =>
            {
                IStorageFile storageFile = asyncInfo1.GetResults();
                IAsyncOperation <IRandomAccessStream> openOp =
                    storageFile.OpenAsync(FileAccessMode.ReadWrite);
                openOp.Completed = (asyncInfo2, asyncStatus2) =>
                {
                    IRandomAccessStream stream     = asyncInfo2.GetResults();
                    DataWriter          dataWriter = new DataWriter(stream);
                    dataWriter.WriteString(text);
                    DataWriterStoreOperation storeOp =
                        dataWriter.StoreAsync();
                    storeOp.Completed = (asyncInfo3, asyncStatus3) =>
                    {
                        dataWriter.Dispose();
                        completed();
                    };
                };
            };
        }
Пример #7
0
        /// <summary>
        /// 将图像写入到文件
        /// </summary>
        /// <param name="writeableBitmap"></param>
        /// <param name="storageFile"></param>
        /// <returns></returns>
        public async Task SaveToStorageFile(WriteableBitmap writeableBitmap, IStorageFile storageFile, double dpi = 100.0)
        {
            var bitmap = new RenderTargetBitmap();
            await bitmap.RenderAsync(qrcodeImage);

            var writeableBmp = await bitmap.GetPixelsAsync();

            using (var writestream = await storageFile.OpenAsync(FileAccessMode.ReadWrite))
            {
                var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, writestream);

                using (var pixelStream = writeableBitmap.PixelBuffer.AsStream())
                {
                    var pixels = new byte[pixelStream.Length];
                    await pixelStream.ReadAsync(pixels, 0, pixels.Length);

                    encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore,
                                         (uint)writeableBitmap.PixelWidth, (uint)writeableBitmap.PixelHeight, dpi, dpi, pixels);

                    await encoder.FlushAsync();

                    UIHelper.ShowDialog("保存在相册:保存的图片 中", AlertIcon.Ok);
                }
            }
        }
Пример #8
0
        public static async Task <bool> TryTranscodePhotoAsync(IStorageFile input, IStorageFile output, IProgress <double?> progress, CancellationToken token = default)
        {
            progress.Report(null);

            try
            {
                using (var inputStream = await input.OpenAsync(FileAccessMode.Read))
                    using (var outputStream = await output.OpenAsync(FileAccessMode.ReadWrite))
                    {
                        var decoder = await BitmapDecoder.CreateAsync(inputStream);

                        double width  = (int)decoder.PixelWidth;
                        double height = (int)decoder.PixelHeight;

                        Drawing.ScaleProportions(ref width, ref height, 2048, 2048);

                        var encoder = await BitmapEncoder.CreateForTranscodingAsync(outputStream, decoder);

                        encoder.BitmapTransform.ScaledWidth  = (uint)width;
                        encoder.BitmapTransform.ScaledHeight = (uint)height;
                        await encoder.FlushAsync();

                        return(true);
                    }
            }
            catch
            {
                return(false);
            }
        }
Пример #9
0
        private async Task <ImageResult> ResizeAsync(IStorageFile file, Size oldSize, Size newSize)
        {
            var newFile = await CreateNewFile();

            try
            {
                using (IRandomAccessStream source = await file.OpenAsync(FileAccessMode.Read)) {
                    var decoder = await BitmapDecoder.CreateAsync(source);

                    var transform = new BitmapTransform {
                        ScaledHeight = (uint)newSize.Height,
                        ScaledWidth  = (uint)newSize.Width
                    };
                    var pixelData = await decoder.GetPixelDataAsync(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight, transform, ExifOrientationMode.RespectExifOrientation, ColorManagementMode.DoNotColorManage);

                    using (IRandomAccessStream destinationStream = await newFile.OpenAsync(FileAccessMode.ReadWrite)) {
                        var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, destinationStream);

                        encoder.SetPixelData(BitmapPixelFormat.Rgba8, BitmapAlphaMode.Premultiplied, (uint)newSize.Width,
                                             (uint)newSize.Height, 96, 96, pixelData.DetachPixelData());
                        await encoder.FlushAsync();
                    }
                }
            }
            catch (Exception ex) {
                if (_ensureSuccessfullScale)
                {
                    throw new Exception("image can not be resized123");
                }
            }
            return(new ImageResult(oldSize, newFile));
        }
        //Stream的读取操作
        //使用Stream读取文件的内容,需要先调用DataReader类的LoadAsync方法,把数据加载进来,再调用相关的Read方法来读取文件的内容;
        //Buffer的操作不用调用LoadAsync方法,那是因为其已经一次性把数据都读取出来了
        public async void StreamReader(IStorageFile file)
        {
            using (IRandomAccessStream readStream = await file.OpenAsync(FileAccessMode.Read))
            {
                using (DataReader dataReader = new DataReader(readStream))
                {
                    //读取文件的相关信息,读取规则要与文件的规则一致
                    //await dataReader.LoadAsync(sizeof(Int32));
                    //Int32 stringSize = dataReader.ReadInt32();
                    //await dataReader.LoadAsync(4096);
                    //string fileContent = dataReader.ReadString((uint)stringSize);



                    //add test code
                    uint size = await dataReader.LoadAsync(sizeof(uint));

                    if (size < sizeof(uint))
                    {
                        return;
                    }
                    else
                    {
                        uint stringLength       = dataReader.ReadUInt32();
                        uint actualStringLength = await dataReader.LoadAsync(stringLength);

                        if (actualStringLength != stringLength)
                        {
                            // The underlying socket was closed before we were able to read the whole data
                            return;
                        }
                    }
                }
            }
        }
Пример #11
0
        public static async Task <Tuple <bool, byte[]> > FillBuffer(IStorageFile file, UploadablePart part)
        {
            try
            {
                if (part.ParentItem.FileNotFound)
                {
                    return(new Tuple <bool, byte[]>(false, null));
                }

                using (var stream = await file.OpenAsync(FileAccessMode.Read))
                {
                    using (var inStream = stream.GetInputStreamAt((ulong)part.Position))
                    {
                        var bytes = new byte[part.Count];
                        using (var reader = new DataReader(inStream))
                        {
                            await reader.LoadAsync((uint)bytes.Length);

                            reader.ReadBytes(bytes);
                        }

                        // encrypting part
                        if (part.ParentItem.Key != null &&
                            part.ParentItem.IV != null)
                        {
                            var key = part.ParentItem.Key;
                            var iv  = part.FilePart.Value == 0 ? part.ParentItem.IV : part.IV;

                            if (iv == null)
                            {
                                return(new Tuple <bool, byte[]>(true, null));
                            }

                            byte[] nextIV;

                            var encryptedBytes = Utils.AesIge(bytes, key.Data, iv.Data, true, out nextIV);
                            bytes = encryptedBytes;

                            var nextPartId = part.FilePart.Value + 1;
                            if (part.ParentItem.Parts.Count > nextPartId)
                            {
                                part.ParentItem.Parts[nextPartId].IV = TLString.FromBigEndianData(nextIV);
                            }
                        }

                        return(new Tuple <bool, byte[]>(true, bytes));
                    }
                }
            }
            catch (FileNotFoundException ex)
            {
                Execute.ShowDebugMessage("FillBuffer FileNotFoundException\n" + ex);
                return(new Tuple <bool, byte[]>(false, null));
            }
            catch (Exception ex)
            {
                Execute.ShowDebugMessage("FillBuffer Exception\n" + ex);
                return(new Tuple <bool, byte[]>(true, null));
            }
        }
Пример #12
0
 public async Task <RenderTargetBitmap> RenderToFileAsync(UIElement uiElement, IStorageFile file, Guid bitmapEncoder)
 {
     using (var stream = await file.OpenAsync(FileAccessMode.ReadWrite))
     {
         return(await RenderToStreamAsync(uiElement, stream, bitmapEncoder));
     }
 }
Пример #13
0
        private async Task HandleSuccessfullDownload(SignalAttachment attachment, IStorageFile tmpDownload, DownloadOperation download)
        {
            try
            {
                SemaphoreSlim.Wait(CancelSource.Token);
                StorageFile plaintextFile = await ApplicationData.Current.LocalCacheFolder.CreateFileAsync(@"Attachments\" + attachment.Id + ".plain", CreationCollisionOption.ReplaceExisting);

                using (var tmpFileStream = (await tmpDownload.OpenAsync(FileAccessMode.ReadWrite)).AsStream())
                    using (var plaintextFileStream = (await plaintextFile.OpenAsync(FileAccessMode.ReadWrite)).AsStream())
                    {
                        Logger.LogInformation("Decrypting to {0}\\{1}", plaintextFile.Path, plaintextFile.Name);
                        DecryptAttachment(attachment.ToAttachmentPointer(), tmpFileStream, plaintextFileStream);
                    }
                Logger.LogInformation("Deleting tmpFile {0}", tmpDownload.Name);
                await tmpDownload.DeleteAsync();

                attachment.Status = SignalAttachmentStatus.Finished;
                SignalDBContext.UpdateAttachmentStatus(attachment);
                await DispatchAttachmentStatusChanged(download, attachment);
            }
            catch (Exception e)
            {
                Logger.LogError("HandleSuccessfullDownload failed: {0}\n{1}", e.Message, e.StackTrace);
            }
            finally
            {
                if (Downloads.ContainsKey(attachment.Id))
                {
                    Downloads.Remove(attachment.Id);
                }
                SemaphoreSlim.Release();
            }
        }
Пример #14
0
        public IAsyncAction SaveSnapshotAsync(SnapshotData data)
        {
            byte[] pixeldata = data.data;
            int    pitch     = data.pitch;

            Func <Task> helper = async() =>
            {
                if (this.currentROM == null)
                {
                    return;
                }

                int pixelWidth  = pitch / 4;
                int pixelHeight = (int)pixeldata.Length / pitch;

                IStorageFile file = await this.GetFileUsingExtension(".png", true);

                using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite))
                {
                    BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, stream);

                    encoder.SetPixelData(
                        BitmapPixelFormat.Rgba8, BitmapAlphaMode.Ignore,
                        (uint)pixelWidth, (uint)pixelHeight, 96.0, 96.0, pixeldata);
                    await encoder.FlushAsync();
                }
                await this.RefreshROMListAsync();
            };

            return(helper().AsAsyncAction());
        }
Пример #15
0
        private async Task <string> ComputeMD5(IStorageFile file)
        {
            string res = string.Empty;

            using (var streamReader = await file.OpenAsync(FileAccessMode.Read))
            {
                var alg     = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Md5);
                var algHash = alg.CreateHash();

                using (BinaryReader reader = new BinaryReader(streamReader.AsStream()))
                {
                    byte[] chunk;

                    chunk = reader.ReadBytes(CHUNK_SIZE);
                    while (chunk.Length > 0)
                    {
                        algHash.Append(CryptographicBuffer.CreateFromByteArray(chunk));
                        chunk = reader.ReadBytes(CHUNK_SIZE);
                    }
                }

                res = CryptographicBuffer.EncodeToHexString(algHash.GetValueAndReset());
                return(res);
            }
        }
        public static async Task <SafeWrapperResult> CopyFileAsync(IStorageFile source, IStorageFile destination, Action <float> progressReportDelegate, CancellationToken cancellationToken)
        {
            long fileSize = await StorageHelpers.GetFileSize(source);

            byte[]            buffer = new byte[Constants.FileSystem.COPY_FILE_BUFFER_SIZE];
            SafeWrapperResult result = SafeWrapperResult.S_SUCCESS;

            using (Stream sourceStream = (await source.OpenReadAsync()).AsStreamForRead())
            {
                using (Stream destinationStream = (await destination.OpenAsync(FileAccessMode.ReadWrite)).AsStreamForWrite())
                {
                    long bytesTransferred = 0L;
                    int  currentBlockSize = 0;

                    while ((currentBlockSize = await sourceStream.ReadAsync(buffer, 0, buffer.Length)) > 0)
                    {
                        bytesTransferred += currentBlockSize;
                        float percentage = (float)bytesTransferred * 100.0f / (float)fileSize;

                        await destinationStream.WriteAsync(buffer, 0, currentBlockSize);

                        progressReportDelegate?.Invoke(percentage);

                        if (cancellationToken.IsCancellationRequested)
                        {
                            // TODO: Delete copied file there
                            result = SafeWrapperResult.S_CANCEL;
                            break;
                        }
                    }
                }
            }

            return(result);
        }
Пример #17
0
        /// <summary>
        /// The save to file.
        /// </summary>
        /// <param name="writeableBitmap">
        /// The writeable bitmap.
        /// </param>
        /// <param name="outputFile">
        /// The output file.
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        private async Task SaveToFile(WriteableBitmap writeableBitmap, IStorageFile outputFile)
        {
            try
            {
                var stream = writeableBitmap.PixelBuffer.AsStream();

                var pixels = new byte[(uint)stream.Length];
                await stream.ReadAsync(pixels, 0, pixels.Length);

                using (var streamOut = await outputFile.OpenAsync(FileAccessMode.ReadWrite))
                {
                    var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, streamOut);

                    encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight, (uint)writeableBitmap.PixelWidth, (uint)writeableBitmap.PixelHeight, 96, 96, pixels);

                    await encoder.FlushAsync();

                    using (var outputStream = streamOut.GetOutputStreamAt(0))
                    {
                        await outputStream.FlushAsync();
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
        }
Пример #18
0
        async public void OnCapturesCommand(object param)
        {
            MediaCapture takePhotoManager = new MediaCapture();
            await takePhotoManager.InitializeAsync();

            ImageEncodingProperties imgFormat = ImageEncodingProperties.CreateJpeg();
            IStorageFile            file      = await ApplicationData.Current.LocalFolder.CreateFileAsync(
                "Photo.jpg", CreationCollisionOption.GenerateUniqueName);

            await takePhotoManager.CapturePhotoToStorageFileAsync(imgFormat, file);

            //Windows.Storage.StorageFile file = await cameraUI.CaptureFileAsync(CameraCaptureUIMode.PhotoOrVideo);

            if (file != null)
            {
                IRandomAccessStream fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);

                BitmapImage bitmap = new BitmapImage();
                bitmap.SetSource(fileStream);

                IGraphInfo graph = this.Info as IGraphInfo;
                NodeVM     node  = new NodeVM();
                node.OffsetX    = ((this.Info as IGraph).ScrollSettings.ScrollInfo.ViewportWidth) / 2;
                node.OffsetY    = ((this.Info as IGraph).ScrollSettings.ScrollInfo.ViewportHeight) / 2;
                node.UnitHeight = 100;
                node.UnitWidth  = 100;
                node.Content    = new Image()
                {
                    Source = bitmap, Stretch = Stretch.Fill
                };
                (Nodes as ObservableCollection <NodeVM>).Add(node);
            }
        }
Пример #19
0
        private async Task <PDFDoc> OpenFilePDFViewer(IStorageFile file, FileAccessMode mode)
        {
            if (file == null)
            {
                return(null);
            }

            Windows.Storage.Streams.IRandomAccessStream stream;
            try
            {
                stream = await file.OpenAsync(mode);
            }
            catch (Exception e)
            {
                // NOTE: If file already opened it will cause an exception
                var msg = new MessageDialog(e.Message);
                _ = msg.ShowAsync();
                return(null);
            }

            PDFDoc doc = new PDFDoc(stream);

            doc.InitSecurityHandler();

            return(doc);
        }
Пример #20
0
        public static async Task SaveToFile(
            this WriteableBitmap writeableBitmap,
            IStorageFile outputFile,
            Guid encoderId)
        {
            try
            {
                Stream stream = writeableBitmap.PixelBuffer.AsStream();
                byte[] pixels = new byte[(uint)stream.Length];
                await stream.ReadAsync(pixels, 0, pixels.Length);

                using (var writeStream = await outputFile.OpenAsync(FileAccessMode.ReadWrite))
                {
                    var encoder = await BitmapEncoder.CreateAsync(encoderId, writeStream);
                    encoder.SetPixelData(
                        BitmapPixelFormat.Bgra8,
                        BitmapAlphaMode.Premultiplied,
                        (uint)writeableBitmap.PixelWidth,
                        (uint)writeableBitmap.PixelHeight,
                        96,
                        96,
                        pixels);
                    await encoder.FlushAsync();

                    using (var outputStream = writeStream.GetOutputStreamAt(0))
                    {
                        await outputStream.FlushAsync();
                    }
                }
            }
            catch (Exception ex)
            {
                string s = ex.ToString();
            }
        }
Пример #21
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="writeableBitmap"></param>
        /// <param name="outputFile"></param>
        /// <param name="encoderId"></param>
        /// <returns></returns>
        public static async Task SaveToFile(this WriteableBitmap writeableBitmap, IStorageFile outputFile, Guid encoderId)
        {
            try
            {
                Stream stream = writeableBitmap.PixelBuffer.AsStream();
                byte[] pixels = new byte[(uint)stream.Length];
                await stream.ReadAsync(pixels, 0, pixels.Length);

                using (var writeStream = await outputFile.OpenAsync(FileAccessMode.ReadWrite))
                {
                    var encoder = await BitmapEncoder.CreateAsync(encoderId, writeStream);

                    encoder.SetPixelData(
                        BitmapPixelFormat.Bgra8,
                        BitmapAlphaMode.Premultiplied,
                        (uint)writeableBitmap.PixelWidth,
                        (uint)writeableBitmap.PixelHeight,
                        96,
                        96,
                        pixels);
                    await encoder.FlushAsync();

                    using (var outputStream = writeStream.GetOutputStreamAt(0))
                    {
                        await outputStream.FlushAsync();
                    }
                }
            }
            catch (Exception ex)
            {
                string s = ex.ToString();
            }
        }
        private async Task <bool> UploadFile(IStorageFile localFile, string path)
        {
            var result = false;
            var cts    = new CancellationTokenSource();

            CachedFileManager.DeferUpdates(localFile);
            try
            {
                using (var stream = await localFile.OpenAsync(FileAccessMode.Read))
                {
                    var targetStream = stream.AsStreamForRead();

                    IProgress <WebDavProgress> progress = new Progress <WebDavProgress>(ProgressHandler);
                    result = await _client.Upload(path, targetStream, localFile.ContentType, progress, cts.Token);
                }
            }
            catch (ResponseError e2)
            {
                ResponseErrorHandlerService.HandleException(e2);
            }

            // Let Windows know that we're finished changing the file so
            // the other app can update the remote version of the file.
            // Completing updates may require Windows to ask for user input.
            await CachedFileManager.CompleteUpdatesAsync(localFile);

            return(result);
        }
Пример #23
0
        public static async Task<FlacMediaSourceAdapter> CreateAsync(IStorageFile file)
        {
            var fileStream = await file.OpenAsync(FileAccessMode.Read);
            var adapter = new FlacMediaSourceAdapter();
            adapter.Initialize(fileStream);

            return adapter;
        }
Пример #24
0
 public FileItemToShare(String fileName, String filePath, IStorageFile fileToShare)
 {
     this.m_FileName   = fileName;
     this.m_FilePath   = filePath;
     this.FileSize     = fileToShare.OpenAsync(FileAccessMode.Read).AsTask().Result.Size;
     this.m_File       = fileToShare;
     m_FileShareStatus = FileShareStatus.Waiting;
 }
Пример #25
0
        public async void DisplayFrame()
        {
            if (Sleeping)
            {
                Debug.WriteLine(@"Fake Module sleeping, I'll do nothing");
                return;
            }

            if (_image != null)
            {
                /* Generate gray image */
                byte[] generatedImage = new byte[4 * Width * Height];
                for (int i = 0; i < Width * Height; ++i)
                {
                    if ((buffer[i / 8] & (0x80 >> (i % 8))) == 0)
                    {
                        generatedImage[4 * i]     = 0;
                        generatedImage[4 * i + 1] = 0;
                        generatedImage[4 * i + 2] = 0;
                        generatedImage[4 * i + 3] = 255;
                    }
                    else
                    {
                        generatedImage[4 * i]     = 255;
                        generatedImage[4 * i + 1] = 255;
                        generatedImage[4 * i + 2] = 255;
                        generatedImage[4 * i + 3] = 255;
                    }
                }

                IStorageFolder applicationfolder = ApplicationData.Current.LocalFolder;
                Debug.WriteLine(applicationfolder.Path);
                IStorageFile saveFile = await applicationfolder.CreateFileAsync("test.png", CreationCollisionOption.ReplaceExisting);

                using (var fileStream = await saveFile.OpenAsync(FileAccessMode.ReadWrite))
                {
                    var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, fileStream);

                    encoder.SetPixelData(BitmapPixelFormat.Rgba8, BitmapAlphaMode.Ignore,
                                         (uint)Width, (uint)Height, 75, 75, generatedImage.ToArray());
                    await encoder.FlushAsync();
                }

                /* Create a bitmap source */
                Stream s = await applicationfolder.OpenStreamForReadAsync("test.png");

                BitmapImage imageSource = new BitmapImage();
                await imageSource.SetSourceAsync(s.AsRandomAccessStream());

                BitmapImage One = new BitmapImage(new Uri("ms-appx:///Assets/StoreLogo.png"));

                /* Update image to the control */
                _image.Source = imageSource;
                _image.Width  = Width;
                _image.Height = Height;
            }
        }
Пример #26
0
 public async void Save_as(IStorageFile file, Excuse excuseToWrite)
 {
     using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite))
         using(Stream outputStream = stream.AsStreamForWrite())
     {
         DataContractSerializer serializer = new DataContractSerializer(typeof(Excuse));
         serializer.WriteObject(outputStream, excuseToWrite);
     }
     OnPropertyChanged("excuseToWrite");
 }
Пример #27
0
        public static async Task <FlacMediaSourceAdapter> CreateAsync(IStorageFile file)
        {
            var fileStream = await file.OpenAsync(FileAccessMode.Read);

            var adapter = new FlacMediaSourceAdapter();

            adapter.Initialize(fileStream);

            return(adapter);
        }
Пример #28
0
        //public static async Task SaveXmlFile(IStorageFile file)
        //{
        //    await SaveXElement(null, file);
        //}

        private static async Task SaveXElement(XElement elem, IStorageFile file)
        {
            var doc = new XDocument(new XDeclaration("1.0", "utf-8", "yes"));

            doc.Add(elem);
            using (var stream = await file.OpenAsync(FileAccessMode.ReadWrite))
            {
                doc.Save(stream.AsStreamForWrite());
            }
        }
        private async Task LoadIconAsync(IStorageFile file)
        {
            using (IRandomAccessStream fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read))
            {
                BitmapImage bitmapImage = new BitmapImage();
                await bitmapImage.SetSourceAsync(fileStream);

                Icon = bitmapImage;
            }
        }
Пример #30
0
        private async void SaveSoftwareBitmapToFile(SoftwareBitmap softwareBitmap, IStorageFile outputFile)
        {
            using (var stream = await outputFile.OpenAsync(FileAccessMode.ReadWrite))
            {
                var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream);

                encoder.SetSoftwareBitmap(softwareBitmap);
                await encoder.FlushAsync();
            }
        }
Пример #31
0
        public static async Task <BitmapImage> ConvertStorageToImage(IStorageFile savedStorageFile)
        {
            using (IRandomAccessStream fileStream = await savedStorageFile.OpenAsync(Windows.Storage.FileAccessMode.Read))
            {
                BitmapImage bitmapImage = new BitmapImage();
                await bitmapImage.SetSourceAsync(fileStream);

                return(bitmapImage);
            }
        }
Пример #32
0
        public static async Task <T> Deserialize <T>(IStorageFile file)
        {
            T val;

            using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.Read))
            {
                XmlSerializer xs = new XmlSerializer(typeof(T));
                val = (T)xs.Deserialize(stream.AsStreamForRead());
            }
            return(val);
        }
Пример #33
0
 public async Task<Excuse> OpenFile(IStorageFile file, Excuse excuseToRead)
 {
     using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.Read))
         using(Stream inputStream = stream.AsStreamForRead())
     {
         DataContractSerializer serializer = new DataContractSerializer(typeof(Excuse));
         excuseToRead = serializer.ReadObject(inputStream) as Excuse;
     }
     return excuseToRead;
     
 }
Пример #34
0
        public static async Task<BitmapImage> GetImageFromFileAsync(IStorageFile file)
        {
            IRandomAccessStream fileStream =
                              await file.OpenAsync(Windows.Storage.FileAccessMode.Read);

            // Set the image source to the selected bitmap.
            BitmapImage bitmapImage = new BitmapImage();
            bitmapImage.SetSource(fileStream);

            return bitmapImage;
        }
Пример #35
0
        public static async Task<byte[]> ReadFromFile(IStorageFile file)
        {
            var stream = await file.OpenAsync(FileAccessMode.Read);
            var reader = new DataReader(stream.GetInputStreamAt(0));

            var streamSize = (uint) stream.Size;
            await reader.LoadAsync(streamSize);
            var buffer = new byte[streamSize];
            reader.ReadBytes(buffer);
            return buffer;
        }
Пример #36
0
        private static async Task <SoftwareBitmap> ConvertToSoftwareBitmap(IStorageFile file)
        {
            using (var stream = await file.OpenAsync(FileAccessMode.Read))
            {
                var decoder = await BitmapDecoder.CreateAsync(stream);

                var softwareBitmap = await decoder.GetSoftwareBitmapAsync();

                return(SoftwareBitmap.Convert(softwareBitmap, BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied));
            }
        }
Пример #37
0
            public static async Task <TagLib.File.IFileAbstraction> CreateAsync(IStorageFile file)
            {
                var fAbs = new UwpFileAbstraction();

                fAbs.Name = file.Path;
                var ras = await file.OpenAsync(FileAccessMode.Read);

                fAbs.ReadStream = ras.AsStream();

                return(fAbs);
            }
Пример #38
0
        public async Task LoadPwDatabase(IStorageFile pwDatabaseFile, IList<IUserKey> userKeys, IProgress<double> percentComplete)
        {
            StorageFile = pwDatabaseFile;
            var factory = new KdbReaderFactory(_encryptionEngine,
                      _keyTransformer,
                      _hasher,
                      _gzipStreamFactory);

            var file = await pwDatabaseFile.OpenAsync(FileAccessMode.Read);

            Stream kdbDataReader = file.AsStream();

            this.PwDatabase = await factory.LoadAsync(kdbDataReader, userKeys, percentComplete);
        }
Пример #39
0
        public async void ReadGuyAsync()
        {
            if (String.IsNullOrEmpty(Path))
                return;
            latestGuyFile = await StorageFile.GetFileFromPathAsync(Path);

            using (IRandomAccessStream stream =
                        await latestGuyFile.OpenAsync(FileAccessMode.Read))
            using (Stream inputStream = stream.AsStreamForRead())
            {
                DataContractSerializer serializer = new DataContractSerializer(typeof(Guy));
                NewGuy = serializer.ReadObject(inputStream) as Guy;
            }
            OnPropertyChanged("NewGuy");
            OnPropertyChanged("LatestGuyFile");
        }
Пример #40
0
        /// <summary>
        /// Reads the contents of the specified file and returns text.
        /// </summary>
        /// <param name="file">The file to read.</param>
        public static async Task<string> ReadTextAsync(IStorageFile file)
        {
            using (var fs = await file.OpenAsync(FileAccessMode.Read))
            {
                using (var inStream = fs.GetInputStreamAt(0))
                {
                    using (var reader = new DataReader(inStream))
                    {
                        await reader.LoadAsync((uint)fs.Size);
                        string data = reader.ReadString((uint)fs.Size);
                        reader.DetachStream();

                        return data;
                    }
                }
            }
        }
        /// <summary>
        /// Saves the given <see cref="WriteableBitmap" /> to a specified storage file.
        /// </summary>
        /// <param name="writeableBitmap">The writeable bitmap.</param>
        /// <param name="storageFile">The storage file.</param>
        public static async Task SaveToStorageFile(this WriteableBitmap writeableBitmap, IStorageFile storageFile)
        {
            using (var writestream = await storageFile.OpenAsync(FileAccessMode.ReadWrite))
            {
                var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, writestream);

                using (var pixelStream = writeableBitmap.PixelBuffer.AsStream())
                {
                    var pixels = new byte[pixelStream.Length];
                    await pixelStream.ReadAsync(pixels, 0, pixels.Length);

                    encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore,
                        (uint)writeableBitmap.PixelWidth, (uint)writeableBitmap.PixelHeight, 96.0, 96.0, pixels);

                    await encoder.FlushAsync();
                }
            }
        }
Пример #42
0
        /// <summary>
        /// Writes text to the specified file.
        /// </summary>
        /// <param name="file">The file that the text is written to.</param>
        /// <param name="contents">The text to write.</param>
        public static async Task WriteTextAsync(IStorageFile file, string contents)
        {
            using (var fs = await file.OpenAsync(FileAccessMode.ReadWrite))
            {
                using (var outStream = fs.GetOutputStreamAt(0))
                {
                    using (var dataWriter = new DataWriter(outStream))
                    {
                        if (contents != null)
                        {
                            dataWriter.WriteString(contents);
                        }

                        await dataWriter.StoreAsync();
                        dataWriter.DetachStream();
                    }

                    await outStream.FlushAsync();
                }
            }
        }
Пример #43
0
        internal static async Task ResizeAndSaveAs(IStorageFile source, IStorageFile destination, 
            int targetDimension)
        {
            // open the file...
            using(var sourceStream = await source.OpenReadAsync())
            {
                // step one, get a decoder...
                var decoder = await BitmapDecoder.CreateAsync(sourceStream);

                // step two, create somewhere to put it...
                using(var destinationStream = await destination.OpenAsync(FileAccessMode.ReadWrite))
                {
                    // step three, create an encoder...
                    var encoder = await BitmapEncoder.CreateForTranscodingAsync(destinationStream, decoder);

                    // how big is it?
                    uint width = decoder.PixelWidth;
                    uint height = decoder.PixelHeight;
                    decimal ratio = (decimal)width / (decimal)height;

                    // orientation?
                    bool portrait = width < height;

                    // step four, configure it...
                    if (portrait)
                    {
                        encoder.BitmapTransform.ScaledHeight = (uint)targetDimension;
                        encoder.BitmapTransform.ScaledWidth = (uint)((decimal)targetDimension * ratio);
                    }
                    else
                    {
                        encoder.BitmapTransform.ScaledWidth = (uint)targetDimension;
                        encoder.BitmapTransform.ScaledHeight = (uint)((decimal)targetDimension / ratio);
                    }

                    // step five, write it...
                    await encoder.FlushAsync();
                }
            }
        }
Пример #44
0
        public async void WriteGuyAsync(Guy guyToWrite)
        {
            IStorageFolder guysFolder =
                await KnownFolders.DocumentsLibrary.CreateFolderAsync("Guys",
                                                    CreationCollisionOption.OpenIfExists);
            latestGuyFile =
                    await guysFolder.CreateFileAsync(guyToWrite.Name + ".xml",
                                            CreationCollisionOption.ReplaceExisting);

            using (IRandomAccessStream stream =
                                await latestGuyFile.OpenAsync(FileAccessMode.ReadWrite))
            using (Stream outputStream = stream.AsStreamForWrite())
            {
                DataContractSerializer serializer = new DataContractSerializer(typeof(Guy));
                serializer.WriteObject(outputStream, guyToWrite);
            }

            Path = latestGuyFile.Path;

            OnPropertyChanged("Path");
            OnPropertyChanged("LatestGuyFile");
        }
        private async Task<Image> CreateImageFromStorageFileAsync(IStorageFile file)
        {
            var image = new Image();

            using (IRandomAccessStream fileStream = await file.OpenAsync(FileAccessMode.Read))
            {
                BitmapImage bitmapImage = new BitmapImage();
                await bitmapImage.SetSourceAsync(fileStream);
                image.Source = bitmapImage;
            }

            return image;
        }
Пример #46
0
        private static async Task<BitmapImage> LoadImage(IStorageFile file)
        {
            var bitmapImage = new BitmapImage();
            var stream = (FileRandomAccessStream)await file.OpenAsync(FileAccessMode.Read);

            bitmapImage.SetSource(stream);

            return bitmapImage;
        }
Пример #47
0
        /// <summary>
        ///     Checks if the current timetable image has the wrong dimensions.
        /// </summary>
        /// <param name="canvasHeight">Height of the <c>canvas</c></param>
        /// <param name="timetableFile">
        ///     <c>Timetable image</c>
        /// </param>
        /// <returns><c>True</c> if a new timetable needs to be downloaded; <c>False</c> if not.</returns>
        private static async Task<bool> CheckIfBadDimensions(double canvasHeight, IStorageFile timetableFile)
        {
            bool downloadNew = false;
            //Bitmap decoder to read width and height from PNG.
            BitmapDecoder bitmapDecoder = null;
            try
            {
                //Open the file async
                using (IRandomAccessStream stream = await timetableFile.OpenAsync(FileAccessMode.Read))
                {
                    bitmapDecoder = await BitmapDecoder.CreateAsync(stream);
                }
            }
                //Sometimes do not work, can't figure out what the problem is. This "catch" helps me avoid crashes.
            catch (Exception)
            {
                // ignored
            }

            if (bitmapDecoder != null)
            {
                //If the image does not have the same height as the canvas, then download new one
                if (bitmapDecoder.PixelHeight != canvasHeight)
                {
                    downloadNew = true;
                }
            }
            //if our Try Catch failed, then just download new image either way.
            else
            {
                downloadNew = true;
            }

            return downloadNew;
        }