/// <summary> /// Asynchronously saves the <paramref name="photo" /> given to the camera roll album. /// </summary> /// <param name="photo">Photo to save.</param> /// <returns>Image with thumbnail.</returns> /// <exception cref="ArgumentNullException"><paramref name="photo"/> is <see langword="null"/>.</exception> public async Task<IThumbnailedImage> SaveResultToCameraRollAsync(ICapturedPhoto photo) { if (photo == null) { throw new ArgumentNullException("photo"); } Tracing.Trace("StorageService: Trying to save picture to the Camera Roll."); Picture cameraRollPicture; string name = this.GeneratePhotoName(); using (InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream()) { // Convert image to JPEG format and rotate in accordance with the original photo orientation. Tracing.Trace("StorageService: Converting photo to JPEG format. Size: {0}x{1}, Rotation: {2}", photo.Width, photo.Height, photo.Rotation); byte[] pixelData = await photo.DetachPixelDataAsync(); BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream); encoder.BitmapTransform.Rotation = photo.Rotation; encoder.BitmapTransform.Flip = photo.Flip; encoder.IsThumbnailGenerated = true; encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, photo.Width, photo.Height, Constants.DefaultDpiX, Constants.DefaultDpiY, pixelData); await encoder.FlushAsync(); cameraRollPicture = this.lazyMediaLibrary.Value.SavePictureToCameraRoll(name, stream.AsStream()); } Tracing.Trace("StorageService: Saved to Camera Roll as {0}", name); return new MediaLibraryThumbnailedImage(cameraRollPicture); }
internal static Bitmap FromStream(Stream stream) { Bitmap bitmap = null; Task.Run(async () => { using (var raStream = new InMemoryRandomAccessStream()) { await stream.CopyToAsync(raStream.AsStream()); var decoder = await BitmapDecoder.CreateAsync(raStream); var pixelData = await decoder.GetPixelDataAsync(); var width = (int)decoder.OrientedPixelWidth; var height = (int)decoder.OrientedPixelHeight; const PixelFormat format = PixelFormat.Format32bppArgb; var bytes = pixelData.DetachPixelData(); bitmap = new Bitmap(width, height, format); var data = bitmap.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite, format); Marshal.Copy(bytes, 0, data.Scan0, bytes.Length); bitmap.UnlockBits(data); } }).Wait(); return bitmap; }
void manager_DataRequested(DataTransferManager sender, DataRequestedEventArgs args) { // do the basics... var data = args.Request.Data; data.Properties.Title = "Deferred image"; data.Properties.Description = "I'll have to be downloaded first!"; // get a deferral... data.SetDataProvider(StandardDataFormats.Bitmap, async (request) => { var deferral = request.GetDeferral(); try { // download... using (var inStream = await new HttpClient().GetStreamAsync("http://streetfoo.apphb.com/images/graffiti00.jpg")) { // copy the stream... but we'll need to obtain a facade // to map between WinRT and .NET... var outStream = new InMemoryRandomAccessStream(); inStream.CopyTo(outStream.AsStream()); // send that... var reference = RandomAccessStreamReference.CreateFromStream(outStream); request.SetData(reference); } } finally { deferral.Complete(); } }); }
public static IRandomAccessStream AsRandomAccessStream(this Stream stream) { // This is bad, as we are reading the whole input stream in memory, but better than nothing. var randomStream = new InMemoryRandomAccessStream(); stream.CopyTo(randomStream.AsStream()); randomStream.Seek(0); return randomStream; }
private async void Run() { await _HubConnection.Start(); var cam = new MediaCapture(); await cam.InitializeAsync(new MediaCaptureInitializationSettings() { MediaCategory = MediaCategory.Media, StreamingCaptureMode = StreamingCaptureMode.Video }); _Sensor.MotionDetected += async (int pinNum) => { var stream = new InMemoryRandomAccessStream(); Stream imageStream = null; try { await Task.Factory.StartNew(async () => { _Sensor.IsActive = false; await cam.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), stream); stream.Seek(0); imageStream = stream.AsStream(); imageStream.Seek(0, SeekOrigin.Begin); string imageUrl = await NotificationHelper.UploadImageAsync(imageStream); switch (await OxfordHelper.IdentifyAsync(imageUrl)) { case AuthenticationResult.IsOwner: // open the door MotorController.PWM(26); break; case AuthenticationResult.Unkown: // send notification to the owner NotificationHelper.NotifyOwnerAsync(imageUrl); break; case AuthenticationResult.None: default: break; } _Sensor.IsActive = true; }); } finally { if (stream != null) stream.Dispose(); if (imageStream != null) imageStream.Dispose(); } }; }
public static async Task<string> EncodeFromByte(byte[] image, uint height, uint width, double dpiX = 96, double dpiY = 96) { // encode image var encoded = new InMemoryRandomAccessStream(); var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, encoded); encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight, height, width, dpiX, dpiY, image); await encoder.FlushAsync(); encoded.Seek(0); // read bytes var bytes = new byte[encoded.Size]; await encoded.AsStream().ReadAsync(bytes, 0, bytes.Length); // create base64 return Convert.ToBase64String(bytes); }
/// <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()"); }
public async Task<PortableImage> ResizeImage(PortableImage image, int newWidth, int newHeight) { BitmapDecoder decoder = await BitmapDecoder.CreateAsync(((Stream)image.EncodedData).AsRandomAccessStream()); var memoryRandomAccessStream = new InMemoryRandomAccessStream(); BitmapEncoder encoder = await BitmapEncoder.CreateForTranscodingAsync(memoryRandomAccessStream, decoder); encoder.BitmapTransform.ScaledHeight = (uint)newHeight; encoder.BitmapTransform.ScaledWidth = (uint)newWidth; //var bounds = new BitmapBounds(); //bounds.Height = 50; //bounds.Width = 50; //bounds.X = 50; //bounds.Y = 50; //enc.BitmapTransform.Bounds = bounds; try { await encoder.FlushAsync(); } catch (Exception exc) { var message = "Error on resizing the image: "; if (exc.Message != null) message += exc.Message; throw new Exception(message); } //var writeableBitmap = new WriteableBitmap(newWidth, newHeight); //writeableBitmap.SetSourceAsync(memoryRandomAccessStream); memoryRandomAccessStream.Seek(0); return new PortableImage { Width = newWidth, Height = newHeight, EncodedData = memoryRandomAccessStream.AsStream() }; }
private void play(double note) { MediaElement playback = new MediaElement(); IRandomAccessStream stream = new InMemoryRandomAccessStream(); BinaryWriter writer = new BinaryWriter(stream.AsStream()); int formatChunkSize = 16; int headerSize = 8; short formatType = 1; short tracks = 1; int samplesPerSecond = 44100; short bitsPerSample = 16; short frameSize = (short)(tracks * ((bitsPerSample + 7) / 8)); int bytesPerSecond = samplesPerSecond * frameSize; int waveSize = 4; int data = 0x61746164; int samples = 88200 * 4; int dataChunkSize = samples * frameSize; int fileSize = waveSize + headerSize + formatChunkSize + headerSize + dataChunkSize; double frequency = note * 1.5; writer.Write(0x46464952); // RIFF writer.Write(fileSize); writer.Write(0x45564157); // WAVE writer.Write(0x20746D66); // Format writer.Write(formatChunkSize); writer.Write(formatType); writer.Write(tracks); writer.Write(samplesPerSecond); writer.Write(bytesPerSecond); writer.Write(frameSize); writer.Write(bitsPerSample); writer.Write(data); writer.Write(dataChunkSize); for (int i = 0; i < samples / 4; i++) { double t = (double)i / (double)samplesPerSecond; short s = (short)(10000 * (Math.Sin(t * frequency * 2.0 * Math.PI))); writer.Write(s); } stream.Seek(0); playback.SetSource(stream, "audio/wav"); playback.Play(); }
private async void btnTakePhoto_Click(object sender, RoutedEventArgs e) { btnTakePhoto.IsEnabled = false; btnStartPreview.IsEnabled = false; InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream(); await mediaCapture.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), stream); stream.Seek(0); BitmapImage bitmap = new BitmapImage(); bitmap.SetSource(stream); captureImage.Source = bitmap; stream.Seek(0); Stream st = stream.AsStream(); if (isPreviewing == true) await mediaCapture.StopPreviewAsync(); isPreviewing = false; previewElement.Visibility = Visibility.Collapsed; progring.IsActive = true; try { EmotionServiceClient emotionServiceClient = new EmotionServiceClient("12345678901234567890123456789012"); // replace 12345678901234567890123456789012 with your key taken from https://www.projectoxford.ai/Subscription/ emotionResult = await emotionServiceClient.RecognizeAsync(st); } catch { } progring.IsActive = false; if ((emotionResult != null) && (emotionResult.Length > 0)) { emo.Clear(); emo.Add(emotionResult[0]); this.DataContext = emo.ElementAt(0); } btnStartPreview.IsEnabled = true; btnTakePhoto.IsEnabled = true; }
private async Task DetectPhotoAsync(IRandomAccessStream stream, PhotoOrientation photoOrientation) { using (var inputStream = stream) { var decoder = await BitmapDecoder.CreateAsync(inputStream); var file = await KnownFolders.PicturesLibrary.CreateFileAsync("SimplePhoto.jpeg", CreationCollisionOption.GenerateUniqueName); using (var outputStream = new InMemoryRandomAccessStream()) { var encoder = await BitmapEncoder.CreateForTranscodingAsync(outputStream, decoder); var properties = new BitmapPropertySet { { "System.Photo.Orientation", new BitmapTypedValue(photoOrientation, PropertyType.UInt16) } }; await encoder.BitmapProperties.SetPropertiesAsync(properties); await encoder.FlushAsync(); var faces = await _instance.DetectAsync(outputStream.AsStream(), false, true, true, false); } } }
/// <summary> /// Start recording a new video and save it as stream. /// </summary> /// <param name="encoding">The video encoding. Mp4 by default.</param> /// <returns>The <see cref="VideoCaptureStreamResult"/> struct.</returns> public async Task<VideoCaptureStreamResult> StartRecordingToStreamAsync(VideoEncoding encoding) { if (!this.isInitialized) { Debug.WriteLine("First you need to initialize the videocapturemanager."); return new VideoCaptureStreamResult(); } if (this.IsRecording) { Debug.WriteLine("VideoCapture is already recording. Call Stop before Start again."); return new VideoCaptureStreamResult(false, Stream.Null); } try { Debug.WriteLine("Recording video..."); MediaEncodingProfile encodingProfile; switch (encoding) { case VideoEncoding.AVI: encodingProfile = MediaEncodingProfile.CreateMp4(VideoEncodingQuality.Auto); break; case VideoEncoding.WMV: encodingProfile = MediaEncodingProfile.CreateWmv(VideoEncodingQuality.Auto); break; default: case VideoEncoding.MP4: encodingProfile = MediaEncodingProfile.CreateAvi(VideoEncodingQuality.Auto); break; } var stream = new InMemoryRandomAccessStream(); await this.mediaCapture.StartRecordToStreamAsync(encodingProfile, stream); this.isRecording = true; return new VideoCaptureStreamResult(true, stream.AsStream()); } catch (Exception ex) { Debug.WriteLine("Exception when recording a video: " + ex.ToString()); return new VideoCaptureStreamResult(false, Stream.Null); } }
/// <summary> /// Take a new photo and hold it in the output stream. /// </summary> /// <param name="parameters">The set of parameters used to take the photo, <see cref="ICameraResolution"/> class.</param> /// <param name="format">The image format. <see cref="PhotoCaptureFormat"/> enum. </param> /// <returns>The <see cref="PhotoCaptureStreamResult"/> struct.</returns> public async Task<PhotoCaptureStreamResult> TakePhotoToStreamAsync(ICameraResolution parameters, PhotoCaptureFormat format) { if (!this.isInitialized) { Debug.WriteLine("First you need to initialize the videocapturemanager."); return new PhotoCaptureStreamResult(); } try { if (parameters != null) { Debug.WriteLine("Applying paramenters..."); await this.mediaCapture.VideoDeviceController.SetMediaStreamPropertiesAsync(MediaStreamType.Photo, (parameters as StreamResolution).EncodingProperties); } Debug.WriteLine("Taking photo..."); var stream = new InMemoryRandomAccessStream(); var properties = this.GetImageEncodingProperties(format); await this.mediaCapture.CapturePhotoToStreamAsync(properties, stream); Debug.WriteLine("Photo stream loaded."); return new PhotoCaptureStreamResult(true, stream.AsStream()); } catch (Exception ex) { Debug.WriteLine("Exception when taking a photo: " + ex.ToString()); return new PhotoCaptureStreamResult(false, Stream.Null); } }
/// <summary> /// resizes the image so it can go through VMHub processing /// </summary> /// <param name="ms"></param> /// <param name="maxImageSize"></param> /// <returns></returns> async private Task<byte[]> ResizeImage(MemoryStream ms, uint maxImageSize) { MemoryStream temp = ms; IRandomAccessStream ras = temp.AsRandomAccessStream(); BitmapDecoder decoder = await BitmapDecoder.CreateAsync(ras).AsTask().ConfigureAwait(false); uint w = decoder.PixelWidth, h = decoder.PixelHeight; if (w > maxImageSize || h > maxImageSize) { if (w > h) { w = maxImageSize; h = decoder.PixelHeight * maxImageSize / decoder.PixelWidth; } else { w = decoder.PixelWidth * maxImageSize / decoder.PixelHeight; h = maxImageSize; } } BitmapTransform transform = new BitmapTransform() { ScaledHeight = h, ScaledWidth = w }; PixelDataProvider pixelData = await decoder.GetPixelDataAsync( BitmapPixelFormat.Rgba8, BitmapAlphaMode.Premultiplied, transform, ExifOrientationMode.RespectExifOrientation, ColorManagementMode.DoNotColorManage); byte[] pixels = pixelData.DetachPixelData(); InMemoryRandomAccessStream encoded = new InMemoryRandomAccessStream(); BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, encoded); encoder.SetPixelData(BitmapPixelFormat.Rgba8, BitmapAlphaMode.Premultiplied, w, h, 96, 96, pixels); await encoder.FlushAsync().AsTask().ConfigureAwait(false); encoded.Seek(0); byte[] outBytes = new byte[encoded.Size]; await encoded.AsStream().ReadAsync(outBytes, 0, outBytes.Length); return outBytes; }
public async Task<string> RenderToBase64(UIElement element) { RenderTargetBitmap rtb = new RenderTargetBitmap(); await rtb.RenderAsync(element); var pixelBuffer = await rtb.GetPixelsAsync(); var pixels = pixelBuffer.ToArray(); // Useful for rendering in the correct DPI var displayInformation = DisplayInformation.GetForCurrentView(); var stream = new InMemoryRandomAccessStream(); var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, stream); encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied, (uint)rtb.PixelWidth, (uint)rtb.PixelHeight, displayInformation.RawDpiX, displayInformation.RawDpiY, pixels); await encoder.FlushAsync(); stream.Seek(0); // read bytes var bytes = new byte[stream.Size]; await stream.AsStream().ReadAsync(bytes, 0, bytes.Length); // create base64 return Convert.ToBase64String(bytes); }
/// <summary> /// rotates the image by the currentRotation value /// </summary> /// <param name="mrs">InMemoryRandomAccessStream containg the image data</param> /// <returns>byte [] to be sent through processing</returns> async private Task<byte[]> RotateImage(InMemoryRandomAccessStream mrs) { BitmapDecoder decoder = await BitmapDecoder.CreateAsync(mrs).AsTask().ConfigureAwait(false); uint w = decoder.PixelWidth; uint h = decoder.PixelHeight; if (currentRotation.Equals(VideoRotation.Clockwise90Degrees) || currentRotation.Equals(VideoRotation.Clockwise270Degrees)) { w = decoder.PixelHeight; h = decoder.PixelWidth; } BitmapTransform transform = new BitmapTransform() { Rotation = (BitmapRotation)currentRotation }; PixelDataProvider pixelData = await decoder.GetPixelDataAsync( BitmapPixelFormat.Rgba8, BitmapAlphaMode.Premultiplied, transform, ExifOrientationMode.RespectExifOrientation, ColorManagementMode.DoNotColorManage); byte[] pixels = pixelData.DetachPixelData(); BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, mrs); encoder.SetPixelData(BitmapPixelFormat.Rgba8, BitmapAlphaMode.Premultiplied, w, h, 96, 96, pixels); await encoder.FlushAsync().AsTask().ConfigureAwait(false); mrs.Seek(0); byte[] outBytes = new byte[mrs.Size]; await mrs.AsStream().ReadAsync(outBytes, 0, outBytes.Length); MemoryStream ms = new MemoryStream(outBytes); var currentApp = (App)App.Current; currentApp.CurrentImageRecog = ms; return outBytes; }
public async Task<Stream> ToStreamAsync() { #if __ANDROID__ var native = ToBitmap(); var stream = new MemoryStream(); if (await native.CompressAsync(NativeBitmap.CompressFormat.Png, 0, stream)) { stream.Position = 0; return stream; } return null; #elif __IOS__ var native = ToUIImage(); return native.AsPNG().AsStream(); #elif WINDOWS_PHONE_APP var native = ToWriteableBitmap(); var stream = new InMemoryRandomAccessStream(); var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, stream); using (Stream pixelStream = native.PixelBuffer.AsStream()) { byte[] pixels = new byte[pixelStream.Length]; await pixelStream.ReadAsync(pixels, 0, pixels.Length); encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight, (uint)native.PixelWidth, (uint)native.PixelHeight, 96.0, 96.0, pixels); await encoder.FlushAsync(); } return stream.AsStream(); #else // PORTABLE return null; #endif }
private async Task<IRandomAccessStreamReference> GetMapIconDonutImage(Grid drawingContainer, ParkingLot lot) { var drawDonut = new ParkingLotLoadDonut { Animate = false, ParkingLot = lot, Style = Application.Current.Resources["ParkingLotMapIconDonutStyle"] as Style }; drawingContainer.Children.Add(drawDonut); var rtb = new RenderTargetBitmap(); await rtb.RenderAsync(drawDonut); drawingContainer.Children.Remove(drawDonut); //TODO: take care of possible scaling issues var pixels = (await rtb.GetPixelsAsync()).ToArray(); var stream = new InMemoryRandomAccessStream(); var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.BmpEncoderId, stream); encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight, (uint)rtb.PixelWidth, (uint)rtb.PixelHeight, 96, 96, pixels); await encoder.FlushAsync(); stream.Seek(0); return RandomAccessStreamReference.CreateFromStream(stream.AsStream().AsRandomAccessStream()); }
protected static async void save(byte[] inData, int width, int height, Stream outStream, ImageFormats imageFormat, ImageSavedCallbackMethod imageSavedCallback) { try { using (var memoryStream = new InMemoryRandomAccessStream()) { Guid encodeID = new Guid(); switch (imageFormat) { case (ImageFormats.PNG): encodeID = BitmapEncoder.PngEncoderId; break; case (ImageFormats.JPG): encodeID = BitmapEncoder.PngEncoderId; break; case (ImageFormats.BMP): encodeID = BitmapEncoder.PngEncoderId; break; default: Debug.ThrowError("ImageMetro", "Unsuported image format: " + imageFormat.ToString()); break; } BitmapEncoder encoder = await BitmapEncoder.CreateAsync(encodeID, memoryStream); encoder.SetPixelData(BitmapPixelFormat.Rgba8, BitmapAlphaMode.Straight, (uint)width, (uint)height, 96, 96, inData); await encoder.FlushAsync(); var stream = memoryStream.AsStream(); stream.Position = 0; await stream.CopyToAsync(outStream); } } catch (Exception e) { if (imageSavedCallback != null) imageSavedCallback(false); } if (imageSavedCallback != null) imageSavedCallback(true); }
/// <summary> /// Decodes the supplied encoded bitmap data into an array of pixels. /// For internal use only. /// </summary> public async Task<byte[]> DecodeAsync(byte[] encodedBytes) { #if NETFX_CORE using (var ras = new InMemoryRandomAccessStream()) { await ras.AsStream().WriteAsync(encodedBytes, 0, encodedBytes.Length); ras.Seek(0); var dec = await BitmapDecoder.CreateAsync(BitmapDecoder.JpegDecoderId, ras); var pixelDataProvider = await dec.GetPixelDataAsync(); return pixelDataProvider.DetachPixelData(); } #else using (var str = new MemoryStream()) { str.Write(encodedBytes, 0, encodedBytes.Length); str.Position = 0; var dec = new JpegBitmapDecoder(str, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad); var frame = dec.Frames[0]; this.PixelFormat = frame.Format; var bpp = frame.Format.BitsPerPixel / 8; var stride = bpp * frame.PixelWidth; var size = stride * frame.PixelHeight; var output = new byte[size]; frame.CopyPixels(output, stride, 0); return await Task.FromResult(output); } #endif }
/// <summary> /// Retrieves the signature image from the canvas /// </summary> /// <param name="imgFormat"></param> /// <returns></returns> public Stream GetImage(ImageFormatType imgFormat) { var imageTask = Task.Run(async () => { //Create new Random Access Tream var stream = new InMemoryRandomAccessStream(); //Create bitmap encoder var encoder = await BitmapEncoder.CreateAsync( imgFormat == ImageFormatType.Png ? BitmapEncoder.PngEncoderId : BitmapEncoder.JpegEncoderId, stream); //Set the pixel data and flush it encoder.SetPixelData( BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight, (uint)bitmapInfo.PixelWidth, (uint)bitmapInfo.PixelHeight, 96d, 96d, bitmapInfo.BitmapBuffer.ToArray()); await encoder.FlushAsync(); return stream.AsStream(); }); imageTask.Wait(); return imageTask.Result; }
public async Task Save(CompressedBitmapFormat format, float quality, Stream target) { // NB: Due to WinRT's brain-dead design, we're copying this image // like three times. Let Dreams Soar. var rwTarget = new InMemoryRandomAccessStream(); var fmt = format == CompressedBitmapFormat.Jpeg ? BitmapEncoder.PngEncoderId : BitmapEncoder.JpegEncoderId; var encoder = await BitmapEncoder.CreateAsync(fmt, rwTarget, new[] { new KeyValuePair<string, BitmapTypedValue>("ImageQuality", new BitmapTypedValue(quality, PropertyType.Single)) }); var pixels = new byte[inner.PixelBuffer.Length]; await inner.PixelBuffer.AsStream().ReadAsync(pixels, 0, (int)inner.PixelBuffer.Length); encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied, (uint)inner.PixelWidth, (uint)inner.PixelHeight, 96, 96, pixels); await encoder.FlushAsync(); await rwTarget.AsStream().CopyToAsync(target); }
private static async Task<Stream> resizeImageStream(IRandomAccessStream imageStream, int maxWidth, int maxHeight) #endif { #if WINDOWS_PHONE var image = new BitmapImage(); image.CreateOptions = BitmapCreateOptions.None; image.SetSource(imageStream); var scaledStream = new MemoryStream(); var newImage = new WriteableBitmap(image); Vector2 newSize; if (image.PixelWidth > maxWidth || image.PixelHeight > maxHeight) newSize = Reign.MathUtilities.FitInViewIfLarger(newImage.PixelWidth, newImage.PixelHeight, maxWidth, maxHeight); else newSize = new Vector2(image.PixelWidth, image.PixelHeight); newImage.SaveJpeg(scaledStream, (int)newSize.x, (int)newSize.y, 0, 95); scaledStream.Position = 0; return scaledStream; #else var decoder = await BitmapDecoder.CreateAsync(imageStream); var newStream = new InMemoryRandomAccessStream(); var encoder = await BitmapEncoder.CreateForTranscodingAsync(newStream, decoder); Vector2 newSize; if (decoder.PixelWidth > maxWidth || decoder.PixelHeight > maxHeight) newSize = Reign.MathUtilities.FitInViewIfLarger(decoder.PixelWidth, decoder.PixelHeight, maxWidth, maxHeight); else newSize = new Vector2(decoder.PixelWidth, decoder.PixelHeight); encoder.BitmapTransform.ScaledWidth = (uint)newSize.x; encoder.BitmapTransform.ScaledHeight = (uint)newSize.y; await encoder.FlushAsync(); return newStream.AsStream(); #endif }
private async Task<Stream> ConvertToJpeg(IRandomAccessStream stream) { var decoder = await BitmapDecoder.CreateAsync(stream); var pixels = await decoder.GetPixelDataAsync(); var outStream = new InMemoryRandomAccessStream(); // create encoder for saving the tile image var propertySet = new BitmapPropertySet(); // create class representing target jpeg quality - a bit obscure, but it works var qualityValue = new BitmapTypedValue(.7, PropertyType.Single); propertySet.Add("ImageQuality", qualityValue); var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, outStream); encoder.SetPixelData(decoder.BitmapPixelFormat, BitmapAlphaMode.Ignore, decoder.OrientedPixelWidth, decoder.OrientedPixelHeight, decoder.DpiX, decoder.DpiY, pixels.DetachPixelData()); await encoder.FlushAsync(); return outStream.AsStream(); }
public async Task<IRandomAccessStream> DownloadPDFAsync(LibrelioLocalUrl magUrl, StorageFolder folder, IProgress<int> progress = null, CancellationToken cancelToken = default(CancellationToken)) { HttpClient client = new HttpClient(); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, magUrl.Url); int read = 0; int offset = 0; byte[] responseBuffer = new byte[1024]; var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancelToken); response.EnsureSuccessStatusCode(); var length = response.Content.Headers.ContentLength; cancelToken.ThrowIfCancellationRequested(); var stream = new InMemoryRandomAccessStream(); using (var responseStream = await response.Content.ReadAsStreamAsync()) { do { cancelToken.ThrowIfCancellationRequested(); read = await responseStream.ReadAsync(responseBuffer, 0, responseBuffer.Length); cancelToken.ThrowIfCancellationRequested(); await stream.AsStream().WriteAsync(responseBuffer, 0, read); offset += read; uint val = (uint)(offset * 100 / length); if (val >= 100) val = 99; if (val <= 0) val = 1; progress.Report((int)val); } while (read != 0); } progress.Report(100); await stream.FlushAsync(); //var folder = await AddMagazineFolderStructure(magUrl); //var folder = await StorageFolder.GetFolderFromPathAsync(folderUrl); var file = await folder.CreateFileAsync(magUrl.FullName, CreationCollisionOption.ReplaceExisting); using (var protectedStream = await DownloadManager.ProtectPDFStream(stream)) using (var fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite)) //using (var unprotectedStream = await DownloadManager.UnprotectPDFStream(protectedStream)) { await RandomAccessStream.CopyAsync(protectedStream, fileStream.GetOutputStreamAt(0)); await fileStream.FlushAsync(); } var pdfStream = new MagazineData(); pdfStream.folderUrl = folder.Path + "\\"; pdfStream.stream = stream; //var fileHandle = // await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(@"Assets\test\testmagazine.pdf"); //pdfStream.folderUrl = "C:\\Users\\Dorin\\Documents\\Magazines\\wind_355\\"; //pdfStream.stream = await fileHandle.OpenReadAsync(); return pdfStream.stream; }