async Task<string> OCRAsync(byte[] buffer, uint width, uint height) { var bitmap = new WriteableBitmap((int)width, (int)height); var memoryStream = new MemoryStream(buffer); await bitmap.SetSourceAsync(memoryStream.AsRandomAccessStream()); if (bitmap.PixelHeight < 40 || bitmap.PixelHeight > 2600 || bitmap.PixelWidth < 40 || bitmap.PixelWidth > 2600) bitmap = await ResizeImage(bitmap, (uint)(bitmap.PixelWidth * .7), (uint)(bitmap.PixelHeight * .7)); var ocrResult = await ocrEngine.RecognizeAsync((uint)bitmap.PixelHeight, (uint)bitmap.PixelWidth, bitmap.PixelBuffer.ToArray()); if (ocrResult.Lines != null) { var extractedText = new StringBuilder(); foreach (var line in ocrResult.Lines) { foreach (var word in line.Words) extractedText.Append(word.Text + " "); extractedText.Append(Environment.NewLine); } return extractedText.ToString(); } return null; }
/// <summary> /// Get the user's photo. /// </summary> /// <param name="user">The target user.</param> /// <returns></returns> public async Task<BitmapImage> GetUserThumbnailPhotoAsync(IUser user) { BitmapImage bitmap = null; try { // The using statement ensures that Dispose is called even if an // exception occurs while you are calling methods on the object. using (var dssr = await user.ThumbnailPhoto.DownloadAsync()) using (var stream = dssr.Stream) using (var memStream = new MemoryStream()) { await stream.CopyToAsync(memStream); memStream.Seek(0, SeekOrigin.Begin); bitmap = new BitmapImage(); await bitmap.SetSourceAsync(memStream.AsRandomAccessStream()); } } catch(ODataException) { // Something went wrong retrieving the thumbnail photo, so set the bitmap to a default image bitmap = new BitmapImage(new Uri("ms-appx:///assets/UserDefaultSignedIn.png", UriKind.RelativeOrAbsolute)); } return bitmap; }
public object Convert(object value, Type typeName, object parameter, string language) #endif { if (value is byte[]) { var array = (byte[])value; if (array.Length > 0) { try { var stream = new MemoryStream(); stream.Write(array, 0, array.Length); var img = new BitmapImage(); #if WINRT img.SetSource(stream.AsRandomAccessStream()); #elif WPF img.StreamSource = stream; #else img.SetSource(stream); #endif return img; } catch { } } } return null; }
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(); }
public async Task<BitmapImage> GetPhotoAsync(string photoUrl, string token) { using (var client = new HttpClient()) { try { var request = new HttpRequestMessage(HttpMethod.Get, new Uri(photoUrl)); BitmapImage bitmap = null; request.Headers.Add("Authorization", "Bearer " + token); var response = await client.SendAsync(request); var stream = await response.Content.ReadAsStreamAsync(); if (response.IsSuccessStatusCode) { using (var memStream = new MemoryStream()) { await stream.CopyToAsync(memStream); memStream.Seek(0, SeekOrigin.Begin); bitmap = new BitmapImage(); await bitmap.SetSourceAsync(memStream.AsRandomAccessStream()); } return bitmap; } else { Debug.WriteLine("Unable to find an image at this endpoint."); bitmap = new BitmapImage(new Uri("ms-appx:///assets/UserDefault.png", UriKind.RelativeOrAbsolute)); return bitmap; } } catch (Exception e) { Debug.WriteLine("Could not get the thumbnail photo: " + e.Message); return null; } } }
public static async Task <BitmapImage> GetBlueIrisImage(String BlueIrisUrl, String CameraKey) { BitmapImage image = new BitmapImage(); Byte[] imageBytes = await WebGetUtils.GetImageBytes(BlueIrisUrl + CameraKey + "?q=20"); //Quality 20 since it's such a small screen... using (var ms = new System.IO.MemoryStream(imageBytes)) { await image.SetSourceAsync(ms.AsRandomAccessStream()); } return(image); }
private async Task ProcessImageAsync() { var bitmapImage = new BitmapImage(); try { using (var client = new HttpClient()) { using (var stream = await client.GetStreamAsync(new Uri(BlobUrl))) { var memoryStream = new MemoryStream(); await stream.CopyToAsync(memoryStream); memoryStream.Position = 0; bitmapImage.SetSource(memoryStream.AsRandomAccessStream()); } } } catch (Exception ex) { } //InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream(); //var httpClient = new HttpClient(); //var webReq = (HttpWebRequest)WebRequest.Create(BlobUrl); //var httpClient.re //using (WebResponse response = await webReq.GetResponseAsync()) //{ // using (Stream responseStream = response.GetResponseStream()) // { // try // { // responseStream.CopyTo(stream); // } // catch (Exception ex) // { } // } //} //var image = new BitmapImage(); //image.SetSource(stream); //Image = image; Image = bitmapImage; var scale = 350.0 / Image.PixelWidth; FaceBoxWidth = FaceRectangle.Width * scale; FaceBoxHeight = FaceRectangle.Height * scale; FaceBoxMargin = new Thickness(FaceRectangle.Left * scale, FaceRectangle.Top * scale, 0, 0); OnPropertyChanged("Image"); OnPropertyChanged("FaceBoxWidth"); OnPropertyChanged("FaceBoxHeight"); OnPropertyChanged("FaceBoxMargin"); }
private async void readQRCode() { StorageFile file = await KnownFolders.PicturesLibrary.GetFileAsync("photo.jpg"); var sourceStream = (await file.OpenReadAsync()).GetInputStreamAt(0); byte[] imageBytes = await readFile(file); MemoryStream stream = new MemoryStream(imageBytes); IRandomAccessStream randomStream = stream.AsRandomAccessStream(); BitmapImage bitmapImage = new BitmapImage(); bitmapImage.SetSource(randomStream); var wb = new WriteableBitmap(bitmapImage.PixelWidth, bitmapImage.PixelHeight); Result result = reader.Decode(wb); resultUrl.Text = result.Text; }
public async Task<BitmapImage> GetFromUrl(string url) { using (var client = new HttpClient()) { var imageData = await client.GetByteArrayAsync(url); using (var ms = new MemoryStream(imageData)) { var image = new BitmapImage(); await image.SetSourceAsync(ms.AsRandomAccessStream()); return image; } } }
private async void GetThumbnail() { DeviceThumbnail thumb = await _information.GetGlyphThumbnailAsync(); Stream s = thumb.AsStreamForRead(); MemoryStream ms = new MemoryStream(); await s.CopyToAsync(ms); ms.Seek(0, SeekOrigin.Begin); WriteableBitmap wb = new WriteableBitmap(1, 1); await wb.SetSourceAsync(ms.AsRandomAccessStream()); _thumbnail = wb; OnPropertyChanged("Thumbnail"); }
public MainPage() { this.InitializeComponent(); var imageLoader = new ImageLoader(); // start image loading task, don't wait var task = ThreadPool.RunAsync(async (source) => { await LoadImages(imageLoader); }); // schedule image databaase refresh every 20 seconds TimeSpan imageLoadPeriod = TimeSpan.FromSeconds(20); ThreadPoolTimer imageLoadTimes = ThreadPoolTimer.CreatePeriodicTimer( async (source) => { await LoadImages(imageLoader); }, imageLoadPeriod); TimeSpan displayImagesPeriod = TimeSpan.FromSeconds(5); // display new images every five seconds ThreadPoolTimer imageDisplayTimer = ThreadPoolTimer.CreatePeriodicTimer( async (source) => { // get next image (byte aray) from database var imageBytes = imageLoader.GetNextImage(); if (imageBytes != null) { // we have to update UI in UI thread only await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () => { // create bitmap from byte array BitmapImage bitmap = new BitmapImage(); MemoryStream ms = new MemoryStream(imageBytes); await bitmap.SetSourceAsync(ms.AsRandomAccessStream()); // display image splashImage.Source = bitmap; } ); } }, displayImagesPeriod); }
public void MultithreadedSaveToStream() { // This is the stream version of the above test var task = Task.Run(async () => { var device = new CanvasDevice(); var rt = new CanvasRenderTarget(device, 16, 16, 96); var stream = new MemoryStream(); await rt.SaveAsync(stream.AsRandomAccessStream(), CanvasBitmapFileFormat.Bmp); rt.Dispose(); }); task.Wait(); }
/// <summary> /// Scales the image in the given memory stream. /// </summary> /// <param name="originalStream">The original image stream to scale.</param> /// <param name="originalResolutionWidth">The original width.</param> /// <param name="originalResolutionHeight">The original height.</param> /// <param name="scaledStream">Stream where the scaled image is stored.</param> /// <param name="scaleWidth">The target width.</param> /// <param name="scaleHeight">The target height.</param> /// <returns></returns> public static async Task ScaleImageStreamAsync(MemoryStream originalStream, int originalResolutionWidth, int originalResolutionHeight, MemoryStream scaledStream, int scaleWidth, int scaleHeight) { System.Diagnostics.Debug.WriteLine(DebugTag + "ScaleImageStreamAsync() ->"); // Create a bitmap containing the full resolution image var bitmap = new WriteableBitmap(originalResolutionWidth, originalResolutionHeight); originalStream.Seek(0, SeekOrigin.Begin); await bitmap.SetSourceAsync(originalStream.AsRandomAccessStream()); /* Construct a JPEG encoder with the newly created * InMemoryRandomAccessStream as target */ IRandomAccessStream previewResolutionStream = new InMemoryRandomAccessStream(); previewResolutionStream.Size = 0; BitmapEncoder encoder = await BitmapEncoder.CreateAsync( BitmapEncoder.JpegEncoderId, previewResolutionStream); // Copy the full resolution image data into a byte array Stream pixelStream = bitmap.PixelBuffer.AsStream(); var pixelArray = new byte[pixelStream.Length]; await pixelStream.ReadAsync(pixelArray, 0, pixelArray.Length); // Set the scaling properties encoder.BitmapTransform.ScaledWidth = (uint)scaleWidth; encoder.BitmapTransform.ScaledHeight = (uint)scaleHeight; encoder.BitmapTransform.InterpolationMode = BitmapInterpolationMode.Fant; encoder.IsThumbnailGenerated = true; // Set the image data and the image format setttings to the encoder encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)originalResolutionWidth, (uint)originalResolutionHeight, 96.0, 96.0, pixelArray); await encoder.FlushAsync(); previewResolutionStream.Seek(0); await previewResolutionStream.AsStream().CopyToAsync(scaledStream); System.Diagnostics.Debug.WriteLine(DebugTag + "<- ScaleImageStreamAsync()"); }
/// <summary> /// This method set ImageSource to image. /// </summary> /// <param name="imageBytes"></param> private async void SetImage(byte[] imageBytes) { BitmapImage im; // If imageBytes has data in it, then use it. if (imageBytes != null) { im = new BitmapImage(); using (MemoryStream ms = new MemoryStream(imageBytes)) { await im.SetSourceAsync(ms.AsRandomAccessStream()); } } // Otherwise use default picture. else im = new BitmapImage(new Uri("ms-appx:///Assets/icon-contact.png")); image.Source = im; }
public void MultithreadedSaveToStream() { // This is the stream version of the above test using (new DisableDebugLayer()) // 6184116 causes the debug layer to fail when CanvasBitmap::SaveAsync is called { var task = Task.Run(async () => { var device = new CanvasDevice(); var rt = new CanvasRenderTarget(device, 16, 16, 96); var stream = new MemoryStream(); await rt.SaveAsync(stream.AsRandomAccessStream(), CanvasBitmapFileFormat.Bmp); rt.Dispose(); }); task.Wait(); } }
private async void BitmapTransform(string filePath) { var client = new HttpClient(); var stream = await client.GetStreamAsync(filePath); var memStream = new MemoryStream(); await stream.CopyToAsync(memStream); memStream.Position = 0; var decoder = await BitmapDecoder.CreateAsync(memStream.AsRandomAccessStream()); var ras = new InMemoryRandomAccessStream(); var enc = await BitmapEncoder.CreateForTranscodingAsync(ras, decoder); var frame = await decoder.GetFrameAsync(0); enc.BitmapTransform.ScaledHeight = frame.PixelHeight; enc.BitmapTransform.ScaledWidth = frame.PixelWidth; var bounds = new BitmapBounds { Height = 80, Width = frame.PixelWidth, X = 0, Y = 0 }; enc.BitmapTransform.Bounds = bounds; try { await enc.FlushAsync(); } catch (Exception ex) { Debug.WriteLine(ex.ToString()); } var bImg = BitmapFactory.New((int) frame.PixelWidth, (int) frame.PixelHeight); using (bImg.GetBitmapContext()) { bImg = await BitmapFactory.New((int) frame.PixelWidth, (int) frame.PixelHeight).FromStream(ras); bImg.ForEach( (x, y, color) => color.ToString().Equals("#FFCECECE") ? Color.FromArgb(80, 0, 0, 0) : Colors.WhiteSmoke); } BorderBrushStreamPlayer.ImageSource = bImg; }
async void GetEmotions(object sender, object e) { // dt.Stop(); var ms = new MemoryStream(); await MC.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), ms.AsRandomAccessStream()); ms.Position = 0L; var Emo = await Oxford.RecognizeAsync(ms); if (Emo!=null && Emo.Length>0) { var Face = Emo[0]; var s = Face.Scores; // res.Text = $"Happiness: {s.Happiness,6:N4}\nAnger: {s.Anger,6:N4}\nContempt: {s.Contempt,6:N4}\nDisgust: {s.Disgust,6:N4}\nFear: {s.Fear,6:N4}\nSadness: {s.Sadness,6:N4}\nSurprise: {s.Surprise,6:N4}"; // Canvas.SetLeft(res, Face.FaceRectangle.Left+Face.FaceRectangle.Width/2); // Canvas.SetTop(res, Face.FaceRectangle.Top+Face.FaceRectangle.Height/2); var T = new Thickness(); T.Left = Face.FaceRectangle.Left; T.Top=Face.FaceRectangle.Top; // res.Margin = T; EmoControl.Margin = T; MyEmo.Update(Face.Scores); } }
/// <summary> /// Get the user's photo. /// </summary> /// <param name="user">The target user.</param> /// <returns></returns> public async Task<BitmapImage> GetUserThumbnailPhotoAsync(IUser user) { BitmapImage bitmap = null; try { using (var stream = (await user.ThumbnailPhoto.DownloadAsync()).Stream) { MemoryStream memStream = new MemoryStream(); await stream.CopyToAsync(memStream); memStream.Seek(0, SeekOrigin.Begin); bitmap = new BitmapImage(); await bitmap.SetSourceAsync(memStream.AsRandomAccessStream()); } } catch(ODataException) { // Set the bitmap to a default image bitmap = new BitmapImage(new Uri("ms-appx:///assets/UserDefaultSignedIn.png", UriKind.RelativeOrAbsolute)); } return bitmap; }
protected async Task GetUserImage() { var user = ConfigurationHub.ReadConfigurationValue("SharePointUser"); var sharePointUser = user.Replace(".", "_").Replace("@", "_"); var imageStream = await MobileClient.Util.SharePointProvider.GetUserPhoto(ConfigurationHub.ReadConfigurationValue("SharePointResource"), State.SharePointToken, sharePointUser); if (imageStream != null) { var memStream = new MemoryStream(); var bitmap = new BitmapImage(); await imageStream.CopyToAsync(memStream); memStream.Position = 0; bitmap.SetSource(memStream.AsRandomAccessStream()); this.UserImage = bitmap; } else { this.UserImage = new BitmapImage(new System.Uri("ms-appx:///Assets/UserImage.png")); } }
private async Task InitSplashScreenAsync() { var visualElements = PackageManifest.Current.Applications.First().VisualElements; var splashScreen = visualElements.SplashScreen; if (splashScreen != null) { if (string.IsNullOrEmpty(splashScreen.Image) == false) { var imagePath = splashScreen.Image; var imageFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///" + imagePath, UriKind.Absolute)); var buffer = (await FileIO.ReadBufferAsync(imageFile)).ToArray(); using (var stream = new MemoryStream(buffer)) { var bitmap = new BitmapImage(); await bitmap.SetSourceAsync(stream.AsRandomAccessStream()); imgExtendedSplashBackground.Source = bitmap; } } var backgroundColor = splashScreen.BackgroundColor.HasValue ? splashScreen.BackgroundColor.Value : visualElements.BackgroundColor; RootLayout.Background = new SolidColorBrush(backgroundColor); } }
/// <summary> /// Using Windows.Data.Pdf in desktop applications /// </summary> private async Task<System.Windows.Media.Imaging.BitmapImage> renderPage() { using (var memoryStream = new MemoryStream()) { using (var winrtStream = memoryStream.AsRandomAccessStream()) { using (var page = _pdfDocument.GetPage(_currentPageIndex)) { await page.RenderToStreamAsync(winrtStream); await winrtStream.FlushAsync(); var bitmapImage = new System.Windows.Media.Imaging.BitmapImage(); bitmapImage.BeginInit(); //Without this, BitmapImage uses lazy initialization by default and the stream will be closed by then. bitmapImage.CacheOption = System.Windows.Media.Imaging.BitmapCacheOption.OnLoad; bitmapImage.StreamSource = memoryStream; bitmapImage.EndInit(); return bitmapImage; } } } }
public static async Task<byte[]> CropImage(byte[] stream, Crop crop) { byte[] byteArray = null; var imageStream = new MemoryStream(stream); var fileStream = imageStream.AsRandomAccessStream(); BitmapDecoder decoder = await BitmapDecoder.CreateAsync(fileStream); InMemoryRandomAccessStream ras = new InMemoryRandomAccessStream(); BitmapEncoder enc = await BitmapEncoder.CreateForTranscodingAsync(ras, decoder); BitmapBounds bounds = new BitmapBounds(); bounds.Height = (uint)crop.Height; bounds.Width = (uint)crop.Width; bounds.X = (uint)crop.X; bounds.Y = (uint)crop.Y; enc.BitmapTransform.Bounds = bounds; enc.BitmapTransform.InterpolationMode = BitmapInterpolationMode.Linear; enc.IsThumbnailGenerated = false; try { await enc.FlushAsync(); } catch (Exception ex) { Debug.WriteLine("Error croping image", ex); } byteArray = new byte[ras.Size]; DataReader dataReader = new DataReader(ras.GetInputStreamAt(0)); await dataReader.LoadAsync((uint)ras.Size); dataReader.ReadBytes(byteArray); return byteArray; }
async void renderPDF() { try { HttpClient client = new HttpClient(); Stream s = await client.GetStreamAsync("http://www.spartahack.com/map.pdf"); MemoryStream ms = new MemoryStream(); await s.CopyToAsync(ms); ms.Position = 0; // StorageFile file = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(@"PDFs\ios-map.pdf"); // PdfDocument pdf = await PdfDocument.LoadFromFileAsync(file); PdfDocument pdf = await PdfDocument.LoadFromStreamAsync(ms.AsRandomAccessStream()); List<BitmapImage> images = new List<BitmapImage>(); pageCount = pdf.PageCount; for (uint pageNum = 0; pageNum < pdf.PageCount; pageNum++) { PdfPage page = pdf.GetPage(pageNum); InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream(); await page.RenderToStreamAsync(stream); BitmapImage source = new BitmapImage(); source.SetSource(stream); images.Add(source); } Pdfs.Source = images; pgrRing.IsActive = false; } catch { } }
/// <summary> /// Loads the detail view for the specified item. /// </summary> /// <param name="item">The item to load.</param> /// <returns>The task to await.</returns> private async Task LoadImage(ItemModel item) { // Only load a detail view image for image items. Initialize the bitmap from the image conent stream. if (item.Bitmap == null && (item.Item.Image != null)) { item.Bitmap = new BitmapImage(new Uri(item.SmallThumbnail.Url)); var client = ((App)Application.Current).OneDriveClient; using (var responseStream = await client.Drive.Items[item.Id].Content.Request().GetAsync()) using (var memoryStream = new MemoryStream()) { await responseStream.CopyToAsync(memoryStream); memoryStream.Position = 0; await item.Bitmap.SetSourceAsync(memoryStream.AsRandomAccessStream()); } } }
/// <summary> /// Utility method to access a byte array as a random access stream. /// </summary> /// <param name="arr">Byte array that you would like to access as a stream.</param> /// <returns>Random access stream based on the specified byte array.</returns> internal static IRandomAccessStream ConvertArrayToStream(byte[] arr) { var stream = new MemoryStream(arr); return stream.AsRandomAccessStream(); }
/// <summary> /// Set an image to this class by specifying the WritableBitmap and the target encoding and /// optionally the DPI to set for the target file (if supported by the target file type). /// </summary> /// <remarks> /// The method takes the bitmap as input and uses the BitmapEncoder to encode /// the image data into the specified MIME type and file format. The encoded contents are /// then stored to the payload of the record, the MIME type is set as the type of the record. /// </remarks> /// <param name="bmp">Input bitmap to encode and set as payload of this record.</param> /// <param name="mimeType">MIME type to use for encoding this image.</param> /// <param name="dpi">Target DPI if supported by the target file / MIME format.</param> /// <returns>Task to await completion of the asynchronous image encoding.</returns> public async Task SetImage(WriteableBitmap bmp, ImageMimeType mimeType, double dpi = 96.0) { var encoderId = GetBitmapEncoderIdForMimeType(mimeType); byte[] pixels; using (var stream = bmp.PixelBuffer.AsStream()) { pixels = new byte[(uint)stream.Length]; await stream.ReadAsync(pixels, 0, pixels.Length); } using (var imgStream = new MemoryStream()) { var raImgStream = imgStream.AsRandomAccessStream(); var encoder = await BitmapEncoder.CreateAsync(encoderId, raImgStream); encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied, (uint)bmp.PixelWidth, (uint)bmp.PixelHeight, dpi, dpi, pixels); await encoder.FlushAsync(); await raImgStream.FlushAsync(); Payload = imgStream.ToArray(); Type = ImageMimeTypes[mimeType]; } }
public async Task<BitmapImage> GetPhotoAsync(string userId, string token) { BitmapImage bitmap = null; var restURL = string.Format("{0}/users/{1}/photo/$value", AuthenticationHelper.ResourceBetaUrl, userId); var accessToken = AuthenticationHelper.AccessToken; using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); using (var response = await client.GetAsync(restURL)) { if (response.IsSuccessStatusCode) { Stream imageStream = await response.Content.ReadAsStreamAsync(); var memStream = new MemoryStream(); await imageStream.CopyToAsync(memStream); memStream.Position = 0; bitmap = new BitmapImage(); await bitmap.SetSourceAsync(memStream.AsRandomAccessStream()); } if (bitmap == null) { Debug.WriteLine("Unable to find an image at this endpoint."); bitmap = new BitmapImage(new Uri("ms-appx:///assets/UserDefault.png", UriKind.RelativeOrAbsolute)); } return bitmap; } } }
private static void LoadImage(Image image, Uri uri) #endif { if (uri == null) { image.Source = null; return; } try { #if WINRT var handler = new HttpClientHandler(); if (uri is AuthenticatedUri) handler.Credentials = ((AuthenticatedUri) uri).Credentials; var client = new HttpClient(handler); var stream = await client.GetStreamAsync(uri); var source = new BitmapImage(); image.Source = source; using (var memoryStream = new MemoryStream(stream.ReadToEnd())) source.SetSourceAsync(memoryStream.AsRandomAccessStream()); #else var request = WebRequest.CreateHttp(uri); if (uri is AuthenticatedUri) request.Credentials = ((AuthenticatedUri) uri).Credentials; request.AllowReadStreamBuffering = true; request.BeginGetResponse(asyncResult => { try { var response = (HttpWebResponse) request.EndGetResponse(asyncResult); image.Dispatcher.BeginInvoke(delegate { var source = new BitmapImage(); source.SetSource(response.GetResponseStream()); image.Source = source; }); } catch { image.Dispatcher.BeginInvoke(delegate { image.Source = new BitmapImage(new Uri("http://0.0.0.0")); // Trigger ImageFailed event }); } }, null); #endif } catch { image.Source = new BitmapImage(new Uri("http://0.0.0.0")); // Trigger ImageFailed event } }
private async Task<ContentTypeEnum> DetectContentType(byte[] binaryData) { var contentType = ContentTypeEnum.ContentTypeUnknown; try { using (MemoryStream imgStream = new MemoryStream(binaryData)) { var image = await BitmapDecoder.CreateAsync(imgStream.AsRandomAccessStream()); var ct = image.DecoderInformation.MimeTypes.First(); switch (ct) { case "image/jpg": contentType = ContentTypeEnum.ContentTypeJpeg; break; case "image/png": contentType = ContentTypeEnum.ContentTypePng; break; case "image/gif": contentType = ContentTypeEnum.ContentTypeGif; break; default: contentType = ContentTypeEnum.ContentTypeUnknown; break; } //using (Bitmap bitmap = new Bitmap(imgStream)) // { // if (bitmap.RawFormat.Equals(ImageFormat.Jpeg)) // { // contentType = ContentTypeEnum.ContentTypeJpeg; // } // else if (bitmap.RawFormat.Equals(ImageFormat.Png)) // { // contentType = ContentTypeEnum.ContentTypePng; // } // else if (bitmap.RawFormat.Equals(ImageFormat.Gif)) // { // contentType = ContentTypeEnum.ContentTypeGif; // } // } } } catch (Exception ex) { throw new Exception(string.Format("Error during image type detection: {0}",ex),ex); } return contentType; }
/// <summary> /// /// </summary> /// <param name="key"></param> /// <returns></returns> private async Task CacheImage(string key) { var bytes = _context.Renderers[0].State.ImageCache.GetImage(key); if (bytes != null) { using (var ms = new MemoryStream(bytes)) { using (var ras = ms.AsRandomAccessStream()) { var bi = await CanvasBitmap.LoadAsync(canvas, ras); _renderer.CacheImage(key, bi); ras.Dispose(); } } } }
/// <summary> /// liest eine Bilddatei und gibt das ensprechande Bitmap-Objekt zurück /// </summary> /// <param name="fileName">Name der Bilddateie, welche geladen werden soll</param> /// <returns>fertig geladenes Bild</returns> public static async Task<WriteableBitmap> ReadBitmapAsync(string fileName) { var data = await ReadAllBytesAsync(fileName); var size = GetBildGröße(data); var memStream = new MemoryStream(); await memStream.WriteAsync(data, 0, data.Length); memStream.Position = 0; var result = new WriteableBitmap(size.w, size.h); result.SetSource(memStream.AsRandomAccessStream()); return result; }