/// <summary> /// 改变图片的大小 /// </summary> /// <param name="sourceStream">包含图片数据的流</param> /// <param name="expWidth">期望的宽度</param> /// <param name="expHeight">期望的高度</param> /// <returns></returns> public static async Task<IRandomAccessStream> ResizeImageHard(IRandomAccessStream sourceStream, uint expWidth,uint expHeight) { BitmapDecoder decoder = await BitmapDecoder.CreateAsync(sourceStream); uint height = decoder.PixelHeight; uint weight = decoder.PixelWidth; uint destHeight = height > expHeight ? expHeight : height; uint destWeight = weight> expWidth? expWidth : weight; BitmapTransform transform = new BitmapTransform() { ScaledWidth = destWeight, ScaledHeight = destHeight }; PixelDataProvider pixelData = await decoder.GetPixelDataAsync( BitmapPixelFormat.Rgba8, BitmapAlphaMode.Straight, transform, ExifOrientationMode.IgnoreExifOrientation, ColorManagementMode.DoNotColorManage); var tempfile = await ApplicationData.Current.LocalFolder.CreateFileAsync("temp.jpg", CreationCollisionOption.ReplaceExisting); IRandomAccessStream destStream = await tempfile.OpenAsync(FileAccessMode.ReadWrite); BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, destStream); encoder.SetPixelData(BitmapPixelFormat.Rgba8, BitmapAlphaMode.Straight, transform.ScaledWidth, transform.ScaledHeight, 100, 100, pixelData.DetachPixelData()); await encoder.FlushAsync(); //把流的位置变为0,这样才能从头读出图片流 destStream.Seek(0); return destStream; }
internal StoreFileStream(string path, string mode) { try { _stream = Task.Run(async () => { StorageFile file; if (mode.Equals("rw", StringComparison.OrdinalIgnoreCase)) { file = await StorageFile.CreateStreamedFileFromUriAsync(Path.GetFileName(path), new Uri(path), null); } else if (mode.Equals("r", StringComparison.OrdinalIgnoreCase)) { file = await StorageFile.GetFileFromPathAsync(path); } else { throw new ArgumentOutOfRangeException("mode", "Only modes r and rw are supported."); } return await file.OpenAsync(FileAccessMode.ReadWrite); }).Result; _disposed = false; Name = path; } catch { _stream = null; _disposed = true; Name = String.Empty; } }
/// <summary> /// Returns a Bitmap image for a give random access stream /// </summary> /// <param name="stream">Random access stream for which the bitmap needs to be generated</param> /// <return Type="BitmapImage">Bitmap for the given stream</return> static async public Task<BitmapImage> GetImageFromFile(IRandomAccessStream stream) { BitmapImage bmp = new BitmapImage(); await bmp.SetSourceAsync(stream); return bmp; }
public async Task LoadSurfaceAsync(ICanvasResourceCreator creator, IRandomAccessStream stream) { tempSurface = await CanvasBitmap.LoadAsync(creator, stream); bound = tempSurface.Bounds; center = tempSurface.Size.ToVector2() / 2; blur.Source = tempSurface; }
private async void Grid_Loaded(object sender, RoutedEventArgs e) { var camera = (await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture)).FirstOrDefault(); if (camera != null) { mediaCapture = new MediaCapture(); var settings = new MediaCaptureInitializationSettings() { VideoDeviceId = camera.Id }; await mediaCapture.InitializeAsync(settings); displayRequest.RequestActive(); VideoPreview.Source = mediaCapture; await mediaCapture.StartPreviewAsync(); memStream = new InMemoryRandomAccessStream(); MediaEncodingProfile mediaEncodingProfile = MediaEncodingProfile.CreateMp4(VideoEncodingQuality.Auto); await mediaCapture.StartRecordToStreamAsync(mediaEncodingProfile, memStream); } //video = await captureUI.CaptureFileAsync(CameraCaptureUIMode.Video); //if (video!=null) //{ // MediaClip mediaClip = await MediaClip.CreateFromFileAsync(video); // mediaComposition.Clips.Add(mediaClip); // mediaStreamSource = mediaComposition.GeneratePreviewMediaStreamSource(600, 600); // VideoPreview.SetMediaStreamSource(mediaStreamSource); //} //FFMPEGHelper.RTMPEncoder encoder = new FFMPEGHelper.RTMPEncoder(); //encoder.Initialize("rtmp://youtube.co"); }
/// <summary> /// Decrypts the specified input stream. /// </summary> /// <param name="input">The input stream.</param> /// <param name="masterKey">The master key.</param> /// <param name="masterSeed">The master seed.</param> /// <param name="encryptionIV">The encryption initialization vector.</param> /// <returns>The decrypted buffer.</returns> /// <exception cref="ArgumentNullException"> /// The <paramref name="input"/>, <paramref name="masterSeed"/>, <paramref name="masterKey"/> /// and <paramref name="encryptionIV"/> cannot be <c>null</c>. /// </exception> public static async Task<IInputStream> Decrypt(IRandomAccessStream input, IBuffer masterKey, IBuffer masterSeed, IBuffer encryptionIV) { if (input == null) throw new ArgumentNullException("input"); if (masterSeed == null) throw new ArgumentNullException("masterSeed"); if (masterKey == null) throw new ArgumentNullException("masterKey"); if (encryptionIV == null) throw new ArgumentNullException("encryptionIV"); var sha = HashAlgorithmProvider .OpenAlgorithm(HashAlgorithmNames.Sha256) .CreateHash(); sha.Append(masterSeed); sha.Append(masterKey); var seed = sha.GetValueAndReset(); var aes = SymmetricKeyAlgorithmProvider .OpenAlgorithm(SymmetricAlgorithmNames.AesCbcPkcs7) .CreateSymmetricKey(seed); var buffer = WindowsRuntimeBuffer.Create( (int)(input.Size - input.Position)); buffer = await input.ReadAsync(buffer, buffer.Capacity); buffer = CryptographicEngine.Decrypt(aes, buffer, encryptionIV); var stream = new InMemoryRandomAccessStream(); await stream.WriteAsync(buffer); stream.Seek(0); return stream; }
public void UpdateImage(IRandomAccessStream rass) { storage["Picture"] = new ParseFile("Picture.jpg", rass.AsStreamForRead()); this.RaisePropertyChanged("Picture"); }
public static async Task<IBuffer> ReadIntoBuffer(IRandomAccessStream stream) { stream.Seek(0); var buffer = new Buffer((uint) stream.Size); await stream.ReadAsync(buffer, buffer.Capacity, InputStreamOptions.None); return buffer; }
private async Task<byte[]> ImageToBytes(IRandomAccessStream sourceStream) { byte[] imageArray; BitmapDecoder decoder = await BitmapDecoder.CreateAsync(sourceStream); var transform = new BitmapTransform { ScaledWidth = decoder.PixelWidth, ScaledHeight = decoder.PixelHeight }; PixelDataProvider pixelData = await decoder.GetPixelDataAsync( BitmapPixelFormat.Rgba8, BitmapAlphaMode.Straight, transform, ExifOrientationMode.RespectExifOrientation, ColorManagementMode.DoNotColorManage); using (var destinationStream = new InMemoryRandomAccessStream()) { BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, destinationStream); encoder.SetPixelData(BitmapPixelFormat.Rgba8, BitmapAlphaMode.Premultiplied, decoder.PixelWidth, decoder.PixelHeight, 96, 96, pixelData.DetachPixelData()); await encoder.FlushAsync(); BitmapDecoder outputDecoder = await BitmapDecoder.CreateAsync(destinationStream); await destinationStream.FlushAsync(); imageArray = (await outputDecoder.GetPixelDataAsync()).DetachPixelData(); } return imageArray; }
/// <summary> /// Saves the file with fullFilePath, uses FileMode.Create, so file create time will be rewrited if needed /// If exception has occurred while writing the file, it will delete it /// </summary> /// <param name="fullFilePath">example: "\\image_cache\\213898adj0jd0asd</param> /// <param name="cacheStream">stream to write to the file</param> /// <returns>true if file was successfully written, false otherwise</returns> protected async virtual Task<bool> InternalSaveAsync(string fullFilePath, IRandomAccessStream cacheStream) { var storageFile = await SF.CreateFileAsync(fullFilePath, CreationCollisionOption.ReplaceExisting); using (IRandomAccessStream outputStream = await storageFile.OpenAsync(FileAccessMode.ReadWrite)) { try { await RandomAccessStream.CopyAsync( cacheStream.GetInputStreamAt(0L), outputStream.GetOutputStreamAt(0L)); return true; } catch { try { // If file was not saved normally, we should delete it await storageFile.DeleteAsync(); } catch { ImageLog.Log("[error] can not delete unsaved file: " + fullFilePath); } } } ImageLog.Log("[error] can not save cache to the: " + fullFilePath); return false; }
public async Task<IRandomAccessStream> GetThumbnailImage(IRandomAccessStream stream, int width, int height, bool smartCropping = true) { var response = await _client.GetThumbnailAsync(stream.AsStreamForRead(), width, height, smartCropping); var responseStream = new MemoryStream(response); return responseStream.AsRandomAccessStream(); }
//Creates RenderTargetBitmap from UI Element async Task<RenderTargetBitmap> CaptureToStreamAsync(FrameworkElement uielement, IRandomAccessStream stream, Guid encoderId) { try { var renderTargetBitmap = new RenderTargetBitmap(); await renderTargetBitmap.RenderAsync(uielement); var pixels = await renderTargetBitmap.GetPixelsAsync(); var logicalDpi = DisplayInformation.GetForCurrentView().LogicalDpi; var encoder = await BitmapEncoder.CreateAsync(encoderId, stream); encoder.SetPixelData( BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)renderTargetBitmap.PixelWidth, (uint)renderTargetBitmap.PixelHeight, logicalDpi, logicalDpi, /*pixels.ToArray()*/ null); await encoder.FlushAsync(); return renderTargetBitmap; } catch { } return null; }
public static async Task PlayStreamAsync(this MediaElement mediaElement, IRandomAccessStream stream, bool disposeStream = true) { // bool is irrelevant here, just using this to flag task completion. TaskCompletionSource<bool> taskCompleted = new TaskCompletionSource<bool>(); // Note that the MediaElement needs to be in the UI tree for events like MediaEnded to fire. RoutedEventHandler endOfPlayHandler = (s, e) => { if (disposeStream) stream.Dispose(); taskCompleted.SetResult(true); }; mediaElement.MediaEnded += endOfPlayHandler; mediaElement.SetSource(stream, (stream as SpeechSynthesisStream).ContentType); mediaElement.Volume = 1; mediaElement.IsMuted = false; mediaElement.Play(); await taskCompleted.Task; mediaElement.MediaEnded -= endOfPlayHandler; }
public async Task<ImageSource> InitializeAsync(CoreDispatcher dispatcher, IRandomAccessStream streamSource, CancellationTokenSource cancellationTokenSource) { byte[] bytes = new byte[streamSource.Size]; await streamSource.ReadAsync(bytes.AsBuffer(), (uint)streamSource.Size, InputStreamOptions.None).AsTask(cancellationTokenSource.Token); var imageSource = WebpCodec.Decode(bytes); return imageSource; }
public async Task ConverterBitmapToTargetStreamAsync(IRandomAccessStream bitmapSourceStream, IRandomAccessStream saveTargetStream) { BitmapDecoder decoder = await BitmapDecoder.CreateAsync(bitmapSourceStream); // Scale image to appropriate size BitmapTransform transform = new BitmapTransform() { //ScaledWidth = Convert.ToUInt32(bi.PixelWidth), //ScaledHeight = Convert.ToUInt32(bi.PixelHeight) }; PixelDataProvider pixelData = await decoder.GetPixelDataAsync( BitmapPixelFormat.Bgra8, // WriteableBitmap uses BGRA format BitmapAlphaMode.Straight, transform, ExifOrientationMode.RespectExifOrientation, // This sample ignores Exif orientation ColorManagementMode.DoNotColorManage); var BitmapEncoderGuid = BitmapEncoder.PngEncoderId; BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoderGuid, saveTargetStream); encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)decoder.PixelWidth, (uint)decoder.PixelHeight, 96.0, 96.0, pixelData.DetachPixelData()); await encoder.FlushAsync(); }
public static async Task<ImgurEntity> UploadImgur(IRandomAccessStream fileStream) { try { var imageData = new byte[fileStream.Size]; for (int i = 0; i < imageData.Length; i++) { imageData[i] = (byte)fileStream.AsStreamForRead().ReadByte(); } var theAuthClient = new HttpClient(); var request = new HttpRequestMessage(HttpMethod.Post, "https://api.imgur.com/3/image"); request.Headers.Authorization = new AuthenticationHeaderValue("Client-ID", "e5c018ac1f4c157"); var form = new MultipartFormDataContent(); var t = new StreamContent(fileStream.AsStream()); // TODO: See if this is the correct way to use imgur's v3 api. I can't see why we would still need to convert images to base64. string base64Img = Convert.ToBase64String(imageData); t.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg"); form.Add(new StringContent(base64Img), @"image"); form.Add(new StringContent("file"), "type"); request.Content = form; HttpResponseMessage response = await theAuthClient.SendAsync(request); string responseString = await response.Content.ReadAsStringAsync(); if (responseString == null) return null; var imgurEntity = JsonConvert.DeserializeObject<ImgurEntity>(responseString); return imgurEntity; } catch (WebException) { } catch (IOException) { return null; } return null; }
/// <summary> /// 改变图片大小 /// </summary> /// <param name="sourceStream">包含图片数据的数据流</param> /// <param name="scaleLong">如果图片长大于宽,那么此为改编后的长度,反之是改变后的高度</param> /// <returns></returns> public static async Task<IRandomAccessStream> ResizeImage(IRandomAccessStream sourceStream,uint scaleLong) { try { BitmapDecoder decoder = await BitmapDecoder.CreateAsync(sourceStream); uint height = decoder.PixelHeight; uint weight = decoder.PixelWidth; double rate; uint destHeight = height; uint destWeight = weight; if (weight > height) { rate = scaleLong / (double)weight; destHeight = weight > scaleLong ? (uint)(rate * height) : height; destWeight = scaleLong; } else { rate = scaleLong / (double)height; destWeight = height > scaleLong ? (uint)(rate * weight) : weight; destHeight = scaleLong; } BitmapTransform transform = new BitmapTransform() { ScaledWidth = destWeight, ScaledHeight = destHeight }; PixelDataProvider pixelData = await decoder.GetPixelDataAsync( BitmapPixelFormat.Rgba8, BitmapAlphaMode.Straight, transform, ExifOrientationMode.IgnoreExifOrientation, ColorManagementMode.DoNotColorManage); var folder = ApplicationData.Current.TemporaryFolder; var tempfile = await folder.CreateFileAsync("temp.jpg", CreationCollisionOption.GenerateUniqueName); IRandomAccessStream destStream = await tempfile.OpenAsync(FileAccessMode.ReadWrite); BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, destStream); encoder.SetPixelData(BitmapPixelFormat.Rgba8, BitmapAlphaMode.Straight, transform.ScaledWidth, transform.ScaledHeight, 100, 100, pixelData.DetachPixelData()); await encoder.FlushAsync(); //REMEMBER destStream.Seek(0); await tempfile.DeleteAsync(StorageDeleteOption.PermanentDelete); return destStream; } catch(Exception e) { var task = ExceptionHelper.WriteRecordAsync(e, nameof(BitmapHandleHelper), nameof(ResizeImage)); return null; } }
private static async Task<byte[]> ConvertIRandomAccessStreamByte(IRandomAccessStream stream) { DataReader read = new DataReader(stream.GetInputStreamAt(0)); await read.LoadAsync((uint)stream.Size); byte[] temp = new byte[stream.Size]; read.ReadBytes(temp); return temp; }
private async Task<DialogStepResult> ProcessResponseOnHowAreYouImage(IRandomAccessStream image) { var prevalentEmotion = await _emotionApi.GetPrevalentEmotion(image); if (prevalentEmotion != "Normal") return new DialogStepResult(String.Format("You are full of {0}. What's up?", prevalentEmotion.ToLower()), new DialogStep(ProcessResponseOnWhatsUp, DidntCatchResponse)); else return new DialogStepResult(")))", new DialogStep(FinalResponse, FinalResponse)); }
public static async Task<string> StorageImageFolder(IRandomAccessStream stream, string uri) { StorageFolder folder = await GetImageFolder(); string image = RenameByMD5(uri) + ".png"; StorageFile file = await folder.CreateFileAsync(image); await FileIO.WriteBytesAsync(file, await ConvertIRandomAccessStreamByte(stream)); return file.Name; }
public TorrentRandomAccessStream(TorrentStreamManager manager) { _manager = manager; _torrentFile = manager.TorrentVideoFile; _torrent = manager.Torrent; var stream = File.Open(Path.Combine(_torrentFile.TargetFolder.Path, _torrentFile.Path), FileMode.Open, FileAccess.Read, FileShare.ReadWrite); _internalStream = stream.AsRandomAccessStream(); }
private async Task LoadBitmap(IRandomAccessStream stream) { _writeableBitmap = new WriteableBitmap(1, 1); _writeableBitmap.SetSource(stream); _writeableBitmap.Invalidate(); await Dispatcher.RunAsync( Windows.UI.Core.CoreDispatcherPriority.Normal, () => ImageTarget.Source = _writeableBitmap); }
/// <summary> /// Decrypts the specified input stream. /// </summary> /// <param name="input">The input stream.</param> /// <param name="masterKey">The master key.</param> /// <param name="headers">The database file headers.</param> /// <returns>The decrypted buffer.</returns> /// <exception cref="ArgumentNullException"> /// The <paramref name="input"/>, <paramref name="masterKey"/>, /// <paramref name="headers"/> cannot be <c>null</c>. /// </exception> public static Task<IInputStream> Decrypt(IRandomAccessStream input, IBuffer masterKey, FileHeaders headers) { if (headers == null) throw new ArgumentNullException("headers"); return Decrypt(input, masterKey, headers.MasterSeed, headers.EncryptionIV); }
public static async Task<Stream> IRandomAccessStreamToStream(IRandomAccessStream irStream) { byte[] pixels = await IRandomAccessStreamToByteArr(irStream); Stream stream = new MemoryStream(pixels); return stream; }
/// <summary> /// Returns a byte array with the content of the stream. /// </summary> /// <param name="stream">stream to get bytes for</param> /// <returns>awaitable byte array</returns> public static async Task<byte[]> GetPhotoBits(IRandomAccessStream stream) { Debug.Assert(stream != null, "GetPhotoBits should not be called with a null stream."); var reader = new DataReader(stream.GetInputStreamAt(0)); var bytes = new byte[stream.Size]; await reader.LoadAsync((uint)stream.Size); reader.ReadBytes(bytes); return bytes; }
public async Task<string> Process(IRandomAccessStream image) { Check.Required<ArgumentNullException>(() => image != null); var result = await CurrentStep.Process(image); if (result.NextStep != null) CurrentStep = result.NextStep; return result.Response; }
private static async Task RenderElementAsync(FrameworkElement element, IRandomAccessStream stream, Guid encoderId, Size size) { var bitmap = new RenderTargetBitmap(); await bitmap.RenderAsync(element, (int)size.Width, (int)size.Height); var pixels = await bitmap.GetPixelsAsync(); var logicalDpi = DisplayInformation.GetForCurrentView().LogicalDpi; var encoder = await BitmapEncoder.CreateAsync(encoderId, stream); encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight, (uint)bitmap.PixelWidth, (uint)bitmap.PixelHeight, logicalDpi, logicalDpi, pixels.ToArray()); await encoder.FlushAsync(); }
public static async Task<byte[]> IRandomAccessStreamToByteArr(IRandomAccessStream irStream) { DataReader reader = new Windows.Storage.Streams.DataReader(irStream.GetInputStreamAt(0)); await reader.LoadAsync((uint)irStream.Size); byte[] pixels = new byte[irStream.Size]; reader.ReadBytes(pixels); return pixels; }
/// <summary> /// Pictures Libraryへファイルを保存する /// 既存の同名ファイルが存在している場合はファイルを上書きする /// </summary> /// <param name="fileName"></param> /// <param name="stream">エンコード済みの画像ストリーム</param> /// <returns></returns> public static async Task<StorageFile> SaveToPicturesLibraryAsync(string fileName, IRandomAccessStream stream) { var library = KnownFolders.PicturesLibrary; var file = await library.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting); using (var writeStrm = await file.OpenStreamForWriteAsync()) { var readStrm = stream.AsStreamForRead(); readStrm.CopyTo(writeStrm); } return file; }
private async Task SaveVideo(IRandomAccessStream videoStream) { StorageFile videoFile = await ApplicationData.Current.LocalFolder.CreateFileAsync("MyCam.mp4"); using (DataReader reader = new DataReader(videoStream.GetInputStreamAt(0))) { await reader.LoadAsync((uint)videoStream.Size); byte[] data = new byte[(int)videoStream.Size]; reader.ReadBytes(data); await FileIO.WriteBytesAsync(videoFile, data); } }
public static Stream AsStream(this IRandomAccessStream windowsRuntimeStream) { return(AsStreamInternal(windowsRuntimeStream, DefaultBufferSize, "AsStream", forceBufferSize: false)); }
public static Stream AsStream(this IRandomAccessStream windowsRuntimeStream, Int32 bufferSize) { return(AsStreamInternal(windowsRuntimeStream, bufferSize, "AsStream", forceBufferSize: true)); }
/// <summary> /// Uses provided options to generate a database file. /// </summary> protected override async Task HandleCredentialsAsync(string confirmedPassword, ITestableFile chosenKeyFile) { CancellationTokenSource cts = new CancellationTokenSource(); IKdbxWriter writer = this.writerFactory.Assemble( confirmedPassword, chosenKeyFile, Settings.Cipher, Settings.GetKdfParameters() ); IRandomNumberGenerator rng = writer.HeaderData.GenerateRng(); KdbxDocument newDocument = new KdbxDocument(new KdbxMetadata("PassKeep Database")); if (!CreateEmpty) { IList <IKeePassGroup> groups = new List <IKeePassGroup> { new KdbxGroup(newDocument.Root.DatabaseGroup), new KdbxGroup(newDocument.Root.DatabaseGroup), new KdbxGroup(newDocument.Root.DatabaseGroup), new KdbxGroup(newDocument.Root.DatabaseGroup), new KdbxGroup(newDocument.Root.DatabaseGroup), new KdbxGroup(newDocument.Root.DatabaseGroup) }; groups[0].Title.ClearValue = "General"; groups[1].Title.ClearValue = "Windows"; groups[2].Title.ClearValue = "Network"; groups[3].Title.ClearValue = "Internet"; groups[4].Title.ClearValue = "eMail"; groups[5].Title.ClearValue = "Homebanking"; groups[0].IconID = 48; groups[1].IconID = 38; groups[2].IconID = 3; groups[3].IconID = 1; groups[4].IconID = 19; groups[5].IconID = 37; foreach (IKeePassGroup group in groups) { newDocument.Root.DatabaseGroup.Children.Add(group); } IList <IKeePassEntry> entries = new List <IKeePassEntry> { new KdbxEntry(newDocument.Root.DatabaseGroup, rng, newDocument.Metadata), new KdbxEntry(newDocument.Root.DatabaseGroup, rng, newDocument.Metadata) }; entries[0].Title.ClearValue = "Sample Entry"; entries[1].Title.ClearValue = "Sample Entry #2"; entries[0].UserName.ClearValue = "User Name"; entries[1].UserName.ClearValue = "Michael321"; entries[0].Password.ClearValue = "Password"; entries[1].Password.ClearValue = "12345"; entries[0].Url.ClearValue = "http://keepass.info/"; entries[1].Url.ClearValue = "http://keepass.info/help/kb/testform.html"; entries[0].Notes.ClearValue = "Notes"; foreach (IKeePassEntry entry in entries) { newDocument.Root.DatabaseGroup.Children.Add(entry); } } using (IRandomAccessStream stream = await File.AsIStorageFile.OpenAsync(FileAccessMode.ReadWrite)) { Task <bool> writeTask = writer.WriteAsync(stream, newDocument, cts.Token); this.taskNotificationService.PushOperation(writeTask, cts, AsyncOperationType.DatabaseEncryption); if (await writeTask) { this.futureAccessList.Add(File, File.AsIStorageItem.Name); IDatabaseCandidate candidate = await this.candidateFactory.AssembleAsync(File); IDatabasePersistenceService persistenceService = new DefaultFilePersistenceService( writer, writer, candidate, this.syncContext, true); DocumentReady?.Invoke( this, new DocumentReadyEventArgs( newDocument, candidate, persistenceService, writer.HeaderData.GenerateRng(), this.keyChangeVmFactory ) ); } } }
/// <summary> /// This method exports the max possible view of the InfiniteCanvas drawings as offScreen drawings that can be converted to image. /// Max is calculated using CanvasDevice.MaximumBitmapSizeInPixels /// </summary> /// <param name="stream">The target stream.</param> /// <param name="bitmapFileFormat">the specified format.</param> /// <returns>Task</returns> public async Task SaveBitmapAsync(IRandomAccessStream stream, BitmapFileFormat bitmapFileFormat) { var offScreen = _drawingSurfaceRenderer.ExportMaxOffScreenDrawings(); await offScreen.SaveAsync(stream, MapToCanvasBitmapFileFormat(bitmapFileFormat)); }
protected override Task <TensorFloat> PreProcessAsync(IRandomAccessStream stream) => stream.GetAsDefaultImageNetNormalizedTensorFloat();
protected override void checkSupportInternal(CameraMetaData meta) { stream = mFile.BaseStream.AsRandomAccessStream(); }
/// <summary> /// Attempts to load KDBX header data from the provided data stream. /// </summary> /// <remarks> /// On success, the HeaderData property of this KdbxReader will be populated. /// On failure, it will be null. /// </remarks> /// <param name="stream">A stream representing a KDBX document (or header).</param> /// <param name="token">A token allowing the operation to be cancelled.</param> /// <returns>A Task representing the result of the read operation.</returns> public async Task <ReaderResult> ReadHeaderAsync(IRandomAccessStream stream, CancellationToken token) { HeaderData = null; using (DataReader reader = GetReaderForStream(stream)) { ReaderResult result = await ValidateSignature(reader); if (result != ReaderResult.Success) { reader.DetachStream(); return(result); } result = await ValidateVersion(reader); if (result != ReaderResult.Success) { reader.DetachStream(); return(result); } // If we get this far, we've passed basic sanity checks. // Construct a HeaderData entity and start reading fields. KdbxHeaderData headerData = new KdbxHeaderData(KdbxHeaderData.Mode.Read); bool gotEndOfHeader = false; while (!gotEndOfHeader) { if (token.IsCancellationRequested) { return(new ReaderResult(KdbxParserCode.OperationCancelled)); } try { OuterHeaderField field = await ReadOuterHeaderField(reader, headerData); if (field == OuterHeaderField.EndOfHeader) { gotEndOfHeader = true; } this.headerInitializationMap[field] = true; } catch (KdbxParseException e) { reader.DetachStream(); return(e.Error); } } // Ensure all headers are initialized bool gotAllHeaders = this.headerInitializationMap.All( kvp => this.headerInitializationMap[kvp.Key] ); if (!gotAllHeaders) { reader.DetachStream(); return(new ReaderResult(KdbxParserCode.HeaderMissing)); } // Hash entire header var sha256 = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Sha256); CryptographicHash hash = sha256.CreateHash(); ulong streamPos = stream.Position; stream.Seek(0); await reader.LoadAsync((uint)streamPos); headerData.FullHeader = reader.ReadBuffer((uint)streamPos); hash.Append(headerData.FullHeader); IBuffer plainHeaderHash = hash.GetValueAndReset(); if (this.parameters.UseXmlHeaderAuthentication) { // The header was parsed successfully - finish creating the object and return success headerData.HeaderHash = CryptographicBuffer.EncodeToBase64String(plainHeaderHash); headerData.Size = streamPos; } if (this.parameters.UseInlineHeaderAuthentication) { // In KDBX4, the header hash is written directly after the header fields. // After the unencrypted hash, an HMAC-SHA-256 hash of the header is written. await reader.LoadAsync(32); IBuffer existingPlainHash = reader.ReadBuffer(32); // Validate plaintext hash if (plainHeaderHash.Length != existingPlainHash.Length) { return(new ReaderResult(KdbxParserCode.BadHeaderHash)); } for (uint i = 0; i < plainHeaderHash.Length; i++) { if (plainHeaderHash.GetByte(i) != existingPlainHash.GetByte(i)) { return(new ReaderResult(KdbxParserCode.BadHeaderHash)); } } DebugHelper.Trace("Validated plaintext KDBX4 header hash"); } if (this.parameters.Version <= KdbxVersion.Three && headerData.KdfParameters == null) { // Need to manually populate KDF parameters for older versions headerData.KdfParameters = new AesParameters( headerData.TransformRounds, headerData.TransformSeed ); } HeaderData = headerData; reader.DetachStream(); return(ReaderResult.Success); } }
protected override Task <TensorFloat> PreProcessAsync(IRandomAccessStream stream) => stream.GetAsTensorFloat(224);
/// <summary> /// 读取wav文件 /// </summary> /// <param name="filename"></param> private async Task <wav> WaveAccess(string filename) { try { byte[] riff = new byte[4]; byte[] riffSize = new byte[4]; byte[] waveID = new byte[4]; byte[] junkID = new byte[4]; bool hasjunk = false; byte[] junklength = new byte[4]; byte[] fmtID = new byte[4]; byte[] cksize = new byte[4]; uint waveType = 0; byte[] channel = new byte[2]; byte[] sample_rate = new byte[4]; byte[] bytespersec = new byte[4]; byte[] blocklen_sample = new byte[2]; byte[] bitNum = new byte[2]; byte[] unknown = new byte[2]; byte[] dataID = new byte[4]; //52 byte[] dataLength = new byte[4]; //56 个字节 //string longFileName = filepath; //FileStream fstream = new FileStream(filename, FileMode.Open); //Windows.Storage.StorageFolder s = Windows.ApplicationModel.Package.Current.InstalledLocation; //FileStream fs; //StorageFolder storageFolder = Package.Current.InstalledLocation; //StorageFolder storageFolder = ApplicationData.Current.LocalFolder; //StorageFile storageFile = await storageFolder.GetFileAsync(filename); //IRandomAccessStream fileStream = await storageFile.OpenAsync(FileAccessMode.Read); //Stream s = fileStream.AsStream(); //Stream s = fs.ReadAsync StorageFolder storageFolder = ApplicationData.Current.LocalFolder; StorageFile storageFile = await storageFolder.GetFileAsync(filename); IRandomAccessStream fileStream = await storageFile.OpenAsync(FileAccessMode.Read); Stream s = fileStream.AsStream(); BinaryReader bread = new BinaryReader(s); //BinaryReader bread = new BinaryReader(fs); riff = bread.ReadBytes(4); // RIFF if (BitConverter.ToUInt32(bytesReserve(riff), 0) != 0x52494646) { Exception e = new Exception("该文件不是WAVE文件"); throw e; } riffSize = bread.ReadBytes(4); // 文件剩余长度 if (BitConverter.ToUInt32(riffSize, 0) != bread.BaseStream.Length - bread.BaseStream.Position) { //Exception e = new Exception("该WAVE文件损坏,文件长度与标记不一致"); //throw e; } waveID = bread.ReadBytes(4); if (BitConverter.ToUInt32(bytesReserve(waveID), 0) != 0x57415645) { Exception e = new Exception("该文件不是WAVE文件"); throw e; } byte[] tmp = bread.ReadBytes(4); if (BitConverter.ToUInt32(bytesReserve(tmp), 0) == 0x4A554E4B) { //包含junk标记的wav junkID = tmp; hasjunk = true; junklength = bread.ReadBytes(4); uint junklen = BitConverter.ToUInt32(junklength, 0); //将不要的junk部分读出 bread.ReadBytes((int)junklen); //读fmt 标记 fmtID = bread.ReadBytes(4); } else if (BitConverter.ToUInt32(bytesReserve(tmp), 0) == 0x666D7420) { fmtID = tmp; } else { Exception e = new Exception("无法找到WAVE文件的junk和fmt标记"); throw e; } if (BitConverter.ToUInt32(bytesReserve(fmtID), 0) != 0x666D7420) { //fmt 标记 Exception e = new Exception("无法找到WAVE文件fmt标记"); throw e; } cksize = bread.ReadBytes(4); uint p_data_start = BitConverter.ToUInt32(cksize, 0); int p_wav_start = (int)p_data_start + 8; waveType = bread.ReadUInt16(); if (waveType != 1) { // 非pcm格式,暂不支持 Exception e = new Exception("WAVE文件不是pcm格式,暂时不支持"); throw e; } //声道数 channel = bread.ReadBytes(2); //采样频率 sample_rate = bread.ReadBytes(4); int fs = (int)BitConverter.ToUInt32(sample_rate, 0); //每秒钟字节数 bytespersec = bread.ReadBytes(4); //每次采样的字节大小,2为单声道,4为立体声道 blocklen_sample = bread.ReadBytes(2); //每个声道的采样精度,默认16bit bitNum = bread.ReadBytes(2); tmp = bread.ReadBytes(2); //寻找da标记 while (BitConverter.ToUInt16(bytesReserve(tmp), 0) != 0x6461) { tmp = bread.ReadBytes(2); } tmp = bread.ReadBytes(2); if (BitConverter.ToUInt16(bytesReserve(tmp), 0) != 0x7461) { //ta标记 Exception e = new Exception("无法找到WAVE文件data标记"); throw e; } //wav数据byte长度 uint DataSize = bread.ReadUInt32(); //计算样本数 long NumSamples = (long)DataSize / 2; if (NumSamples == 0) { NumSamples = (bread.BaseStream.Length - bread.BaseStream.Position) / 2; } //if (BitConverter.ToUInt32(notDefinition, 0) == 18) //{ // unknown = bread.ReadBytes(2); //} //dataID = bread.ReadBytes(4); Int16[] data = new Int16[NumSamples]; for (int i = 0; i < NumSamples; i++) { //读入2字节有符号整数 data[i] = bread.ReadInt16(); } s.Dispose(); //fstream.Close(); //fstream.Dispose(); bread.Dispose(); wav wave = new wav(); wave.wavs = data; wave.fs = fs; return(wave); } catch (System.Exception ex) { //return null; throw ex; } }
private async void DropArea_Drop(object sender, DragEventArgs e) { if (e.DataView.Contains(StandardDataFormats.StorageItems)) { MainColorText.Text = "Loading..."; var items = await e.DataView.GetStorageItemsAsync(); //文件过滤,防止他们往里面拖 excel // items = items.OfType<StorageFile>().Where(s => s.FileType.Equals(".jpg")).ToList() as IReadOnlyList<IStorageItem>; //items = items.OfType<StorageFile>().Where(s => s.FileType.Equals(".png")).ToList() as IReadOnlyList<IStorageItem>; //细化一下文件类型,然后对于非法类型做一下提示 if (items.Count == 0) { MainColorText.Text = "Please drag a JPG file in this panel."; } if (items.Count > 0) { var storageFile = items[0] as StorageFile; //设置图片路径 ImageBrush imageBrush = new ImageBrush(); BitmapImage bitmap = new BitmapImage(); await bitmap.SetSourceAsync(await storageFile.OpenAsync(FileAccessMode.Read)); imageBrush.ImageSource = bitmap; PriImagePath.Fill = imageBrush; PriImagePath2.Fill = imageBrush; TempPanelImg.Fill = imageBrush; TempPanelImg.Visibility = Visibility.Visible; MainColorText.Text = "Calculating..."; //获取主色调 ColorAbouts colorAbouts = new ColorAbouts(); FileAbouts fileAbouts = new FileAbouts(); ColorMatch colorMatch = new ColorMatch(); StorageFile file2 = await fileAbouts.GetPanelPic(TempPanel); string comColor = await colorAbouts.GetPicMainColor(file2, StatisticsGrid); string mainColor = "#" + comColor.Substring(3, 6); TempPanelImg.Visibility = Visibility.Collapsed; //颜色匹配&设置边框 int minNub = colorMatch.CompareDist(mainColor); TriditionalColor triditionalColors = new TriditionalColor(); TridColor[] tridColors = new TridColor[630]; tridColors = triditionalColors.InitTriditionalColors(); ColorNameTextblock.Text = tridColors[minNub].Name; SolidColorBrush triColor = colorAbouts.GetSolidColorBrush(tridColors[minNub].Hex); ColorBorder.BorderBrush = triColor; MainColorGrid.Background = triColor; //设置时间戳 TimeTurn timestamp = new TimeTurn(); string atime = await timestamp.GetImageProperties(storageFile); TimestampTextBlock.Text = atime; //test TempPanelImg.Visibility = Visibility.Visible; WriteableBitmap wb2 = new WriteableBitmap(1000, 600); string mainColorHex2 = "#000000"; if (file2 != null) { // Set the source of the WriteableBitmap to the image stream using (IRandomAccessStream fileStream2 = await file2.OpenAsync(FileAccessMode.Read)) { try { await wb2.SetSourceAsync(fileStream2); System.IO.File.Delete(file2.Path); } catch (TaskCanceledException) { // The async action to set the WriteableBitmap's source may be canceled if the user clicks the button repeatedly } } mainColorHex2 = ColorMatch.GetMajorColor2(wb2).ToString(); string mainColor2 = "#" + mainColorHex2.Substring(3, 6); //DisplayText.Text = mainColor2; TimestampTextBlock.Foreground = colorAbouts.GetSolidColorBrush(colorAbouts.InvertColor2(mainColor2)); //设置天数 TextHelper textHelper = new TextHelper(); DaysTextblock.Text = textHelper.CalculateDays().ToString(); //设置节气 LunarHolDayTextBlock.Text = TextHelper.GetLunarHolDay(DateTime.Now); //设置表情 RanTextBlock.Text = textHelper.RandomEmoji(); //弥散阴影 MainColorText.Text = "Almost Done..."; WriteableBitmap wb = new WriteableBitmap(1600, 1600); StorageFile file = await fileAbouts.GetPanelPic(PicPanel); if (file != null) { // Set the source of the WriteableBitmap to the image stream using (IRandomAccessStream fileStream = await file.OpenAsync(FileAccessMode.Read)) { try { await wb.SetSourceAsync(fileStream); } catch (TaskCanceledException) { // The async action to set the WriteableBitmap's source may be canceled if the user clicks the button repeatedly } } //高斯模糊 BlurEffect be = new BlurEffect(wb); ShadowImg.Source = await be.ApplyFilter(22);//高斯模糊等级可以自己定义 System.IO.File.Delete(file.Path); } MainColorText.Text = "Done!"; } } } }
public NonSeekableRandomAccessStreamForWrite(Stream stream) { this.stream = stream; this.oStream = stream.AsOutputStream(); this.imrac = new InMemoryRandomAccessStream(); }
async void OnLoaded(object sender, RoutedEventArgs args) { // Get fonts from DirectXWrapper library WriteFactory writeFactory = new WriteFactory(); WriteFontCollection writeFontCollection = writeFactory.GetSystemFontCollection(); int count = writeFontCollection.GetFontFamilyCount(); string[] fonts = new string[count]; for (int i = 0; i < count; i++) { WriteFontFamily writeFontFamily = writeFontCollection.GetFontFamily(i); WriteLocalizedStrings writeLocalizedStrings = writeFontFamily.GetFamilyNames(); int index; if (writeLocalizedStrings.FindLocaleName("en-us", out index)) { fonts[i] = writeLocalizedStrings.GetString(index); } else { fonts[i] = writeLocalizedStrings.GetString(0); } } Array.Sort <string>(fonts); fontFamilyComboBox.ItemsSource = fonts; // Load current document StorageFolder localFolder = ApplicationData.Current.LocalFolder; try { StorageFile storageFile = await localFolder.CreateFileAsync("RichTextEditor.rtf", CreationCollisionOption.OpenIfExists); IRandomAccessStream stream = await storageFile.OpenAsync(FileAccessMode.Read); richEditBox.Document.LoadFromStream(TextSetOptions.FormatRtf, stream); } catch { // Ignore exceptions here } // Load selection settings IPropertySet propertySet = ApplicationData.Current.LocalSettings.Values; if (propertySet.ContainsKey("SelectionStart")) { richEditBox.Document.Selection.StartPosition = (int)propertySet["SelectionStart"]; } if (propertySet.ContainsKey("SelectionEnd")) { richEditBox.Document.Selection.EndPosition = (int)propertySet["SelectionEnd"]; } }
private static async Task CropImageWithShapeAsync(WriteableBitmap writeableBitmap, IRandomAccessStream stream, Rect croppedRect, BitmapFileFormat bitmapFileFormat, CropShape cropShape) { var device = CanvasDevice.GetSharedDevice(); var clipGeometry = CreateClipGeometry(device, cropShape, new Size(croppedRect.Width, croppedRect.Height)); if (clipGeometry == null) { return; } CanvasBitmap sourceBitmap = null; using (var randomAccessStream = new InMemoryRandomAccessStream()) { await CropImageAsync(writeableBitmap, randomAccessStream, croppedRect, bitmapFileFormat); sourceBitmap = await CanvasBitmap.LoadAsync(device, randomAccessStream); } using (var offScreen = new CanvasRenderTarget(device, (float)croppedRect.Width, (float)croppedRect.Height, 96f)) { using (var drawingSession = offScreen.CreateDrawingSession()) using (var markCommandList = new CanvasCommandList(device)) { using (var markDrawingSession = markCommandList.CreateDrawingSession()) { markDrawingSession.FillGeometry(clipGeometry, Colors.Black); } var alphaMaskEffect = new AlphaMaskEffect { Source = sourceBitmap, AlphaMask = markCommandList }; drawingSession.DrawImage(alphaMaskEffect); alphaMaskEffect.Dispose(); } clipGeometry.Dispose(); sourceBitmap.Dispose(); var pixelBytes = offScreen.GetPixelBytes(); var bitmapEncoder = await BitmapEncoder.CreateAsync(GetEncoderId(bitmapFileFormat), stream); bitmapEncoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied, offScreen.SizeInPixels.Width, offScreen.SizeInPixels.Height, 96.0, 96.0, pixelBytes); await bitmapEncoder.FlushAsync(); } }
/// <summary> /// Loads the object from a file using a specific formatting. /// </summary> /// <param name="fileStream">File stream of the file that contains the serialized data of this object.</param> /// <param name="mode"><see cref="SerializationMode"/> to use.</param> /// <returns>Deserialized instance of the object. If the deserialization fails, <c>null</c> is returned.</returns> /// <remarks> /// When enableRedirects is enabled, loading will take more time. Only set /// the parameter to <c>true</c> when the deserialization without redirects fails. /// </remarks> public static T Load(IRandomAccessStream fileStream, SerializationMode mode) { return(Load <T>((Stream)fileStream, mode, null)); }
/// <summary> /// Saves the object to an isolated storage file stream using the default formatting. /// </summary> /// <param name="fileStream">Stream that will contain the serialized data of this object.</param> public void Save(IRandomAccessStream fileStream) { Save((Stream)fileStream, null); }
/// <summary> /// Gets the image data from a Uri, with Caching. /// </summary> /// <param name="uri">Image Uri</param> /// <returns>Image Stream</returns> public async Task <IRandomAccessStream> GetImageStream(Uri uri) { async Task <Stream> CopyStream(HttpContent source) { var stream = new MemoryStream(); await source.CopyToAsync(stream); stream.Seek(0, SeekOrigin.Begin); return(stream); } IRandomAccessStream imageStream = null; var localPath = $"{uri.Host}/{uri.LocalPath}".Replace("//", "/"); if (localPath.StartsWith(_docsOnlineRoot.Substring(8))) { // If we're looking for docs we should look in our local area first. localPath = localPath.Substring(_docsOnlineRoot.Length - 3); // want to chop "live/" but missing https:// as well. } // Try cache only in Release (using remote docs) #if REMOTE_DOCS try { imageStream = await StreamHelper.GetLocalCacheFileStreamAsync(localPath, Windows.Storage.FileAccessMode.Read); } catch { } if (imageStream == null) { try { // Our docs don't reference any external images, this should only be for getting latest image from repo. using (var response = await client.GetAsync(uri)) { if (response.IsSuccessStatusCode) { var imageCopy = await CopyStream(response.Content); imageStream = imageCopy.AsRandomAccessStream(); // Takes a second copy of the image stream, so that is can save the image data to cache. using (var saveStream = await CopyStream(response.Content)) { await SaveImageToCache(localPath, saveStream); } } } } catch { } } // If we don't have internet, then try to see if we have a packaged copy if (imageStream == null) { try { imageStream = await StreamHelper.GetPackagedFileStreamAsync(localPath); } catch { } } #endif return(imageStream); }
public StreamDataSource(IRandomAccessStream stream) { this.stream = stream; }
/// <summary> /// Load the family and their notes from local storage /// </summary> /// <returns>Null if there was no model to load, otherwise, the deserialized model</returns> private async Task <Model> LoadModelAsync() { Model model = null; InkStrokeContainer combinedStrokes = new InkStrokeContainer(); // To avoid managing individual files for every InkCanvas, we will combine all ink stroke information into one container List <int> InkStrokesPerCanvas = new List <int>(); try { StorageFile modelDataFile = await ApplicationData.Current.LocalFolder.GetFileAsync(NOTES_MODEL_FILE); using (IRandomAccessStream randomAccessStream = await modelDataFile.OpenAsync(FileAccessMode.ReadWrite)) { // Load the model which contains the people and the note collection try { DataContractJsonSerializer modelSerializer = new DataContractJsonSerializer(typeof(Model)); model = (Model)modelSerializer.ReadObject(randomAccessStream.AsStream()); } catch (System.Runtime.Serialization.SerializationException) { System.Diagnostics.Debug.Assert(false, "Failed to load serialized model"); return(null); } } // For each sticky note, load the number of inkstrokes it contains StorageFile inkDataFile = await ApplicationData.Current.LocalFolder.GetFileAsync(NOTES_INK_FILE); using (IInputStream inkStream = await inkDataFile.OpenSequentialReadAsync()) { bool combinedStrokesExist = false; DataReader reader = new DataReader(inkStream); foreach (StickyNote n in model.StickyNotes) { await reader.LoadAsync(sizeof(int)); // You need to buffer the data before you can read from a DataReader. int numberOfInkStrokes = reader.ReadInt32(); InkStrokesPerCanvas.Add(numberOfInkStrokes); combinedStrokesExist |= numberOfInkStrokes > 0; } // Load the ink data if (combinedStrokesExist) { await combinedStrokes.LoadAsync(inkStream); } } // using inkStream } // try catch (FileNotFoundException) { // No data to load. We'll start with a fresh model return(null); } // Factor out the inkstrokes from the big container into each note int allStrokesIndex = 0, noteIndex = 0; IReadOnlyList <InkStroke> allStrokes = combinedStrokes.GetStrokes(); foreach (StickyNote n in model.StickyNotes) { // InkStrokeContainers can't be serialized using the default xml/json serialization. // So create a new one and fill it up from the data we restored n.Ink = new InkStrokeContainer(); // pull out the ink strokes that belong to this note for (int i = 0; i < InkStrokesPerCanvas[noteIndex]; i++) { n.Ink.AddStroke(allStrokes[allStrokesIndex++].Clone()); } ++noteIndex; } return(model); }
/// <summary> /// Encodes the data from a WriteableBitmap as JPEG into a stream. /// </summary> /// <param name="bmp">The WriteableBitmap.</param> /// <param name="destinationStream">The stream which will take the JPEG image data.</param> public static async Task ToStreamAsJpeg(this WriteableBitmap bmp, IRandomAccessStream destinationStream) { await ToStream(bmp, destinationStream, BitmapEncoder.JpegEncoderId); }
public static Task <WriteableBitmap> FromStream(this WriteableBitmap bmp, IRandomAccessStream stream, BitmapPixelFormat pixelFormat = BitmapPixelFormat.Unknown) { return(BitmapFactory.FromStream(stream, pixelFormat)); }
public async void ContinueFileOpenPicker(FileOpenPickerContinuationEventArgs args) { //Import data if ((args.ContinuationData["Operation"] as string) == "UpdateDatabase" && args.Files != null && args.Files.Count > 0) { StorageFile file = args.Files[0]; if (file.Name.EndsWith("poyo")) { IRandomAccessStream fileStream = await file.OpenAsync(FileAccessMode.Read); DataManager.ConnectToDatabase(); List <Lesson> lessons; int kanjiRound; int vocabRound; String importStatus = DataManager.ImportFromFile(fileStream.AsStream(), out lessons, out vocabRound, out kanjiRound); if (MessageBox.Show(importStatus, "Import", MessageBoxButton.OKCancel) == MessageBoxResult.OK) { String updateStatus = DataManager.UpdateDatabase(lessons); AppSettings.VocabRound = vocabRound; AppSettings.KanjiRound = kanjiRound; AppSettings.SaveSettings(); MessageBox.Show(updateStatus); } else { MessageBox.Show("Import Abgebrochen"); } DataManager.CloseConnection(); fileStream.Dispose(); } } //Add New Content else if ((args.ContinuationData["Operation"] as string) == "AddContent" && args.Files != null && args.Files.Count > 0) { StorageFile file = args.Files[0]; if (file.Name.EndsWith("nya")) { IRandomAccessStream fileStream = await file.OpenAsync(FileAccessMode.Read); DataManager.ConnectToDatabase(); String updateStatus = DataManager.AddContentFromFile(fileStream.AsStream()); DataManager.CloseConnection(); fileStream.Dispose(); MessageBox.Show(updateStatus); } } updateDatabase = false; }
/// <summary> /// Attempts to asynchronously persist the document to its default location. /// If a save is already in progress, it is cancelled and the more recent save should /// override it. /// </summary> /// <param name="document">The KdbxDocument to persist.</param> /// <returns>A Task representing whether the save was successful.</returns> public async Task <bool> Save(KdbxDocument document) { if (document == null) { throw new ArgumentNullException(nameof(document)); } if (!CanSave) { return(false); } // Lock to avoid a race condition between checking not null and cancelling bool firePropertyChanged = false; lock (this.ctsLock) { if (IsSaving) { this.currentSaveCts.Cancel(); } else { // We only fire PropertyChanged for false -> true if the // transition is actually happening. If we are pre-empting // a save in progress, then it is not useful to fire the // event. firePropertyChanged = true; } this.pendingRequests++; } // Cancelling above may cause a previous save to wrap up faster, but we do still need // to wait for it to wrap up. await this.saveSemaphore.WaitAsync(); // Inside the semaphore it is impossible for a save to already be in progress. // This is because we clean up the current save at the end of the semaphore, so if // we just entered it, there is no pending operation. // However, we still want to lock around the CTS in case another save starts right // away and needs to cancel this one. lock (this.ctsLock) { DebugHelper.Assert(this.currentSaveCts == null); this.pendingRequests--; if (this.pendingRequests == 0) { // If pendingRequests > 0, then at least one more recent call to // Save is currently stalled at the semaphore. // We only kick off this save if that's NOT true. this.currentSaveCts = new CancellationTokenSource(); } } // Only proceed with this save attempt if there are no pending requests... // otherwise this block is skipped and we immediately release the semaphore // and return false. bool writeResult = false; if (this.currentSaveCts != null) { if (firePropertyChanged) { #pragma warning disable CS4014 // No need to await this to continue saving. this.syncContext.Post(() => OnPropertyChanged(nameof(IsSaving))); #pragma warning restore CS4014 } // Do the write to a temporary file until it's finished successfully. StorageFile outputFile = await GetTemporaryFile(); using (IRandomAccessStream fileStream = await outputFile.OpenAsync(FileAccessMode.ReadWrite)) { using (IOutputStream outputStream = fileStream.GetOutputStreamAt(0)) { writeResult = await this.fileWriter.WriteAsync(fileStream, document, this.currentSaveCts.Token); } } if (writeResult) { Task replaceTask = this.defaultSaveFile.ReplaceWithAsync(outputFile); try { await replaceTask; } catch (Exception) { } } try { // Make a good-faith effort to delete the temp file, due // to reports that Windows might not handle this automatically. await outputFile.DeleteAsync(); } catch (Exception e) { DebugHelper.Trace($"Caught exception during temp file cleanup: {e}"); } // At this point we are done with all file IO - clean up and let any // pending saves do their thing. firePropertyChanged = false; lock (this.ctsLock) { this.currentSaveCts.Dispose(); this.currentSaveCts = null; if (this.pendingRequests == 0) { firePropertyChanged = true; } } // We only update IsSaving if nothing else is pending - if another save // is already queued, it's just going to flip this back to true immediately. if (firePropertyChanged) { #pragma warning disable CS4014 // No need to await this to continue saving. this.syncContext.Post(() => OnPropertyChanged(nameof(IsSaving))); #pragma warning restore CS4014 } } this.saveSemaphore.Release(); return(writeResult); }
/// <summary> /// Asynchronously attempts to unlock the document file. /// </summary> /// <remarks> /// Algorithm is as of this writing (11/5/2012): /// 0. Use UTF8 encoding with no BOM. /// 1. Read header. /// 2. Compute SHA256 hash of header. /// 3. Decrypt the rest of the viewModel using header parameters. /// Relies on: /// a. MasterSeed.Length == 32 /// Write masterseed to stream /// b. GenerateKey32(_transformSeed, KeyEncryptionRounds) /// Create raw32 (CreateRawCompositeKey32) /// Concatenate all data and Sha256 /// TransformKey(raw32, _transformSeed, numRounds) /// Init Rijndael: /// 128 bit (16 byte) blocks /// ECB mode /// k = _transformSeed /// For numRounds: /// Transform in place raw32[0:15] /// Transform in place raw32[16:31] /// c. Write 32 bytes of Key32 to stream /// d. aesKey = Sha256 the stream /// e. DecryptStream with aesKey and _encryptionIV /// 4. Verify the first 32 bytes of the decrypted viewModel match up with /// "StreamStartBytes" from the header. /// 5. Read from the decrypted viewModel as a "HashedBlockStream" /// /// File format at the time of this writing (11/5/2012): /// /// 4 bytes: SIG1 /// 4 bytes: SIG2 /// Failure to match these constants results in a parse Result. /// /// 4 bytes: File version /// /// Header fields: /// 1 byte: Field ID /// 2 bytes: Field size (n) /// n bytes: Data /// </remarks> /// <param name="stream">An IRandomAccessStream containing the document to unlock (including the header).</param> /// <param name="rawKey">The aggregate raw key to use for decrypting the database.</param> /// <param name="token">A token allowing the parse to be cancelled.</param> /// <returns>A Task representing the result of the descryiption operation.</returns> public async Task <KdbxDecryptionResult> DecryptFile(IRandomAccessStream stream, IBuffer rawKey, CancellationToken token) { if (HeaderData == null) { throw new InvalidOperationException("Cannot decrypt database before ReadHeader has been called."); } // Init a SHA256 hash buffer and append the master seed to it HashAlgorithmProvider sha256 = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Sha256); CryptographicHash hash = sha256.CreateHash(); hash.Append(HeaderData.MasterSeed); this.rawKey = rawKey; this.logger.LogEvent("KdbxReader.GotRawKey", EventVerbosity.Verbose); // Transform the key (this can take a while) IBuffer transformedKey; try { IKdfEngine kdf = HeaderData.KdfParameters.CreateEngine(); LoggingFields fields = new LoggingFields(); fields.AddString("KdfEngine", kdf.GetType().Name); this.logger.LogEvent("KdbxReader.StartingKeyTransform", fields, EventVerbosity.Info); transformedKey = await HeaderData.KdfParameters.CreateEngine().TransformKeyAsync(rawKey, token) .ConfigureAwait(false); if (transformedKey == null) { throw new OperationCanceledException(); } this.logger.LogEvent("KdbxReader.KeyTransformSucceeded", EventVerbosity.Info); } catch (OperationCanceledException) { return(new KdbxDecryptionResult(new ReaderResult(KdbxParserCode.OperationCancelled))); } // In KDBX4, after the header is an HMAC-SHA-256 value computed over the header // allowing validation of header integrity. IBuffer hmacKey = HmacBlockHandler.DeriveHmacKey(transformedKey, HeaderData.MasterSeed); HmacBlockHandler hmacHandler = new HmacBlockHandler(hmacKey); IBuffer expectedMac = null; if (this.parameters.UseInlineHeaderAuthentication) { var algorithm = MacAlgorithmProvider.OpenAlgorithm(MacAlgorithmNames.HmacSha256); CryptographicHash hmacHash = algorithm.CreateHash(hmacHandler.GetKeyForBlock(UInt64.MaxValue)); DebugHelper.Assert(HeaderData.FullHeader != null); hmacHash.Append(HeaderData.FullHeader); expectedMac = hmacHash.GetValueAndReset(); } // Hash transformed k (with the master seed) to get final cipher k hash.Append(transformedKey); IBuffer cipherKey = hash.GetValueAndReset(); this.logger.LogEvent("KdbxReader.GotFinalCipherKey", EventVerbosity.Info); // Decrypt the document starting from the end of the header ulong headerLength = HeaderData.FullHeader.Length; if (this.parameters.UseInlineHeaderAuthentication) { // KDBX4 has a hash at the end of the header headerLength += 32; } stream.Seek(headerLength); if (expectedMac != null) { using (DataReader macReader = GetReaderForStream(stream)) { await macReader.LoadAsync(expectedMac.Length); IBuffer actualMac = macReader.ReadBuffer(expectedMac.Length); for (uint i = 0; i < expectedMac.Length; i++) { if (expectedMac.GetByte(i) != actualMac.GetByte(i)) { this.logger.LogEvent("KdbxReader.HmacFailure", EventVerbosity.Critical); return(new KdbxDecryptionResult(new ReaderResult(KdbxParserCode.CouldNotDecrypt))); } } macReader.DetachStream(); } } IBuffer cipherText; try { cipherText = await GetCipherText(stream, hmacHandler); } catch (FormatException ex) { this.logger.LogEvent("KdbxReader.DataIntegrityFailure", ex.ToLoggingFields(), EventVerbosity.Critical); return(new KdbxDecryptionResult(new ReaderResult(KdbxParserCode.DataIntegrityProblem, ex))); } IBuffer decryptedFile = DecryptDatabaseData(cipherText, cipherKey); if (decryptedFile == null) { this.logger.LogEvent("KdbxReader.DecryptionFailure", EventVerbosity.Critical); return(new KdbxDecryptionResult(new ReaderResult(KdbxParserCode.CouldNotDecrypt))); } this.logger.LogEvent("KdbxReader.DecryptionSucceeded", EventVerbosity.Info); // Verify first 32 bytes of the clear data; if StreamStartBytes wasn't set // (e.g. due to KDBX4), nothing happens here. for (uint i = 0; i < (HeaderData.StreamStartBytes?.Length ?? 0); i++) { byte actualByte = decryptedFile.GetByte(i); byte expectedByte = HeaderData.StreamStartBytes.GetByte(i); if (actualByte != expectedByte) { this.logger.LogEvent("KdbxReader.PlaintextValidationFailure", EventVerbosity.Critical); return(new KdbxDecryptionResult(new ReaderResult(KdbxParserCode.FirstBytesMismatch))); } } this.logger.LogEvent("KdbxReader.PlaintextValidationSucceeded", EventVerbosity.Verbose); IBuffer plainText = await UnhashAndInflate(decryptedFile); if (plainText == null) { return(new KdbxDecryptionResult(new ReaderResult(KdbxParserCode.CouldNotInflate))); } // Update HeaderData with info from the inner header, if relevant if (this.parameters.UseInnerHeader) { using (IRandomAccessStream plainTextStream = plainText.AsStream().AsRandomAccessStream()) { using (DataReader reader = GetReaderForStream(plainTextStream)) { ReaderResult innerHeaderResult = await ReadInnerHeader(reader, HeaderData); if (innerHeaderResult != ReaderResult.Success) { LoggingFields fields = new LoggingFields(); fields.AddInt32("Code", (int)innerHeaderResult.Code); this.logger.LogEvent("KdbxReader.InnerHeaderReadFailure", fields, EventVerbosity.Critical); return(new KdbxDecryptionResult(innerHeaderResult)); } // Update plainText to point to the remainder of the buffer uint bytesRemaining = plainText.Length - (uint)plainTextStream.Position; await reader.LoadAsync(bytesRemaining); plainText = reader.ReadBuffer(bytesRemaining); } } } XDocument finalTree = null; try { finalTree = XDocument.Load(plainText.AsStream()); } catch (XmlException) { return(null); } if (finalTree == null) { return(new KdbxDecryptionResult(new ReaderResult(KdbxParserCode.MalformedXml))); } try { KdbxDocument parsedDocument = await Task.Run(() => new KdbxDocument(finalTree.Root, HeaderData.ProtectedBinaries, HeaderData.GenerateRng(), this.parameters)); // Validate the final parsed header hash before returning if (this.parameters.UseXmlHeaderAuthentication && !String.IsNullOrEmpty(parsedDocument.Metadata.HeaderHash) && parsedDocument.Metadata.HeaderHash != HeaderData.HeaderHash) { return(new KdbxDecryptionResult(new ReaderResult(KdbxParserCode.BadHeaderHash))); } return(new KdbxDecryptionResult(this.parameters, parsedDocument, this.rawKey)); } catch (KdbxParseException e) { return(new KdbxDecryptionResult(e.Error)); } }
private async Task Initialize(FileSystemStorageFile PdfFile) { LoadingControl.IsLoading = true; PdfCollection = new ObservableCollection <BitmapImage>(); LoadQueue = new Queue <int>(); ExitLocker = new ManualResetEvent(false); Cancellation = new CancellationTokenSource(); Flip.ItemsSource = PdfCollection; MaxLoad = 0; LastPageIndex = 0; try { using (IRandomAccessStream PdfStream = await PdfFile.GetRandomAccessStreamFromFileAsync(FileAccessMode.Read).ConfigureAwait(true)) { try { Pdf = await PdfDocument.LoadFromStreamAsync(PdfStream); } catch (Exception) { PdfPasswordDialog Dialog = new PdfPasswordDialog(); if ((await Dialog.ShowAsync().ConfigureAwait(true)) == ContentDialogResult.Primary) { Pdf = await PdfDocument.LoadFromStreamAsync(PdfStream, Dialog.Password); } else { Frame.GoBack(); return; } } } for (uint i = 0; i < 10 && i < Pdf.PageCount && !Cancellation.IsCancellationRequested; i++) { using (PdfPage Page = Pdf.GetPage(i)) using (InMemoryRandomAccessStream PageStream = new InMemoryRandomAccessStream()) { await Page.RenderToStreamAsync(PageStream); BitmapImage DisplayImage = new BitmapImage(); PdfCollection.Add(DisplayImage); await DisplayImage.SetSourceAsync(PageStream); } } } catch (Exception) { QueueContentDialog Dialog = new QueueContentDialog { Title = Globalization.GetString("Common_Dialog_ErrorTitle"), Content = Globalization.GetString("QueueDialog_PDFOpenFailure"), CloseButtonText = Globalization.GetString("Common_Dialog_GoBack") }; _ = await Dialog.ShowAsync().ConfigureAwait(true); Frame.GoBack(); } finally { ExitLocker.Set(); if (!Cancellation.IsCancellationRequested) { Flip.SelectionChanged += Flip_SelectionChanged; Flip.SelectionChanged += Flip_SelectionChanged1; } await Task.Delay(1000).ConfigureAwait(true); LoadingControl.IsLoading = false; } }
/// <summary> /// 获取所有快速启动项 /// </summary> /// <returns></returns> public async Task <List <KeyValuePair <QuickStartType, QuickStartItem> > > GetQuickStartItemAsync() { List <Tuple <string, string, string> > ErrorList = new List <Tuple <string, string, string> >(); List <KeyValuePair <QuickStartType, QuickStartItem> > Result = new List <KeyValuePair <QuickStartType, QuickStartItem> >(); using (SqliteCommand Command = new SqliteCommand("Select * From QuickStart", Connection)) using (SqliteDataReader Reader = await Command.ExecuteReaderAsync().ConfigureAwait(true)) { while (Reader.Read()) { try { if (Convert.ToString(Reader[1]).StartsWith("ms-appx")) { StorageFile BitmapFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri(Reader[1].ToString())); BitmapImage Bitmap = new BitmapImage(); using (IRandomAccessStream Stream = await BitmapFile.OpenAsync(FileAccessMode.Read)) { await Bitmap.SetSourceAsync(Stream); } if ((QuickStartType)Enum.Parse(typeof(QuickStartType), Reader[3].ToString()) == QuickStartType.Application) { Result.Add(new KeyValuePair <QuickStartType, QuickStartItem>(QuickStartType.Application, new QuickStartItem(Bitmap, Convert.ToString(Reader[2]), QuickStartType.Application, Reader[1].ToString(), Reader[0].ToString()))); } else { Result.Add(new KeyValuePair <QuickStartType, QuickStartItem>(QuickStartType.WebSite, new QuickStartItem(Bitmap, Convert.ToString(Reader[2]), QuickStartType.WebSite, Reader[1].ToString(), Reader[0].ToString()))); } } else { StorageFile ImageFile = await StorageFile.GetFileFromPathAsync(Path.Combine(ApplicationData.Current.LocalFolder.Path, Convert.ToString(Reader[1]))); using (IRandomAccessStream Stream = await ImageFile.OpenAsync(FileAccessMode.Read)) { BitmapImage Bitmap = new BitmapImage(); await Bitmap.SetSourceAsync(Stream); if ((QuickStartType)Enum.Parse(typeof(QuickStartType), Reader[3].ToString()) == QuickStartType.Application) { Result.Add(new KeyValuePair <QuickStartType, QuickStartItem>(QuickStartType.Application, new QuickStartItem(Bitmap, Convert.ToString(Reader[2]), QuickStartType.Application, Reader[1].ToString(), Reader[0].ToString()))); } else { Result.Add(new KeyValuePair <QuickStartType, QuickStartItem>(QuickStartType.WebSite, new QuickStartItem(Bitmap, Convert.ToString(Reader[2]), QuickStartType.WebSite, Reader[1].ToString(), Reader[0].ToString()))); } } } } catch (Exception) { ErrorList.Add(new Tuple <string, string, string>(Convert.ToString(Reader[0]), Convert.ToString(Reader[1]), Convert.ToString(Reader[3]))); } } } foreach (var ErrorItem in ErrorList) { using (SqliteCommand Command = new SqliteCommand("Delete From QuickStart Where Name = @Name And FullPath = @FullPath And Type=@Type", Connection)) { Command.Parameters.AddWithValue("@Name", ErrorItem.Item1); Command.Parameters.AddWithValue("@FullPath", ErrorItem.Item2); Command.Parameters.AddWithValue("@Type", ErrorItem.Item3); await Command.ExecuteNonQueryAsync().ConfigureAwait(true); } } return(Result); }
private async void ExportImage() { // We haven't enabled image export for phone. var qualifiers = Windows.ApplicationModel.Resources.Core.ResourceContext.GetForCurrentView().QualifierValues; if (qualifiers.ContainsKey("DeviceFamily") && qualifiers["DeviceFamily"] == "Mobile") { ContentDialog notSupportedDialog = new ContentDialog { Title = "Export is not enabled", Content = "Image export is not enabled on phones.", CloseButtonText = "OK", }; ContentDialogResult result = await notSupportedDialog.ShowAsync(); return; } // Not on phone, so export image. CanvasDevice device = CanvasDevice.GetSharedDevice(); using (CanvasRenderTarget offscreen = new CanvasRenderTarget( device, item.ImageProperties.Width, item.ImageProperties.Height, 96)) { using (IRandomAccessStream stream = await item.ImageFile.OpenReadAsync()) using (CanvasBitmap image = await CanvasBitmap.LoadAsync(offscreen, stream, 96)) { ImageEffectsBrush.SetSource(image); using (CanvasDrawingSession ds = offscreen.CreateDrawingSession()) { ds.Clear(Windows.UI.Colors.Black); var img = ImageEffectsBrush.Image; ds.DrawImage(img); } var fileSavePicker = new FileSavePicker() { SuggestedStartLocation = PickerLocationId.PicturesLibrary, SuggestedSaveFile = item.ImageFile }; fileSavePicker.FileTypeChoices.Add("JPEG files", new List <string>() { ".jpg" }); var outputFile = await fileSavePicker.PickSaveFileAsync(); if (outputFile != null) { using (IRandomAccessStream outStream = await outputFile.OpenAsync(FileAccessMode.ReadWrite)) { await offscreen.SaveAsync(outStream, CanvasBitmapFileFormat.Jpeg); } // Check whether this save is overwriting the original image. // If it is, replace it in the list. Otherwise, insert it as a copy. bool replace = false; if (outputFile.IsEqual(item.ImageFile)) { replace = true; } try { await LoadSavedImageAsync(outputFile, replace); } catch (Exception ex) { if (ex.Message.Contains("0x80070323")) { // The handle with which this oplock was associated has been closed. // The oplock is now broken. (Exception from HRESULT: 0x80070323) // This is a temporary condition, so just try again. await LoadSavedImageAsync(outputFile, replace); } } } } } }
/// <summary> /// Performs all necessary actions (including SystemMediaTransportControls related) of loading a new media item /// in the app for playback. /// </summary> /// <param name="newItemIndex">index in playlist of new item to load for playback, can be out of range.</param> /// <remarks> /// If the newItemIndex argument is out of range, it will be adjusted accordingly to stay in range. /// </remarks> private async Task SetNewMediaItem(int newItemIndex) { // enable Next button unless we're on last item of the playlist if (newItemIndex >= playlist.Count - 1) { systemMediaControls.IsNextEnabled = false; newItemIndex = playlist.Count - 1; } else { systemMediaControls.IsNextEnabled = true; } // enable Previous button unless we're on first item of the playlist if (newItemIndex <= 0) { systemMediaControls.IsPreviousEnabled = false; newItemIndex = 0; } else { systemMediaControls.IsPreviousEnabled = true; } // note that the Play, Pause and Stop buttons were already enabled via SetupSystemMediaTransportControls() // invoked during this scenario page's OnNavigateToHandler() currentItemIndex = newItemIndex; StorageFile mediaFile = playlist[newItemIndex]; IRandomAccessStream stream = null; try { stream = await mediaFile.OpenAsync(FileAccessMode.Read); } catch (Exception e) { // User may have navigated away from this scenario page to another scenario page // before the async operation completed. if (isThisPageActive) { // If the file can't be opened, for this sample we will behave similar to the case of // setting a corrupted/invalid media file stream on the MediaElement (which triggers a // MediaFailed event). We abort any ongoing playback by nulling the MediaElement's // source. The user must press Next or Previous to move to a different media item, // or use the file picker to load a new set of files to play. MyMediaElement.Source = null; string errorMessage = String.Format(@"Cannot open {0} [""{1}""]." + "\nPress Next or Previous to continue, or select new files to play.", mediaFile.Name, e.Message.Trim()); rootPage.NotifyUser(errorMessage, NotifyType.ErrorMessage); } } // User may have navigated away from this scenario page to another scenario page // before the async operation completed. Check to make sure page is still active. if (!isThisPageActive) { return; } if (stream != null) { // We're about to change the MediaElement's source media, so put ourselves into a // "changing media" state. We stay in that state until the new media is playing, // loaded (if user has currently paused or stopped playback), or failed to load. // At those points we will call OnChangingMediaEnded(). MyMediaElement.SetSource(stream, mediaFile.ContentType); } try { // Updates the system UI for media transport controls to display metadata information // reflecting the file we are playing (eg. track title, album art/video thumbnail, etc.) // We call this even if the mediaFile can't be opened; in that case the method can still // update the system UI to remove any metadata information previously displayed. await UpdateSystemMediaControlsDisplayAsync(mediaFile); } catch (Exception e) { // Check isThisPageActive as user may have navigated away from this scenario page to // another scenario page before the async operations completed. if (isThisPageActive) { rootPage.NotifyUser(e.Message, NotifyType.ErrorMessage); } } }
private void NewImageEditor(IRandomAccessStream stream) { imgeditor.Image = stream as FileRandomAccessStream; frontPage.Visibility = Visibility.Collapsed; imageEditorPage.Visibility = Visibility.Visible; imgeditor.SetToolbarItemVisibility("text, save,redo,undo,reset,path,shape,transform", false); banner = new FooterToolbarItem() { Text = "Banner Types", SubItems = new System.Collections.ObjectModel.ObservableCollection <Syncfusion.UI.Xaml.ImageEditor.ToolbarItem>() { new Syncfusion.UI.Xaml.ImageEditor.ToolbarItem() { Text = "Facebook Post" }, new Syncfusion.UI.Xaml.ImageEditor.ToolbarItem() { Text = "Facebook Cover" }, new Syncfusion.UI.Xaml.ImageEditor.ToolbarItem() { Text = "Twitter Cover" }, new Syncfusion.UI.Xaml.ImageEditor.ToolbarItem() { Text = "Twitter Post" }, new Syncfusion.UI.Xaml.ImageEditor.ToolbarItem() { Text = "YouTubeChannel Cover" }, }, }; item1 = new CustomHeader(); item = new FooterToolbarItem(); imgeditor.ToolbarSettings.ToolbarItems.Add(banner); item1.HeaderName = "Share"; BitmapImage bitmap = new BitmapImage(new Uri("ms-appx:/Image/View/Assets/share.png")); item1.Icon = bitmap; item1.IconHeight = 15; imgeditor.ToolbarSettings.ToolbarItems.Add(item); imgeditor.ToolbarSettings.ToolbarItems.Add(item1); imgeditor.ToolbarSettings.ToolbarItemSelected += (sender, e) => { cancelToolBar.Visibility = Visibility.Collapsed; if (e.ToolbarItem is CustomHeader) { if ((e.ToolbarItem as CustomHeader).HeaderName == "Share") { Share(); } } if (e.ToolbarItem is Syncfusion.UI.Xaml.ImageEditor.ToolbarItem) { var toolitem = e.ToolbarItem as UI.Xaml.ImageEditor.ToolbarItem; if (cancelToolBar.Visibility == Visibility.Visible && toolitem.Text == "Banner Types") { imgeditor.ToggleCropping(); } cancelToolBar.Visibility = Visibility.Collapsed; if (toolitem is HeaderToolbarItem) { var item2 = toolitem as HeaderToolbarItem; if (item2.Text == "Banner Types" && item1.Text == "Share") { cancelToolBar.Visibility = Visibility.Collapsed; } } else if (toolitem.Text != "Banner Types") { cancelToolBar.Visibility = Visibility.Visible; } if (toolitem.Text == "Facebook Post") { imgeditor.ToggleCropping(1200, 900); } else if (toolitem.Text == "Facebook Cover") { imgeditor.ToggleCropping(851, 315); } else if (toolitem.Text == "Twitter Cover") { imgeditor.ToggleCropping(1500, 500); } else if (toolitem.Text == "Twitter Post") { imgeditor.ToggleCropping(1024, 512); } else if (toolitem.Text == "YouTubeChannel Cover") { imgeditor.ToggleCropping(2560, 1440); } } }; }
public static async Task CropandScaleAsync(StorageFile source, StorageFile dest, Point startPoint, Size size, double m_scaleFactor) { uint startPointX = (uint)Math.Floor(startPoint.X); uint startPointY = (uint)Math.Floor(startPoint.Y); uint height = (uint)Math.Floor(size.Height); uint width = (uint)Math.Floor(size.Width); using (IRandomAccessStream sourceStream = await source.OpenReadAsync(), destStream = await dest.OpenAsync(FileAccessMode.ReadWrite)) { BitmapDecoder decoder = await BitmapDecoder.CreateAsync(sourceStream); var m_displayHeightNonScaled = decoder.OrientedPixelHeight; var m_displayWidthNonScaled = decoder.OrientedPixelWidth; // Use the native (no orientation applied) image dimensions because we want to handle // orientation ourselves. BitmapTransform transform = new BitmapTransform(); BitmapBounds bounds = new BitmapBounds(); bounds.X = (uint)(startPointX * m_scaleFactor); bounds.Y = (uint)(startPointY * m_scaleFactor); bounds.Height = (uint)(height * m_scaleFactor); bounds.Width = (uint)(width * m_scaleFactor); transform.Bounds = bounds; // Scaling occurs before flip/rotation, therefore use the original dimensions // (no orientation applied) as parameters for scaling. transform.ScaledHeight = (uint)(decoder.PixelHeight * m_scaleFactor); transform.ScaledWidth = (uint)(decoder.PixelWidth * m_scaleFactor); transform.Rotation = BitmapRotation.None; // Fant is a relatively high quality interpolation mode. transform.InterpolationMode = BitmapInterpolationMode.Fant; BitmapPixelFormat format = decoder.BitmapPixelFormat; BitmapAlphaMode alpha = decoder.BitmapAlphaMode; // Set the encoder's destination to the temporary, in-memory stream. PixelDataProvider pixelProvider = await decoder.GetPixelDataAsync( format, alpha, transform, ExifOrientationMode.IgnoreExifOrientation, ColorManagementMode.ColorManageToSRgb ); byte[] pixels = pixelProvider.DetachPixelData(); Guid encoderID = Guid.Empty; switch (dest.FileType.ToLower()) { case ".png": encoderID = BitmapEncoder.PngEncoderId; break; case ".bmp": encoderID = BitmapEncoder.BmpEncoderId; break; default: encoderID = BitmapEncoder.JpegEncoderId; break; } // Write the pixel data onto the encoder. Note that we can't simply use the // BitmapTransform.ScaledWidth and ScaledHeight members as the user may have // requested a rotation (which is applied after scaling). var encoder = await BitmapEncoder.CreateAsync(encoderID, destStream); encoder.SetPixelData( format, alpha, (bounds.Width), (bounds.Height), decoder.DpiX, decoder.DpiY, pixels ); await encoder.FlushAsync(); } }
/// <summary> /// Return cover saved in file tags or .jpg from folder. /// If cover doesn't exist width and height are 0px. /// </summary> public async Task <BitmapImage> GetOriginalCover(string path, bool small) { BitmapImage bitmap = new BitmapImage(); if (small) { bitmap.DecodePixelHeight = 192; } int a = 0; try { StorageFile file = await StorageFile.GetFileFromPathAsync(path); Stream fileStream = await file.OpenStreamForReadAsync(); File tagFile = TagLib.File.Create(new StreamFileAbstraction(file.Name, fileStream, fileStream)); a = tagFile.Tag.Pictures.Length; fileStream.Dispose(); if (a > 0) { IPicture pic = tagFile.Tag.Pictures[0]; using (MemoryStream stream = new MemoryStream(pic.Data.Data)) { using (Windows.Storage.Streams.IRandomAccessStream istream = stream.AsRandomAccessStream()) { await bitmap.SetSourceAsync(istream); } } } else { StorageFolder folder = await StorageFolder.GetFolderFromPathAsync(Path.GetDirectoryName(path)); try { IReadOnlyList <StorageFile> files = await folder.GetFilesAsync(); if (files.Count > 0) { foreach (var x in files) { if (x.Path.EndsWith("jpg")) { using (IRandomAccessStream stream = await x.OpenAsync(Windows.Storage.FileAccessMode.Read)) { await bitmap.SetSourceAsync(stream); } } } } } catch (Exception e) { } } } catch (Exception e) { } return(bitmap); }