public static async Task <UwpSoftwareBitmap> ConvertFrom(BitmapFrame sourceBitmap) { // BitmapFrameをBMP形式のバイト配列に変換 byte[] bitmapBytes; var encoder = new BmpBitmapEncoder(); // .NET用のエンコーダーを使う encoder.Frames.Add(sourceBitmap); using (var memoryStream = new MemoryStream()) { encoder.Save(memoryStream); bitmapBytes = memoryStream.ToArray(); } // バイト配列をUWPのIRandomAccessStreamに変換 using (var randomAccessStream = new UwpInMemoryRandomAccessStream()) { using (var outputStream = randomAccessStream.GetOutputStreamAt(0)) using (var writer = new UwpDataWriter(outputStream)) { writer.WriteBytes(bitmapBytes); await writer.StoreAsync(); await outputStream.FlushAsync(); } // IRandomAccessStreamをSoftwareBitmapに変換 // (UWP APIのデコーダー) var decoder = await UwpBitmapDecoder.CreateAsync(randomAccessStream); var softwareBitmap = await decoder.GetSoftwareBitmapAsync(UwpBitmapPixelFormat.Bgra8, UwpBitmapAlphaMode.Premultiplied); return(softwareBitmap); } }
private async Task <int> SaveSubTask(double rate, string filePath, uint i) { using (Windows.Data.Pdf.PdfPage page = PdfDocument.GetPage((uint)i)) { //指定されたdpiを元にレンダーサイズ指定、四捨五入 double h = page.Size.Height; var options = new Windows.Data.Pdf.PdfPageRenderOptions(); options.DestinationHeight = (uint)Math.Round(h * rate, MidpointRounding.AwayFromZero); using (var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream()) { await page.RenderToStreamAsync(stream, options); BitmapImage image = new BitmapImage(); image.BeginInit(); image.CacheOption = BitmapCacheOption.OnLoad; image.StreamSource = stream.AsStream(); image.EndInit(); JpegBitmapEncoder encoder = new JpegBitmapEncoder(); encoder.QualityLevel = 85; encoder.Frames.Add(BitmapFrame.Create(image)); using (var fileStream = new FileStream(filePath + "_" + i + ".jpg", FileMode.Create, FileAccess.Write)) { encoder.Save(fileStream); } } } return((int)i); }
private async void _baseWebView_ScriptNotify(object sender, NotifyEventArgs e) { try { var bmp = new BitmapImage(); var base64 = e.Value.Substring(e.Value.IndexOf(",") + 1); var imageBytes = Convert.FromBase64String(base64); #if WINDOWS_APP || WINDOWS_PHONE_APP using (var ms = new Windows.Storage.Streams.InMemoryRandomAccessStream()) { using (var writer = new Windows.Storage.Streams.DataWriter(ms.GetOutputStreamAt(0))) { writer.WriteBytes(imageBytes); await writer.StoreAsync(); } bmp.SetSource(ms); } #elif WINDOWS_PHONE using (var ms = new System.IO.MemoryStream(imageBytes)) { ms.Position = 0; bmp.SetSource(ms); } #endif imageBytes = null; _img.Source = bmp; _img.Visibility = Visibility.Visible; } catch { } }
/// <summary> /// This is the click handler for the 'Copy Strings' button. Here we will parse the /// strings contained in the ElementsToWrite text block, write them to a stream using /// DataWriter, retrieve them using DataReader, and output the results in the /// ElementsRead text block. /// </summary> /// <param name="sender">Contains information about the button that fired the event.</param> /// <param name="e">Contains state information and event data associated with a routed event.</param> private async void TransferData(object sender, RoutedEventArgs e) { // Initialize the in-memory stream where data will be stored. using (var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream()) { // Create the data writer object backed by the in-memory stream. using (var dataWriter = new Windows.Storage.Streams.DataWriter(stream)) { dataWriter.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8; dataWriter.ByteOrder = Windows.Storage.Streams.ByteOrder.LittleEndian; // Write each element separately. foreach (string inputElement in inputElements) { uint inputElementSize = dataWriter.MeasureString(inputElement); dataWriter.WriteUInt32(inputElementSize); dataWriter.WriteString(inputElement); } // Send the contents of the writer to the backing stream. await dataWriter.StoreAsync(); // For the in-memory stream implementation we are using, the flushAsync call is superfluous, // but other types of streams may require it. await dataWriter.FlushAsync(); // In order to prolong the lifetime of the stream, detach it from the DataWriter so that it // will not be closed when Dispose() is called on dataWriter. Were we to fail to detach the // stream, the call to dataWriter.Dispose() would close the underlying stream, preventing // its subsequent use by the DataReader below. dataWriter.DetachStream(); } // Create the input stream at position 0 so that the stream can be read from the beginning. stream.Seek(0); using (var dataReader = new Windows.Storage.Streams.DataReader(stream)) { // The encoding and byte order need to match the settings of the writer we previously used. dataReader.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8; dataReader.ByteOrder = Windows.Storage.Streams.ByteOrder.LittleEndian; // Once we have written the contents successfully we load the stream. await dataReader.LoadAsync((uint)stream.Size); var receivedStrings = ""; // Keep reading until we consume the complete stream. while (dataReader.UnconsumedBufferLength > 0) { // Note that the call to readString requires a length of "code units" to read. This // is the reason each string is preceded by its length when "on the wire". uint bytesToRead = dataReader.ReadUInt32(); receivedStrings += dataReader.ReadString(bytesToRead) + "\n"; } // Populate the ElementsRead text block with the items we read from the stream. ElementsRead.Text = receivedStrings; } } }
public static async Task <string> GetFullTextFromImage(Image img) { try { StringBuilder b = new StringBuilder(); using (var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream()) { img.Save(stream.AsStream(), System.Drawing.Imaging.ImageFormat.Bmp); //These steps to get to a SoftwareBitmap are aweful! Windows.Graphics.Imaging.BitmapDecoder decoder = await Windows.Graphics.Imaging.BitmapDecoder.CreateAsync(stream); SoftwareBitmap bitmap = await decoder.GetSoftwareBitmapAsync(); OcrResult ocrResult = await _ocrEngine.RecognizeAsync(bitmap); for (int i = 0; i < ocrResult.Lines.Count; i++) { b.Append(ocrResult.Lines[i].Text); b.Append(" "); } } return(b.ToString()); }catch (Exception ex) { Logger.Error(ex.ToString()); } return(string.Empty); }
/// <summary> /// This is the click handler for the 'Copy Strings' button. Here we will parse the /// strings contained in the ElementsToWrite text block, write them to a stream using /// DataWriter, retrieve them using DataReader, and output the results in the /// ElementsRead text block. /// </summary> /// <param name="sender">Contains information about the button that fired the event.</param> /// <param name="e">Contains state information and event data associated with a routed event.</param> private async void TransferData(object sender, RoutedEventArgs e) { // Initialize the in-memory stream where data will be stored. using (var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream()) { // Create the data writer object backed by the in-memory stream. using (var dataWriter = new Windows.Storage.Streams.DataWriter(stream)) { dataWriter.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8; dataWriter.ByteOrder = Windows.Storage.Streams.ByteOrder.LittleEndian; // Write each element separately. foreach (string inputElement in inputElements) { uint inputElementSize = dataWriter.MeasureString(inputElement); dataWriter.WriteUInt32(inputElementSize); dataWriter.WriteString(inputElement); } // Send the contents of the writer to the backing stream. await dataWriter.StoreAsync(); // For the in-memory stream implementation we are using, the flushAsync call is superfluous, // but other types of streams may require it. await dataWriter.FlushAsync(); // In order to prolong the lifetime of the stream, detach it from the DataWriter so that it // will not be closed when Dispose() is called on dataWriter. Were we to fail to detach the // stream, the call to dataWriter.Dispose() would close the underlying stream, preventing // its subsequent use by the DataReader below. dataWriter.DetachStream(); } // Create the input stream at position 0 so that the stream can be read from the beginning. stream.Seek(0); using (var dataReader = new Windows.Storage.Streams.DataReader(stream)) { // The encoding and byte order need to match the settings of the writer we previously used. dataReader.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8; dataReader.ByteOrder = Windows.Storage.Streams.ByteOrder.LittleEndian; // Once we have written the contents successfully we load the stream. await dataReader.LoadAsync((uint)stream.Size); var receivedStrings = ""; // Keep reading until we consume the complete stream. while (dataReader.UnconsumedBufferLength > 0) { // Note that the call to readString requires a length of "code units" to read. This // is the reason each string is preceded by its length when "on the wire". uint bytesToRead = dataReader.ReadUInt32(); receivedStrings += dataReader.ReadString(bytesToRead) + "\n"; } // Populate the ElementsRead text block with the items we read from the stream. ElementsRead.Text = receivedStrings; } } }
private async Task <WriteableBitmap> GetMathCapture() { using (Windows.Storage.Streams.InMemoryRandomAccessStream rs = new Windows.Storage.Streams.InMemoryRandomAccessStream()) { if (MathView.DefaultBackgroundColor.A == 0x00) { await MathView.InvokeScriptAsync("ChangeColor", new string[] { CURRENT_FGCOLOR.ToCssRGBA(), Colors.White.ToCssRGBA() }); } await MathView.CapturePreviewToStreamAsync(rs); await rs.FlushAsync(); var wb = await rs.ToWriteableBitmap(); if (wb is WriteableBitmap) { wb = wb.Crop(2); } if (MathView.DefaultBackgroundColor.A == 0x00) { await MathView.InvokeScriptAsync("ChangeColor", new string[] { CURRENT_FGCOLOR.ToCssRGBA(), CURRENT_BGCOLOR.ToCssRGBA() }); } return(wb); } }
private async Task Save5(PdfDocument pdfDocument, ZipArchive archive, int keta, int quality, double dpi) { for (int i = 0; i < MyPdfDocument.PageCount; i++) { int renban = i + 1; string jpegName = MyPdfName + "_" + renban.ToString("d" + keta) + ".jpg"; using (PdfPage page = pdfDocument.GetPage((uint)i)) { var options = new PdfPageRenderOptions(); options.DestinationHeight = (uint)Math.Round(page.Size.Height * (dpi / 96.0), MidpointRounding.AwayFromZero); using (var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream()) { await page.RenderToStreamAsync(stream, options);//画像に変換したのはstreamへ JpegBitmapEncoder encoder = new JpegBitmapEncoder(); encoder.QualityLevel = quality; encoder.Frames.Add(BitmapFrame.Create(stream.AsStream())); var entry = archive.CreateEntry(jpegName); //open using (var entryStream = entry.Open()) { using (var jpegStream = new MemoryStream()) { encoder.Save(jpegStream); jpegStream.Position = 0; jpegStream.CopyTo(entryStream); } } } } } }
private async Task <List <BitmapImage> > Test2() { var streams = new List <Windows.Storage.Streams.InMemoryRandomAccessStream>(); var images = new List <BitmapImage>(); for (uint i = 0; i < MyPdfDocument.PageCount; i++) { using (var neko = MyPdfDocument.GetPage(i)) { using (var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream()) { await neko.RenderToStreamAsync(stream); streams.Add(stream); var img = new BitmapImage(); img.BeginInit(); img.CacheOption = BitmapCacheOption.OnLoad; img.StreamSource = stream.AsStream(); img.EndInit(); images.Add(img); } } } return(images); }
/// <summary> /// jpeg画像で保存 /// </summary> private async Task SaveSub2_1(int pageIndex, int keta, bool isJpeg) { var encoder = MakeEncoder(isJpeg); using (PdfPage page = MyPdfDocument.GetPage((uint)pageIndex)) { string ext = isJpeg ? ".jpg" : ".png"; //指定されたdpiを元に画像サイズ指定、四捨五入 var options = new PdfPageRenderOptions(); options.DestinationHeight = (uint)Math.Round(page.Size.Height * (MyDpi / 96.0), MidpointRounding.AwayFromZero); using (var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream()) { await page.RenderToStreamAsync(stream, options);//画像に変換したのはstreamへ //streamから直接BitmapFrameを作成することができた encoder.Frames.Add(BitmapFrame.Create(stream.AsStream())); //連番ファイル名を作成して保存 pageIndex++; string renban = pageIndex.ToString("d" + keta); using (var fileStream = new FileStream( System.IO.Path.Combine(MyPdfDirectory, MyPdfName) + "_" + renban + ext, FileMode.Create, FileAccess.Write)) { encoder.Save(fileStream); } } } }
private async void DisplayImage(int pageIndex, double dpi) { if (MyPdfDocument == null) { return; } MyDpi = dpi; using (Windows.Data.Pdf.PdfPage page = MyPdfDocument.GetPage((uint)pageIndex)) { double h = page.Size.Height; var options = new Windows.Data.Pdf.PdfPageRenderOptions(); options.DestinationHeight = (uint)Math.Round(page.Size.Height * (dpi / 96.0), MidpointRounding.AwayFromZero); tbDpi.Text = $"dpi : {dpi.ToString()}"; tbHeight.Text = $"縦ピクセル : {options.DestinationHeight.ToString()}"; using (var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream()) { await page.RenderToStreamAsync(stream, options); BitmapImage image = new BitmapImage(); image.BeginInit(); image.CacheOption = BitmapCacheOption.OnLoad; image.StreamSource = stream.AsStream();//using System.IOがないとエラーになる image.EndInit(); MyImage.Source = image; MyImage.Width = image.PixelWidth; MyImage.Height = image.PixelHeight; } } }
private async void ButtonOpenScale_Click(object sender, RoutedEventArgs e) { var file = await Windows.Storage.StorageFile.GetFileFromPathAsync(@"D:\ブログ用\1708_04.pdf"); try { PdfDocument = await Windows.Data.Pdf.PdfDocument.LoadFromFileAsync(file); } catch (Exception) { } if (PdfDocument != null) { using (Windows.Data.Pdf.PdfPage page = PdfDocument.GetPage(0)) { BitmapImage image = new BitmapImage(); using (var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream()) { var options = new Windows.Data.Pdf.PdfPageRenderOptions(); options.DestinationHeight = 1000; await page.RenderToStreamAsync(stream, options); image.BeginInit(); image.CacheOption = BitmapCacheOption.OnLoad; image.StreamSource = stream.AsStream(); image.EndInit(); } ImagePDF.Source = image; } } }
/// <summary> /// 表示 /// </summary> /// <param name="pageNumber">指定ページ</param> /// <param name="displayDpi">指定dpi、通常なら96</param> private async void PageLoad(uint pageNumber, double displayDpi) { if (PdfDocument == null) { return; } BitmapImage image = new BitmapImage(); var rate = displayDpi / 96.0;//表示倍率みたいなもの using (Windows.Data.Pdf.PdfPage page = PdfDocument.GetPage(pageNumber)) { //指定されたdpiを元にレンダーサイズ指定、四捨五入 double h = page.Size.Height; var options = new Windows.Data.Pdf.PdfPageRenderOptions(); options.DestinationHeight = (uint)Math.Round(h * rate, MidpointRounding.AwayFromZero); using (var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream()) { await page.RenderToStreamAsync(stream, options); image.BeginInit(); image.CacheOption = BitmapCacheOption.OnLoad; image.StreamSource = stream.AsStream(); image.EndInit(); } } MyImage.Source = image; MyImage.Width = image.PixelWidth; MyImage.Height = image.PixelHeight; }
public static async Task <string> GetFullText2(string pathToImg) { Bitmap bmp = new Bitmap(pathToImg); int width = bmp.Width; int height = bmp.Height; using (Graphics g = Graphics.FromImage(bmp)) { // copy rectangle from screen (doesn't include cursor) using (var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream()) { //These steps to get to a SoftwareBitmap are aweful! bmp.Save(stream.AsStream(), System.Drawing.Imaging.ImageFormat.Bmp);//choose the specific image format by your own bitmap source Windows.Graphics.Imaging.BitmapDecoder decoder = await Windows.Graphics.Imaging.BitmapDecoder.CreateAsync(stream); SoftwareBitmap bitmap = await decoder.GetSoftwareBitmapAsync(); OcrResult ocrResult = await _ocrEngine.RecognizeAsync(bitmap); for (int i = 0; i < ocrResult.Lines.Count; i++) { OcrLine line = ocrResult.Lines[i]; } } } return(string.Empty); }
async void RenderPictures() { var service = new JDanielSmith.PictureOfTheDay.Service(); var thickness = new Thickness(0, 0, 50, 100); foreach (var name in service.Names) { var image = new Image() { Stretch = Stretch.Fill, Margin = thickness }; const int offset = 25; thickness = new Thickness(thickness.Left + offset, thickness.Top + offset, thickness.Right - offset, thickness.Bottom - offset); this.grid1.Children.Add(image); var result = await service.GetPictureAsync(name); //var bitmapImage = new BitmapImage(result.Url); var bitmapImage = new BitmapImage(); // http://jebarson.info/post/2012/03/14/byte-array-to-bitmapimage-converter-irandomaccessstream-implementation-for-windows-8-metro.aspx (see comment) using (var ms = new Windows.Storage.Streams.InMemoryRandomAccessStream()) { await result.Image.WriteContentAsync(ms.AsStreamForWrite()); ms.Seek(0); await bitmapImage.SetSourceAsync(ms); } image.Source = bitmapImage; } }
/// <summary> /// jpeg画像で保存 /// </summary> /// <param name="dpi">PDFファイルを読み込む時のDPI</param> /// <param name="directory">保存フォルダ</param> /// <param name="fileName">保存名</param> /// <param name="pageIndex">保存するPDFのページ</param> /// <param name="quality">jpegの品質min0、max100</param> /// <param name="keta">保存名につける連番0埋めの桁数</param> /// <returns></returns> private async Task SaveSub2(double dpi, string directory, string fileName, int pageIndex, int quality, int keta) { using (Windows.Data.Pdf.PdfPage page = MyPdfDocument.GetPage((uint)pageIndex)) { //指定されたdpiを元に画像サイズ指定、四捨五入 var options = new Windows.Data.Pdf.PdfPageRenderOptions(); options.DestinationHeight = (uint)Math.Round(page.Size.Height * (dpi / 96.0), MidpointRounding.AwayFromZero); using (var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream()) { await page.RenderToStreamAsync(stream, options); BitmapImage image = new BitmapImage(); image.BeginInit(); image.CacheOption = BitmapCacheOption.OnLoad; image.StreamSource = stream.AsStream(); image.EndInit(); JpegBitmapEncoder encoder = new JpegBitmapEncoder(); encoder.QualityLevel = quality; encoder.Frames.Add(BitmapFrame.Create(image)); pageIndex++; string renban = pageIndex.ToString("d" + keta); using (var fileStream = new FileStream( System.IO.Path.Combine(directory, fileName) + "_" + renban + ".jpg", FileMode.Create, FileAccess.Write)) { encoder.Save(fileStream); } } } }
//ロックじゃない開き方 private async void ButtonFree_Click(object sender, RoutedEventArgs e) { Windows.Storage.StorageFile file = await Windows.Storage.StorageFile.GetFileFromPathAsync(@"D:\ブログ用\1708_04.pdf"); //ここから using (Windows.Storage.Streams.IRandomAccessStream RAStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read)) { Windows.Data.Pdf.PdfDocument MyPdfDocument = await Windows.Data.Pdf.PdfDocument.LoadFromStreamAsync(RAStream); //ここまで using (Windows.Data.Pdf.PdfPage page = MyPdfDocument.GetPage(0)) { using (var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream()) { await page.RenderToStreamAsync(stream); var image = new BitmapImage(); image.BeginInit(); image.CacheOption = BitmapCacheOption.OnLoad; image.StreamSource = stream.AsStream(); image.EndInit(); MyImage.Source = image; } } } }
public Windows.UI.Xaml.Media.Imaging.BitmapImage GetBitmapSource(System.IO.Stream stream) { Windows.UI.Xaml.Media.Imaging.BitmapImage bitmapSource = new Windows.UI.Xaml.Media.Imaging.BitmapImage(); Windows.Storage.Streams.InMemoryRandomAccessStream ras = new Windows.Storage.Streams.InMemoryRandomAccessStream(); stream.CopyTo(System.IO.WindowsRuntimeStreamExtensions.AsStreamForRead(ras)); bitmapSource.SetSource(ras); return bitmapSource; }
public async Task SetBitmapAsync(BitmapImage image) { var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream(); await RenderToStreamAsync(stream); await image.SetSourceAsync(stream); }
private async void AddToIndex_Click(object sender, RoutedEventArgs e) { if (ItemKeyInput.Text == "") { rootPage.NotifyUser("You must add an item key to insert an item into the index.", NotifyType.ErrorMessage); } else { // Write the content property to a stream var contentStream = new Windows.Storage.Streams.InMemoryRandomAccessStream(); var contentWriter = new Windows.Storage.Streams.DataWriter(contentStream); contentWriter.WriteString(ContentInput.Text); await contentWriter.StoreAsync(); contentStream.Seek(0); // Get the name, keywords, and comment properties, and assign a language to them if provided object itemNameValue = NameInput.Text; object keywordsValue = KeywordsInput.Text; object commentValue = CommentInput.Text; if (LanguageInput.Text != "") { var itemNameValueAndLanguage = new Windows.Storage.Search.ValueAndLanguage(); itemNameValueAndLanguage.Language = LanguageInput.Text; itemNameValueAndLanguage.Value = itemNameValue; itemNameValue = itemNameValueAndLanguage; var keywordsValueAndLanguage = new Windows.Storage.Search.ValueAndLanguage(); keywordsValueAndLanguage.Language = LanguageInput.Text; keywordsValueAndLanguage.Value = keywordsValue; keywordsValue = keywordsValueAndLanguage; var commentValueAndLanguage = new Windows.Storage.Search.ValueAndLanguage(); commentValueAndLanguage.Language = LanguageInput.Text; commentValueAndLanguage.Value = commentValue; commentValue = commentValueAndLanguage; } // Create the item to add to the indexer var content = new Windows.Storage.Search.IndexableContent(); content.Id = ItemKeyInput.Text; content.Properties.Add(Windows.Storage.SystemProperties.ItemNameDisplay, itemNameValue); content.Properties.Add(Windows.Storage.SystemProperties.Keywords, keywordsValue); content.Properties.Add(Windows.Storage.SystemProperties.Comment, commentValue); content.Stream = contentStream; content.StreamContentType = "text/plain"; // Add the item to the indexer Helpers.OnIndexerOperationBegin(); var indexer = Windows.Storage.Search.ContentIndexer.GetIndexer(); await indexer.AddAsync(content); Helpers.OnIndexerOperationComplete(indexer); // Retrieve the item from the indexer and output its properties var retrievedProperties = await indexer.RetrievePropertiesAsync(ItemKeyInput.Text, content.Properties.Keys); rootPage.NotifyUser(Helpers.CreateItemString(ItemKeyInput.Text, content.Properties.Keys, retrievedProperties), NotifyType.StatusMessage); } }
private async Task <Windows.Storage.Streams.InMemoryRandomAccessStream> RenderPageBitmapAsync() { using (Windows.Data.Pdf.PdfPage pdfPage = _pdfDoc.GetPage(_currentPageIndex)) { var memStream = new Windows.Storage.Streams.InMemoryRandomAccessStream(); await pdfPage.RenderToStreamAsync(memStream); return(memStream); } }
public async Task SaveImageAsync(StorageFile file, uint width) { var pdfOption = new pdf.PdfPageRenderOptions(); pdfOption.DestinationWidth = width; var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream(); await Content.RenderToStreamAsync(stream, pdfOption); await Functions.SaveStreamToFile(stream, file); }
async private void Page_Loaded(object sender, RoutedEventArgs e) { Assembly assembly = this.GetType().GetTypeInfo().Assembly; BitmapImage bitmapImage = new BitmapImage(); System.IO.Stream resourceStream = assembly.GetManifestResourceStream(Defaults.IB_CLOSE_BUTTON_RESOURCE); Windows.Storage.Streams.InMemoryRandomAccessStream imras = new Windows.Storage.Streams.InMemoryRandomAccessStream(); await Windows.Storage.Streams.RandomAccessStream.CopyAsync(resourceStream.AsInputStream(), imras); imras.Seek(0); await bitmapImage.SetSourceAsync(imras); this.closeImage.Source = bitmapImage; bitmapImage = new BitmapImage(); resourceStream = assembly.GetManifestResourceStream(Defaults.IB_BACK_BUTTON_RESOURCE); imras = new Windows.Storage.Streams.InMemoryRandomAccessStream(); await Windows.Storage.Streams.RandomAccessStream.CopyAsync(resourceStream.AsInputStream(), imras); imras.Seek(0); await bitmapImage.SetSourceAsync(imras); this.backImage.Source = bitmapImage; bitmapImage = new BitmapImage(); resourceStream = assembly.GetManifestResourceStream(Defaults.IB_FORWARD_BUTTON_RESOURCE); imras = new Windows.Storage.Streams.InMemoryRandomAccessStream(); await Windows.Storage.Streams.RandomAccessStream.CopyAsync(resourceStream.AsInputStream(), imras); imras.Seek(0); await bitmapImage.SetSourceAsync(imras); this.forwardImage.Source = bitmapImage; bitmapImage = new BitmapImage(); resourceStream = assembly.GetManifestResourceStream(Defaults.IB_REFRESH_BUTTON_RESOURCE); imras = new Windows.Storage.Streams.InMemoryRandomAccessStream(); await Windows.Storage.Streams.RandomAccessStream.CopyAsync(resourceStream.AsInputStream(), imras); imras.Seek(0); await bitmapImage.SetSourceAsync(imras); this.refreshImage.Source = bitmapImage; bitmapImage = new BitmapImage(); resourceStream = assembly.GetManifestResourceStream(Defaults.IB_OPEN_BUTTON_RESOURCE); imras = new Windows.Storage.Streams.InMemoryRandomAccessStream(); await Windows.Storage.Streams.RandomAccessStream.CopyAsync(resourceStream.AsInputStream(), imras); imras.Seek(0); await bitmapImage.SetSourceAsync(imras); this.openImage.Source = bitmapImage; }
/// <summary> /// Gets the current preview frame as a SoftwareBitmap, displays its properties in a TextBlock, and can optionally display the image /// in the UI and/or save it to disk as a jpg /// </summary> /// <returns></returns> public async Task <MemoryStream> GetPhotoStreamAsync() { // Get information about the preview var previewProperties = _mediaCapture.VideoDeviceController.GetMediaStreamProperties(MediaStreamType.VideoPreview) as VideoEncodingProperties; PhotoWidth = (int)previewProperties.Width; PhotoHeight = (int)previewProperties.Height; // Create the video frame to request a SoftwareBitmap preview frame var ms = new Windows.Storage.Streams.InMemoryRandomAccessStream(); // Capture the preview frame await _mediaCapture.CapturePhotoToStreamAsync( new ImageEncodingProperties { Height = (uint)PhotoHeight, Width = (uint)PhotoWidth, Subtype = "PNG" }, ms); { // Collect the resulting frame //SoftwareBitmap previewFrame = new SoftwareBitmap(BitmapPixelFormat.Bgra8, PhotoWidth, PhotoHeight); // this is a PNG file so we need to decode it to raw pixel data. var bitmapDecoder = await BitmapDecoder.CreateAsync(ms); // grab the pixels in a byte[] array. var pixelProvider = await bitmapDecoder.GetPixelDataAsync(); var bits = pixelProvider.DetachPixelData(); var stm = new MemoryStream(bits); // Show the frame information //FrameInfoTextBlock.Text = String.Format("{0}x{1} {2}", previewFrame.PixelWidth, previewFrame.PixelHeight, previewFrame.BitmapPixelFormat); // Add a simple green filter effect to the SoftwareBitmap //if (GreenEffectCheckBox.IsChecked == true) //{ // ApplyGreenFilter(previewFrame); //}y // Show the frame (as is, no rotation is being applied) //if (ShowFrameCheckBox.IsChecked == true) //{ // Create a SoftwareBitmapSource to display the SoftwareBitmap to the user //var sbSource = new SoftwareBitmapSource(); //await sbSource.SetBitmapAsync(previewFrame); // // Display it in the Image control // PreviewFrameImage.Source = sbSource; //} //var stm = await SaveSoftwareBitmapAsync(previewFrame); return(stm); } }
private async void AddToIndex_Click(object sender, RoutedEventArgs e) { if (ItemKeyInput.Text == "") { rootPage.NotifyUser("You must add an item key to insert an item into the index.", NotifyType.ErrorMessage); } else { // Write the content property to a stream var contentStream = new Windows.Storage.Streams.InMemoryRandomAccessStream(); var contentWriter = new Windows.Storage.Streams.DataWriter(contentStream); contentWriter.WriteString(ContentInput.Text); await contentWriter.StoreAsync(); contentStream.Seek(0); // Get the name, keywords, and comment properties, and assign a language to them if provided object itemNameValue = NameInput.Text; object keywordsValue = KeywordsInput.Text; object commentValue = CommentInput.Text; if (LanguageInput.Text != "") { var itemNameValueAndLanguage = new Windows.Storage.Search.ValueAndLanguage(); itemNameValueAndLanguage.Language = LanguageInput.Text; itemNameValueAndLanguage.Value = itemNameValue; itemNameValue = itemNameValueAndLanguage; var keywordsValueAndLanguage = new Windows.Storage.Search.ValueAndLanguage(); keywordsValueAndLanguage.Language = LanguageInput.Text; keywordsValueAndLanguage.Value = keywordsValue; keywordsValue = keywordsValueAndLanguage; var commentValueAndLanguage = new Windows.Storage.Search.ValueAndLanguage(); commentValueAndLanguage.Language = LanguageInput.Text; commentValueAndLanguage.Value = commentValue; commentValue = commentValueAndLanguage; } // Create the item to add to the indexer var content = new Windows.Storage.Search.IndexableContent(); content.Id = ItemKeyInput.Text; content.Properties.Add(Windows.Storage.SystemProperties.ItemNameDisplay, itemNameValue); content.Properties.Add(Windows.Storage.SystemProperties.Keywords, keywordsValue); content.Properties.Add(Windows.Storage.SystemProperties.Comment, commentValue); content.Stream = contentStream; content.StreamContentType = "text/plain"; // Add the item to the indexer Helpers.OnIndexerOperationBegin(); var indexer = Windows.Storage.Search.ContentIndexer.GetIndexer(); await indexer.AddAsync(content); Helpers.OnIndexerOperationComplete(indexer); // Retrieve the item from the indexer and output its properties var retrievedProperties = await indexer.RetrievePropertiesAsync(ItemKeyInput.Text, content.Properties.Keys); rootPage.NotifyUser(Helpers.CreateItemString(ItemKeyInput.Text, content.Properties.Keys, retrievedProperties), NotifyType.StatusMessage); } }
public async Task <Windows.UI.Xaml.Media.Imaging.BitmapImage> GetBitmapAsync() { var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream(); await RenderToStreamAsync(stream); var result = new Windows.UI.Xaml.Media.Imaging.BitmapImage(); await result.SetSourceAsync(stream); return(result); }
private Windows.Storage.Streams.IBuffer GetBufferFromBytes(byte[] str) { using (Windows.Storage.Streams.InMemoryRandomAccessStream memoryStream = new Windows.Storage.Streams.InMemoryRandomAccessStream()) { using (Windows.Storage.Streams.DataWriter dataWriter = new Windows.Storage.Streams.DataWriter(memoryStream)) { dataWriter.WriteBytes(str); return(dataWriter.DetachBuffer()); } } }
private async void RenderPageAsync() { if (_pdfDoc == null || _pdfDoc.PageCount == 0) { return; } using (Windows.Storage.Streams.InMemoryRandomAccessStream bitmapStream = await RenderPageBitmapAsync()) { ShowImageAsync(bitmapStream); } }
private async Task <byte[]> GetAudioBytes(Windows.Storage.Streams.InMemoryRandomAccessStream _audioStream) { using (var dataReader = new Windows.Storage.Streams.DataReader(_audioStream.GetInputStreamAt(0))) { await dataReader.LoadAsync((uint)_audioStream.Size); byte[] buffer = new byte[(int)_audioStream.Size]; dataReader.ReadBytes(buffer); return(buffer); } }
public async Task <Stream> GetBitmapAsync() { var softwareBitmap = await capture.GetCaptureAsync(); var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream(); var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, stream); encoder.SetSoftwareBitmap(softwareBitmap); await encoder.FlushAsync(); return(stream.AsStream()); }
/// <summary> /// PdfDocumentをjpegにして、1つのzipファイルにする /// </summary> /// <param name="pdfDocument">Windows.Data.Pdf</param> /// <param name="dpi">PDFを画像にするときに使う</param> /// <param name="directory">保存フォルダ</param> /// <param name="fileName">zipファイル名とjpegファイル名に使う</param> /// <param name="quality">jpeg品質</param> /// <param name="keta">0埋め連番の桁数、jpegファイル名に使う</param> /// <returns></returns> private async Task SaveSub3_1(PdfDocument pdfDocument, double dpi, string directory, string fileName, int quality, int keta, bool isJpeg) { string exte = isJpeg ? ".jpg" : ".png"; BitmapEncoder encoder; string zipName = System.IO.Path.Combine(directory, fileName) + ".zip"; using (var zipstream = File.Create(zipName)) { using (ZipArchive archive = new ZipArchive(zipstream, ZipArchiveMode.Create)) { for (int i = 0; i < MyPdfDocument.PageCount; i++) { int renban = i + 1; string jpegName = MyPdfName + "_" + renban.ToString("d" + keta) + exte; if (isJpeg) { JpegBitmapEncoder j = new JpegBitmapEncoder(); j.QualityLevel = quality; encoder = j; } else { encoder = new PngBitmapEncoder(); } using (PdfPage page = pdfDocument.GetPage((uint)i)) { var options = new PdfPageRenderOptions(); options.DestinationHeight = (uint)Math.Round(page.Size.Height * (dpi / 96.0), MidpointRounding.AwayFromZero); using (var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream()) { await page.RenderToStreamAsync(stream, options);//画像に変換したのはstreamへ encoder.Frames.Add(BitmapFrame.Create(stream.AsStream())); var entry = archive.CreateEntry(jpegName); //open using (var entryStream = entry.Open()) { using (var jpegStream = new MemoryStream()) { encoder.Save(jpegStream); jpegStream.Position = 0; jpegStream.CopyTo(entryStream); } } } } }//for } } }
async Task <OcrResult> RecognizeBitmapAsync(Bitmap b) { // Need to marshall from Drawing.Bitmap to UWP SoftwareBitmap using (var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream()) { b.Save(stream.AsStream(), System.Drawing.Imaging.ImageFormat.Bmp); //choose the specific image format by your own bitmap source Windows.Graphics.Imaging.BitmapDecoder decoder = await Windows.Graphics.Imaging.BitmapDecoder.CreateAsync(stream); Windows.Graphics.Imaging.SoftwareBitmap softwareBitmap = await decoder.GetSoftwareBitmapAsync(); return(await engine.RecognizeAsync(softwareBitmap)); } }
//全ページBitmapSourceのリスト private async void ButtonTest2_Click(object sender, RoutedEventArgs e) { List <BitmapFrame> frames = new List <BitmapFrame>(); var ps = GetPages(); for (int i = 0; i < ps.Count; i++) { using (var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream()) { await ps[i].RenderToStreamAsync(stream); frames.Add(BitmapFrame.Create(stream.AsStream())); } } }
private BitmapImage GetBitmap(byte[] bytes) { var bmp = new BitmapImage(); using (var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream()) { using (var writer = new Windows.Storage.Streams.DataWriter(stream.GetOutputStreamAt(0))) { writer.WriteBytes(bytes); writer.StoreAsync().GetResults(); bmp.SetSource(stream); } } return bmp; }
private static async Task <MemoryStream> SaveSoftwareBitmapAsync(SoftwareBitmap bitmap) { var rs = new Windows.Storage.Streams.InMemoryRandomAccessStream(); var bf = new Windows.Storage.Streams.Buffer(1024 * 1024 * 10); bitmap.CopyToBuffer(bf); //var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.BmpEncoderId, rs); await rs.WriteAsync(bf); var ms = new MemoryStream(); await rs.GetInputStreamAt(0).AsStreamForRead().CopyToAsync(ms); ms.Position = 0; return(ms); }
async private void Page_Loaded(object sender, RoutedEventArgs e) { Assembly assembly = this.GetType().GetTypeInfo().Assembly; BitmapImage bitmapImage = new BitmapImage(); System.IO.Stream resourceStream = assembly.GetManifestResourceStream(Defaults.IB_CLOSE_BUTTON_RESOURCE); Windows.Storage.Streams.InMemoryRandomAccessStream imras = new Windows.Storage.Streams.InMemoryRandomAccessStream(); await Windows.Storage.Streams.RandomAccessStream.CopyAsync(resourceStream.AsInputStream(), imras); imras.Seek(0); await bitmapImage.SetSourceAsync(imras); this.closeImage.Source = bitmapImage; bitmapImage = new BitmapImage(); resourceStream = assembly.GetManifestResourceStream(Defaults.IB_BACK_BUTTON_RESOURCE); imras = new Windows.Storage.Streams.InMemoryRandomAccessStream(); await Windows.Storage.Streams.RandomAccessStream.CopyAsync(resourceStream.AsInputStream(), imras); imras.Seek(0); await bitmapImage.SetSourceAsync(imras); this.backImage.Source = bitmapImage; bitmapImage = new BitmapImage(); resourceStream = assembly.GetManifestResourceStream(Defaults.IB_FORWARD_BUTTON_RESOURCE); imras = new Windows.Storage.Streams.InMemoryRandomAccessStream(); await Windows.Storage.Streams.RandomAccessStream.CopyAsync(resourceStream.AsInputStream(), imras); imras.Seek(0); await bitmapImage.SetSourceAsync(imras); this.forwardImage.Source = bitmapImage; bitmapImage = new BitmapImage(); resourceStream = assembly.GetManifestResourceStream(Defaults.IB_REFRESH_BUTTON_RESOURCE); imras = new Windows.Storage.Streams.InMemoryRandomAccessStream(); await Windows.Storage.Streams.RandomAccessStream.CopyAsync(resourceStream.AsInputStream(), imras); imras.Seek(0); await bitmapImage.SetSourceAsync(imras); this.refreshImage.Source = bitmapImage; bitmapImage = new BitmapImage(); resourceStream = assembly.GetManifestResourceStream(Defaults.IB_OPEN_BUTTON_RESOURCE); imras = new Windows.Storage.Streams.InMemoryRandomAccessStream(); await Windows.Storage.Streams.RandomAccessStream.CopyAsync(resourceStream.AsInputStream(), imras); imras.Seek(0); await bitmapImage.SetSourceAsync(imras); this.openImage.Source = bitmapImage; }
/// <summary> /// This method set the poster source for the MediaElement /// </summary> private async System.Threading.Tasks.Task<bool> SetPosterUrl(string PosterUrl) { if (IsPicture(PosterUrl)) { if (IsLocalFile(PosterUrl)) { try { Windows.Storage.StorageFile file = await GetFileFromLocalPathUrl(PosterUrl); if (file != null) { using (var fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read)) { if (fileStream != null) { Windows.UI.Xaml.Media.Imaging.BitmapImage b = new Windows.UI.Xaml.Media.Imaging.BitmapImage(); if (b != null) { b.SetSource(fileStream); SetPictureSource(b); SetPictureElementSize(); return true; } } } } else LogMessage("Failed to load poster: " + PosterUrl); } catch (Exception e) { LogMessage("Exception while loading poster: " + PosterUrl + " - " + e.Message); } } else { try { // Load the bitmap image over http Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient(); Windows.Storage.Streams.InMemoryRandomAccessStream ras = new Windows.Storage.Streams.InMemoryRandomAccessStream(); using (var stream = await httpClient.GetInputStreamAsync(new Uri(PosterUrl))) { if (stream != null) { await stream.AsStreamForRead().CopyToAsync(ras.AsStreamForWrite()); ras.Seek(0); var b = new Windows.UI.Xaml.Media.Imaging.BitmapImage(); if (b != null) { await b.SetSourceAsync(ras); SetPictureSource(b); SetPictureElementSize(); return true; } } } } catch (Exception e) { System.Diagnostics.Debug.WriteLine("Exception: " + e.Message); } } } return false; }
private Windows.Storage.Streams.IBuffer GetBufferFromBytes(byte[] str) { using (Windows.Storage.Streams.InMemoryRandomAccessStream memoryStream = new Windows.Storage.Streams.InMemoryRandomAccessStream()) { using (Windows.Storage.Streams.DataWriter dataWriter = new Windows.Storage.Streams.DataWriter(memoryStream)) { dataWriter.WriteBytes(str); return dataWriter.DetachBuffer(); } } }
public async Task SetBitmapAsync(BitmapImage image) { var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream(); await RenderToStreamAsync(stream); await image.SetSourceAsync(stream); }
public async Task SaveImageAsync(StorageFile file,uint width) { var pdfOption = new pdf.PdfPageRenderOptions(); pdfOption.DestinationWidth = width; var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream(); await Content.RenderToStreamAsync(stream, pdfOption); await Functions.SaveStreamToFile(stream, file); }
public async Task<Windows.UI.Xaml.Media.Imaging.BitmapImage> GetBitmapAsync() { var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream(); await RenderToStreamAsync(stream); var result = new Windows.UI.Xaml.Media.Imaging.BitmapImage(); await result.SetSourceAsync(stream); return result; }
public async void drawSelection(int iPageIndex) { int selectCharStartIndexTemp = -1; int selectCharEndIndexTemp = -1; int flag; pageInfo pginfo; Image img; Windows.Storage.Streams.InMemoryRandomAccessStream ms; Windows.Graphics.Imaging.BitmapEncoder encoder; Windows.UI.Xaml.Media.Imaging.BitmapImage newImg; if (visiblePage.ContainsKey(iPageIndex) && visiblePage[iPageIndex].hTextPage.pointer != 0) { pginfo = visiblePage[iPageIndex]; Windows.Storage.Streams.InMemoryRandomAccessStream stream = new Windows.Storage.Streams.InMemoryRandomAccessStream(); if (selectBmpTemp.Length != pginfo.bitmap.Length) { selectBmpTemp = new byte[pginfo.bitmap.Length]; } Buffer.BlockCopy(pginfo.bitmap, 0, selectBmpTemp, 0, pginfo.bitmap.Length); if (iPageIndex < rSelectPageStartIndex || iPageIndex > rSelectPageEndIndex) { img = (Image)(ud_pdfContainer.Children.ElementAt(iPageIndex)); ms = new Windows.Storage.Streams.InMemoryRandomAccessStream(); encoder = await Windows.Graphics.Imaging.BitmapEncoder.CreateAsync(Windows.Graphics.Imaging.BitmapEncoder.BmpEncoderId, ms); encoder.SetPixelData(Windows.Graphics.Imaging.BitmapPixelFormat.Rgba8, Windows.Graphics.Imaging.BitmapAlphaMode.Straight, (uint)m_iRenderAreaSizeX, (uint)m_iRenderAreaSizeY, 96.0, 96.0, selectBmpTemp); await encoder.FlushAsync(); newImg = new Windows.UI.Xaml.Media.Imaging.BitmapImage(); newImg.SetSource(ms); img.Source = newImg; return; } if(iPageIndex == rSelectPageStartIndex) { selectCharStartIndexTemp = rSelectCharStartIndex; } else { selectCharStartIndexTemp = 0; } if(iPageIndex < rSelectPageEndIndex) { flag = m_SDKDocument.getCharNum(visiblePage[iPageIndex].hTextPage, out selectCharEndIndexTemp); if(flag != 0) { return; } } else if(iPageIndex == rSelectPageEndIndex) { selectCharEndIndexTemp = rSelectCharEndIndex; } img = (Image)(ud_pdfContainer.Children.ElementAt(iPageIndex)); m_SDKDocument.LoadMatrix(pginfo.hPage, m_iStartX, m_iStartY, m_iRenderAreaSizeX, m_iRenderAreaSizeY, m_iRotation, out pginfo.hMatrix); m_SDKDocument.startSelectText(pginfo.hTextPage, selectCharStartIndexTemp, selectCharEndIndexTemp - selectCharStartIndexTemp + 1); int rectNum; int x, y, z, w; m_SDKDocument.getRectNum(out rectNum); for(int count = 0;count < rectNum;count++) { m_SDKDocument.getRect(count, pginfo.hMatrix, out x, out y, out z, out w); for(int count1 = w;count1 <= y;count1 ++) { for(int count2 = 4 * x;count2 <= 4 * z;count2 += 1) { selectBmpTemp[count1 * pginfo.bmpWidth * 4 + count2] /= 2; } } } m_SDKDocument.endSelectText(); // ms = new Windows.Storage.Streams.InMemoryRandomAccessStream(); encoder = await Windows.Graphics.Imaging.BitmapEncoder.CreateAsync(Windows.Graphics.Imaging.BitmapEncoder.BmpEncoderId, ms); encoder.SetPixelData(Windows.Graphics.Imaging.BitmapPixelFormat.Rgba8, Windows.Graphics.Imaging.BitmapAlphaMode.Straight, (uint)m_iRenderAreaSizeX, (uint)m_iRenderAreaSizeY, 96.0, 96.0, selectBmpTemp); await encoder.FlushAsync(); newImg = new Windows.UI.Xaml.Media.Imaging.BitmapImage(); newImg.SetSource(ms); img.Source = newImg; } }
private BitmapSource ReadDeviceIndependantBitmap(BinaryReader wmfReader, uint dibSize, out int width, out int height) { #if NETFX_CORE var bmp = new BitmapImage(); var memStream = new Windows.Storage.Streams.InMemoryRandomAccessStream(); var dibBytes = wmfReader.ReadBytes((int)dibSize); // int imageBytesOffset = 14; //System.Runtime.InteropServices.GCHandle pinnedDib = System.Runtime.InteropServices.GCHandle.Alloc(dibBytes, System.Runtime.InteropServices.GCHandleType.Pinned); //if (dibBytes[3] == 0x0C) //{ // imageBytesOffset += 12; //} //else //{ // var infoHeader = (BITMAPINFOHEADER)System.Runtime.InteropServices.Marshal.PtrToStructure(pinnedDib.AddrOfPinnedObject(), typeof(BITMAPINFOHEADER)); // imageBytesOffset += (int)infoHeader.biSize; // switch ((BitCount)infoHeader.biBitCount) // { // case BitCount.BI_BITCOUNT_1: // // 1 bit - Two colors // imageBytesOffset += 4 * (colorUsed == 0 ? 2 : Math.Min(colorUsed, 2)); // break; // case BitCount.BI_BITCOUNT_2: // // 4 bit - 16 colors // imageBytesOffset += 4 * (colorUsed == 0 ? 16 : Math.Min(colorUsed, 16)); // break; // case BitCount.BI_BITCOUNT_3: // // 8 bit - 256 colors // imageBytesOffset += 4 * (colorUsed == 0 ? 256 : Math.Min(colorUsed, 256)); // break; // } // if ((Compression)infoHeader.biCompression == Compression.BI_BITFIELDS) // { // imageBytesOffset += 12; // } //} //pinnedDib.Free(); using (Windows.Storage.Streams.DataWriter writer = new Windows.Storage.Streams.DataWriter(memStream.GetOutputStreamAt(0))) { writer.WriteBytes(new byte[] { 66, 77 }); // BM writer.WriteUInt32(dibSize + 14); writer.WriteBytes(new byte[] { 0, 0, 0, 0 }); // Reserved writer.WriteUInt32((UInt32)0); writer.WriteBytes(dibBytes); var t = writer.StoreAsync(); t.GetResults(); } // bmp.ImageFailed += bmp_ImageFailed; // bmp.ImageOpened += bmp_ImageOpened; bmp.SetSource(memStream); width = bmp.PixelWidth; height = bmp.PixelHeight; return bmp; #else var bmp = new BitmapImage(); var memStream = new MemoryStream(); var dibBytes = wmfReader.ReadBytes((int)dibSize); BinaryWriter writer = new BinaryWriter(memStream); writer.Write(new byte[] { 66, 77 }); // BM writer.Write(dibSize + 14); writer.Write(new byte[] { 0, 0, 0, 0 }); // Reserved writer.Write((UInt32)0); writer.Write(dibBytes); writer.Flush(); memStream.Position = 0; try { bmp.BeginInit(); bmp.StreamSource = memStream; bmp.EndInit(); width = bmp.PixelWidth; height = bmp.PixelHeight; return bmp; } catch { // Bad image; width = 0; height = 0; return null; } #endif }