public async Task<SoftwareBitmap> ConvertToSoftwareBitmap(Stream stream) { BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream.AsRandomAccessStream()); SoftwareBitmap softwareBitmap = await decoder.GetSoftwareBitmapAsync(); SoftwareBitmap softwareBitmapBGR8 = SoftwareBitmap.Convert(softwareBitmap, BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied); return softwareBitmapBGR8; }
private async void SelectImage(object sender, RoutedEventArgs e) { var picker = new FileOpenPicker(); picker.ViewMode = PickerViewMode.Thumbnail; picker.SuggestedStartLocation = PickerLocationId.PicturesLibrary; picker.FileTypeFilter.Add(".jpg"); picker.FileTypeFilter.Add(".jpeg"); picker.FileTypeFilter.Add(".png"); StorageFile file = await picker.PickSingleFileAsync(); if (file != null) { Stream imagestream = await file.OpenStreamForReadAsync(); BitmapDecoder dec = await BitmapDecoder.CreateAsync(imagestream.AsRandomAccessStream()); imageHeight = (int)dec.PixelHeight; imageWidth = (int)dec.PixelWidth; var data = await dec.GetPixelDataAsync(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, new BitmapTransform(), ExifOrientationMode.IgnoreExifOrientation, ColorManagementMode.DoNotColorManage); var bytes = data.DetachPixelData(); imageData = new byte[imageWidth, imageHeight, 4]; Buffer.BlockCopy(bytes, 0, imageData, 0, bytes.Length); BitmapImage bitmap = new BitmapImage(); bitmap.SetSource(imagestream.AsRandomAccessStream()); ((MainPageViewModel)DataContext).OrginalImageSource = bitmap; await new MessageDialog($"Your texture was successfully loaded.", "Success!").ShowAsync(); } }
public void Save(Stream stream, ImageFormat format = ImageFormat.Png, float quality = 1) { switch (format) { case ImageFormat.Jpeg: AsyncPump.Run(async() => await _bitmap.SaveAsync(stream.AsRandomAccessStream(), CanvasBitmapFileFormat.Jpeg, quality)); break; default: AsyncPump.Run(async() => await _bitmap.SaveAsync(stream.AsRandomAccessStream(), CanvasBitmapFileFormat.Png)); break; } }
public async Task SaveAsync(Stream stream, ImageFormat format = ImageFormat.Png, float quality = 1) { switch (format) { case ImageFormat.Jpeg: await _bitmap.SaveAsync(stream.AsRandomAccessStream(), CanvasBitmapFileFormat.Jpeg, quality); break; default: await _bitmap.SaveAsync(stream.AsRandomAccessStream(), CanvasBitmapFileFormat.Png); break; } }
private async Task CreateDefaultImage() { var imageWidth = ServiceLocator.SystemInformationService.ScreenWidth; var imageHeight = ServiceLocator.SystemInformationService.ScreenHeight; using (var storage = StorageSystem.GetStorage()) { await storage.DeleteFileAsync(StorageConstants.TempPaintImagePath); Stream stream = await storage.OpenFileAsync(StorageConstants.TempPaintImagePath, StorageFileMode.Create, StorageFileAccess.Write); BitmapEncoder encoder = await BitmapEncoder.CreateAsync( BitmapEncoder.PngEncoderId, stream.AsRandomAccessStream()); Byte[] pixels = new byte[imageWidth * imageHeight * 4]; for (var pixelStart = 0; pixelStart < pixels.Length; pixelStart += 4) { pixels[pixelStart + 0] = 0xAA; // Full transparent: 0x00 pixels[pixelStart + 1] = 0xAA; pixels[pixelStart + 2] = 0xAA; pixels[pixelStart + 3] = 0xAA; } encoder.SetPixelData(BitmapPixelFormat.Rgba8, BitmapAlphaMode.Straight, (uint)imageWidth, (uint)imageHeight, 96, 96, pixels); await encoder.FlushAsync(); } }
public async static Task <string> DownloadImageForTile(string uriString) { Uri imageUri = new Uri(GetRemoteUri(uriString)); using (Stream stream = await GetImageStreamAsync(imageUri)) { using (IRandomAccessStream inStream = stream.AsRandomAccessStream()) { // BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream.AsRandomAccessStream()); var ras = await ResizeImage(inStream, 1024, 1024); //BitmapEncoder encoder = await BitmapEncoder.CreateForTranscodingAsync(ras, decoder); //encoder.BitmapTransform.ScaledWidth = 1024; //encoder.BitmapTransform.sc //await encoder.FlushAsync(); string fileName = "tile.tmp"; var file = await(await ApplicationData.Current.LocalFolder.CreateFolderAsync("Tiles", CreationCollisionOption.OpenIfExists)).CreateFileAsync(fileName, CreationCollisionOption.GenerateUniqueName); using (var reader = new DataReader(ras)) { await reader.LoadAsync((uint)ras.Size); var buffer = new byte[(int)ras.Size]; reader.ReadBytes(buffer); await Windows.Storage.FileIO.WriteBytesAsync(file, buffer); } return(file.Path); } } }
public async Task LoadMe() { // Get user info var result = await httpClient.GetAsync("https://graph.microsoft.com/v1.0/me/"); var json = await result.Content.ReadAsStringAsync(); var jsonObject = JsonObject.Parse(json); ProfileDisplayName = jsonObject.GetNamedString("displayName"); ProfileEmail = jsonObject.GetNamedString("userPrincipalName"); // Get photo data var photo = await httpClient.GetAsync("https://graph.microsoft.com/beta/me/photo/$value"); Stream photoStream = await photo.Content.ReadAsStreamAsync(); using (var ras = photoStream.AsRandomAccessStream()) { BitmapImage bitmapImage = new BitmapImage(); await bitmapImage.SetSourceAsync(ras); ProfileImageSource = bitmapImage; } }
public async Task <ImageInfo> DecodeAsync(Stream imageStream) { var output = default(ImageInfo); try { var decoder = await BitmapDecoder.CreateAsync(imageStream.AsRandomAccessStream()).AsTask().ConfigureAwait(false); var codecId = decoder.DecoderInformation.CodecId; if (codecId == BitmapDecoder.BmpDecoderId) { output = ImageInfo.Bmp((int)decoder.PixelWidth, (int)decoder.PixelHeight); } else if (codecId == BitmapDecoder.GifDecoderId) { output = ImageInfo.Gif((int)decoder.PixelWidth, (int)decoder.PixelHeight); } else if (codecId == BitmapDecoder.JpegDecoderId) { output = ImageInfo.Jpeg((int)decoder.PixelWidth, (int)decoder.PixelHeight); } else if (codecId == BitmapDecoder.PngDecoderId) { output = ImageInfo.Png((int)decoder.PixelWidth, (int)decoder.PixelHeight); } } catch { output = null; } return(output); }
private static async Task <Tuple <double, double> > ResizePhoto(Stream photo, int height, IRandomAccessStream resultStream) { WriteableBitmap wb = new WriteableBitmap(1, 1); wb = await wb.FromStream(photo.AsRandomAccessStream()); int originalWidth = wb.PixelWidth; int originalHeight = wb.PixelHeight; if (wb.PixelHeight > height) { wb = wb.Resize((int)(((double)wb.PixelWidth / wb.PixelHeight) * height), height, WriteableBitmapExtensions.Interpolation.Bilinear); } var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, resultStream); encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)wb.PixelWidth, (uint)wb.PixelHeight, DisplayInformation.GetForCurrentView().LogicalDpi, DisplayInformation.GetForCurrentView().LogicalDpi, wb.PixelBuffer.ToArray()); await encoder.FlushAsync(); return(new Tuple <double, double>((double)originalWidth / wb.PixelWidth, (double)originalHeight / wb.PixelHeight)); }
public virtual async Task SetLockScreenAsync(Stream stream) { if (Windows.Foundation.Metadata.ApiInformation.IsTypePresent("Windows.System.UserProfile.LockScreen")) { await LockScreen.SetImageStreamAsync(stream.AsRandomAccessStream()); } }
/// <summary> /// Cache specific hooks to process items from HTTP response /// </summary> /// <param name="stream">input stream</param> /// <param name="initializerKeyValues">key value pairs used when initializing instance of generic type</param> /// <returns>awaitable task</returns> protected override async Task <BitmapImage> InitializeTypeAsync(Stream stream, List <KeyValuePair <string, object> > initializerKeyValues = null) { if (stream.Length == 0) { throw new FileNotFoundException(); } return(await DispatcherHelper.ExecuteOnUIThreadAsync(async() => { BitmapImage image = new BitmapImage(); if (initializerKeyValues != null && initializerKeyValues.Count > 0) { foreach (var kvp in initializerKeyValues) { if (string.IsNullOrWhiteSpace(kvp.Key)) { continue; } var propInfo = image.GetType().GetProperty(kvp.Key, BindingFlags.Public | BindingFlags.Instance); if (propInfo != null && propInfo.CanWrite) { propInfo.SetValue(image, kvp.Value); } } } await image.SetSourceAsync(stream.AsRandomAccessStream()).AsTask().ConfigureAwait(false); return image; })); }
public async Task FileReadStreamSeekTestAsyncInternal() { byte[] buffer = GetRandomBuffer(3 * 1024 * 1024); CloudFileShare share = GetRandomShareReference(); try { await share.CreateAsync(); CloudFile file = share.GetRootDirectoryReference().GetFileReference("file1"); file.StreamMinimumReadSizeInBytes = 2 * 1024 * 1024; using (MemoryStream wholeFile = new MemoryStream(buffer)) { await file.UploadFromStreamAsync(wholeFile); } OperationContext opContext = new OperationContext(); using (Stream fileStream = await file.OpenReadAsync(null, null, opContext)) { #if NETCORE int attempts = await FileReadStreamSeekTestAsync(fileStream, file.StreamMinimumReadSizeInBytes, buffer); #else int attempts = await FileReadStreamSeekTestAsync(fileStream.AsRandomAccessStream(), file.StreamMinimumReadSizeInBytes, buffer); #endif TestHelper.AssertNAttempts(opContext, attempts); } } finally { await share.DeleteAsync(); } }
/// <summary> /// Encodes a WriteableBitmap object into a PNG stream. /// </summary> /// <param name="writeableBitmap">The writeable bitmap.</param> /// <param name="outputStream">The image data stream.</param> /// <returns>The <see cref="Task"/> object representing the asynchronous operation.</returns> public static async Task SavePngAsync(this WriteableBitmap writeableBitmap, Stream outputStream) { #if WINDOWS_PHONE WriteHeader(outputStream, writeableBitmap); WritePhysics(outputStream); ////WriteGamma(outputStream); WriteDataChunks(outputStream, writeableBitmap); WriteFooter(outputStream); outputStream.Flush(); await Task.FromResult(0); #else var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, outputStream.AsRandomAccessStream()); var pixels = writeableBitmap.PixelBuffer.ToArray(); encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight, (uint)writeableBitmap.PixelWidth, (uint)writeableBitmap.PixelHeight, ResolutionDpi, ResolutionDpi, pixels); await encoder.FlushAsync(); #endif }
public async Task <RecogniseResult> Recognise(Stream fileStream) { var randomAccessStream = fileStream.AsRandomAccessStream(); var bitmapDecoder = await BitmapDecoder.CreateAsync(randomAccessStream); var rawBitmap = await bitmapDecoder.GetSoftwareBitmapAsync(); var supportedBitmapFormats = FaceDetector.GetSupportedBitmapPixelFormats(); var supportedFormatBitmap = SoftwareBitmap.Convert(rawBitmap, supportedBitmapFormats.First()); var faceDetector = await FaceDetector.CreateAsync(); var faces = await faceDetector.DetectFacesAsync(supportedFormatBitmap); var result = new RecogniseResult(); if (faces.Any()) { result.Faces = faces.Count(); var memoryStream = new InMemoryRandomAccessStream(); var bitmapEncoder = await BitmapEncoder.CreateAsync(BitmapEncoder.BmpEncoderId, memoryStream); bitmapEncoder.SetSoftwareBitmap(rawBitmap); bitmapEncoder.BitmapTransform.Bounds = faces.First().FaceBox; await bitmapEncoder.FlushAsync(); result.FirstFace = memoryStream.AsStream(); } return(result); }
public static async Task <ImageSource> BlurImageAsync([NotNull] IBuffer buffer, int blur) { using (Stream imageStream = buffer.AsStream()) using (IRandomAccessStream randomImageStream = imageStream.AsRandomAccessStream()) { BitmapDecoder decoder; try { decoder = await BitmapDecoder.CreateAsync(randomImageStream); } catch { // Invalid image data return(null); } randomImageStream.Seek(0); using (RandomAccessStreamImageSource imageProvider = new RandomAccessStreamImageSource(randomImageStream)) using (BlurEffect blurEffect = new BlurEffect(imageProvider) { KernelSize = blur }) { WriteableBitmap blurred = new WriteableBitmap((int)decoder.PixelWidth, (int)decoder.PixelHeight); return(await blurEffect.GetBitmapAsync(blurred, OutputOption.Stretch)); } } }
public static async Task <BandImage> FromStreamAsync(Stream stream) { #if __ANDROID__ var image = await BitmapFactory.DecodeStreamAsync(stream); return(FromBitmap(image)); #elif __IOS__ var image = await Task.Run(() => { using (var data = NSData.FromStream(stream)) { return(NativeBitmap.LoadFromData(data)); } }); return(FromUIImage(image)); #elif WINDOWS_PHONE_APP using (var fileStream = stream.AsRandomAccessStream()) { var bitmap = new NativeBitmap(1, 1); await bitmap.SetSourceAsync(fileStream); return(FromWriteableBitmap(bitmap)); } #else // PORTABLE return(null); #endif }
public object GetImageSource(Stream stream) { var bitmap = new BitmapImage(); bitmap.SetSource(stream.AsRandomAccessStream()); return(bitmap); }
async private Task <StorageFile> CreateTempFileScaled(Stream stream, float percentageToFit) { var appFolder = ApplicationData.Current.TemporaryFolder; var tempFile = await appFolder.CreateFileAsync(Guid.NewGuid() + ".jpg"); using (IRandomAccessStream str = await tempFile.OpenAsync(FileAccessMode.ReadWrite)) { BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream.AsRandomAccessStream()); var softBitmap = await decoder.GetSoftwareBitmapAsync(); BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, str); encoder.SetSoftwareBitmap(softBitmap); encoder.BitmapTransform.ScaledWidth = (uint)(softBitmap.PixelWidth / percentageToFit); encoder.BitmapTransform.ScaledHeight = (uint)(softBitmap.PixelHeight / percentageToFit); try { await encoder.FlushAsync(); return(tempFile); } catch (Exception err) { throw new Exception("[CropImageImplementation] ScaleBitmap Could not scale Bitmap Message= " + err.Message); } } }
public async Task AppendBlobReadStreamSeekTestAsync() { byte[] buffer = GetRandomBuffer(3 * 1024 * 1024); CloudBlobContainer container = GetRandomContainerReference(); try { await container.CreateAsync(); CloudAppendBlob blob = container.GetAppendBlobReference("blob1"); await blob.CreateOrReplaceAsync(); blob.StreamMinimumReadSizeInBytes = 2 * 1024 * 1024; using (MemoryStream wholeBlob = new MemoryStream(buffer)) { await blob.AppendBlockAsync(wholeBlob); } OperationContext opContext = new OperationContext(); using (Stream blobStream = await blob.OpenReadAsync(null, null, opContext)) { #if WINDOWS_RT int attempts = await BlobReadStreamSeekTestAsync(blobStream.AsRandomAccessStream(), blob.StreamMinimumReadSizeInBytes, buffer); #else int attempts = await BlobReadStreamSeekTestAsync(blobStream, blob.StreamMinimumReadSizeInBytes, buffer); #endif TestHelper.AssertNAttempts(opContext, attempts); } } finally { container.DeleteIfExistsAsync().Wait(); } }
private static void RendererImage(Stream stream, SvgImageRendererSettings settings) { var svg = settings.Document; var viewPort = svg.RootElement.ViewPort; if (!viewPort.HasValue) { throw new ArgumentException(nameof(settings)); } var width = viewPort.Value.Width; var height = viewPort.Value.Height; var device = CanvasDevice.GetSharedDevice(); using (var offScreen = new CanvasRenderTarget(device, width, height, settings.Scaling * 96.0F)) { using (var renderer = new Win2dRenderer(offScreen, svg)) using (var session = offScreen.CreateDrawingSession()) { session.Clear(Colors.Transparent); renderer.Render(width, height, session); } offScreen.SaveAsync(stream.AsRandomAccessStream(), (CanvasBitmapFileFormat)settings.Format, settings.Quality).AsTask().GetAwaiter().GetResult(); } }
private async void btnTakePicture_Click(object sender, RoutedEventArgs e) { HttpClientHandler handler = new HttpClientHandler(); handler.Credentials = new NetworkCredential("Tolegen", "hassAn10"); HttpClient client = new HttpClient(handler); HttpResponseMessage message = await client.PostAsync(HoloLensUrl + ApiTakePhoto, null); Picture picture = new Picture(); if (message.StatusCode == HttpStatusCode.OK) { //content contains json payload with name of picture taken string content = await message.Content.ReadAsStringAsync(); picture = JsonConvert.DeserializeObject <Picture>(content); } tbResult.Text = picture.PhotoFileName; Stream stream = await GetFileAsStream(picture.PhotoFileName); BitmapImage bitmapImage = new BitmapImage(); bitmapImage.DecodePixelWidth = 600; await bitmapImage.SetSourceAsync(stream.AsRandomAccessStream()); imgPicture.Source = bitmapImage; }
async void Page_Loaded(object sender, RoutedEventArgs e) { Stream stream = this.GetType().GetTypeInfo().Assembly.GetManifestResourceStream("PdfDocumentSourceSamples.Resources.DefaultDocument.pdf"); await _pdfDocSource.LoadFromStreamAsync(stream.AsRandomAccessStream()); flexViewer.DocumentSource = _pdfDocSource; }
public async void SavePictureToDiskWINRT(Stream imgStream, string Id, bool OverwriteIfExist = false) { var inStream = imgStream.AsRandomAccessStream(); var fileBytes = new byte[inStream.Size]; using (DataReader reader = new DataReader(inStream)) { await reader.LoadAsync((uint)inStream.Size); reader.ReadBytes(fileBytes); } var file = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFileAsync(Id + ".jpg", Windows.Storage.CreationCollisionOption.ReplaceExisting); using (var fs = await file.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite)) { var outStream = fs.GetOutputStreamAt(0); var dataWriter = new DataWriter(outStream); dataWriter.WriteBytes(fileBytes); await dataWriter.StoreAsync(); dataWriter.DetachStream(); await outStream.FlushAsync(); outStream.Dispose(); fs.Dispose(); } }
public async Task <object> GetImageSourceAsync(Stream stream) { var bitmap = new BitmapImage(); await bitmap.SetSourceAsync(stream.AsRandomAccessStream()); return(bitmap); }
private static bool CheckDesignMode(Image image, Uri sourceUri, Stream sourceStream) { if (IsInDesignMode(image) && !GetAnimateInDesignMode(image)) { var bmp = new BitmapImage(); #if WPF bmp.BeginInit(); #endif if (sourceStream != null) { #if WPF bmp.StreamSource = sourceStream; #elif WINRT bmp.SetSource(sourceStream.AsRandomAccessStream()); #endif } if (sourceUri != null) { bmp.UriSource = sourceUri; } #if WPF bmp.EndInit(); #endif image.Source = bmp; return(false); } return(true); }
public static async Task <Tuple <ImageSource, ImageSource> > GetImageAndBlurredCopyFromPixelDataAsync([NotNull] IBuffer buffer, int blur) { // Check if the input is valid if (buffer.Length == 0) { return(null); } // Apply the blur effect on a copy of the original image using (Stream imageStream = buffer.AsStream()) using (IRandomAccessStream randomImageStream = imageStream.AsRandomAccessStream()) { // Load the default image BitmapImage original = new BitmapImage(); await original.SetSourceAsync(randomImageStream); // Blur the copy of the image randomImageStream.Seek(0); using (RandomAccessStreamImageSource imageProvider = new RandomAccessStreamImageSource(randomImageStream)) using (BlurEffect blurEffect = new BlurEffect(imageProvider) { KernelSize = blur }) { // Process the blurred image WriteableBitmap blurred = new WriteableBitmap((int)original.PixelWidth, (int)original.PixelHeight); await blurEffect.GetBitmapAsync(blurred, OutputOption.Stretch); // Return the two images return(Tuple.Create <ImageSource, ImageSource>(original, blurred)); } } }
public async Task <SoftwareBitmap> getCachedImageAsync(string url) { // Провека, есть ли изображение в пуле foreach (KeyValuePair <string, SoftwareBitmap> kvp in imagePool) { if (kvp.Key == url) { return(kvp.Value); } } // Преобразуем строку в Uri KeyValuePair <string, string> uri = convertPathFilenameFromUri(url); SoftwareBitmap bitmap = null; // Проверка на существование файла на диске if (await cache.isFileActual(url)) { bitmap = await cache.readImageFile(url); return(bitmap); } else { // Загрузка файла на диск try { using (HttpClient client = new HttpClient()) { var response = await client.GetAsync(url); response.EnsureSuccessStatusCode(); Stream inputStream = await response.Content.ReadAsStreamAsync(); BitmapDecoder decoder = await BitmapDecoder.CreateAsync(inputStream.AsRandomAccessStream()); bitmap = await decoder.GetSoftwareBitmapAsync(); bitmap = SoftwareBitmap.Convert(bitmap, BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore); } } catch (Exception) { Debug.WriteLine("Ошибка при загрузке изображения: " + uri); } } if (bitmap != null) // Если картинка загрузилась { await cache.createImageFile(url, bitmap); // Запись загруженного файла на диск imagePool.Add(new KeyValuePair <string, SoftwareBitmap>(url, bitmap)); return(bitmap); } return(null); }
/// <summary> /// Get Bitmap /// </summary> /// <param name="fileNameOfImage"></param> /// <returns></returns> public async Task <BitmapDecoder> BitmapDecoderGet(string fileNameOfImage) { StorageFile imageFile = await Package.Current.InstalledLocation.GetFileAsync(fileNameOfImage); Stream imagestream = await imageFile.OpenStreamForReadAsync(); return(await BitmapDecoder.CreateAsync(imagestream.AsRandomAccessStream())); // Stream dekodieren }
protected BitmapImage CreateBitmapFromStream(Stream stream) { var result = new BitmapImage(); result.SetSource(stream.AsRandomAccessStream()); return(result); }
public async Task LoadFileAsync(StorageFile file) { Stream stream = await file.OpenStreamForReadAsync(); var properties = await file.Properties.GetImagePropertiesAsync(); await SetCanvas(properties.Width, properties.Height, stream.AsRandomAccessStream()); }
// This dumbass workaround is necessary as the direct usage of // BitmapImage.SetSource does not produce a bitmap at all, and // BitmapImage.SetSourceAsync crashes with an access violation. // Thanks for the cool shit, Microsoft. private async void LoadPreview(Stream preview) { var decoder = await BitmapDecoder.CreateAsync(preview.AsRandomAccessStream()); var bitmap = await decoder.GetSoftwareBitmapAsync(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied); await Preview.SetBitmapAsync(bitmap); }
private async void testWrite() { if (_item != null) { _encoder = new CaptureEncode(_device, _item); await _encoder.EncodeAsync(_stream.AsRandomAccessStream(), 1920, 1080, 36000000, 60); } }
/// <summary> /// Encodes a WriteableBitmap object into a PNG stream. /// </summary> /// <param name="renderTargetBitmap">The render target bitmap.</param> /// <param name="outputStream">The image data stream.</param> /// <returns>The <see cref="Task"/> object representing the asynchronous operation.</returns> public static async Task SavePngAsync(this RenderTargetBitmap renderTargetBitmap, Stream outputStream) { var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, outputStream.AsRandomAccessStream()); var pixels = (await renderTargetBitmap.GetPixelsAsync()).ToArray(); encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight, (uint)renderTargetBitmap.PixelWidth, (uint)renderTargetBitmap.PixelHeight, ResolutionDpi, ResolutionDpi, pixels); await encoder.FlushAsync(); }
public async Task PlayAsync(Stream speechStream, string contentFormat) { if (speechStream == null) throw new ArgumentNullException(nameof(speechStream)); if (contentFormat == null) throw new ArgumentNullException(nameof(speechStream)); var media = new MediaElement(); media.SetSource(speechStream.AsRandomAccessStream(), contentFormat); media.Play(); await Task.CompletedTask; }
/// <summary> /// Encodes a WriteableBitmap object into a JPEG stream, with parameters for setting the target quality of the JPEG file. /// </summary> /// <param name="writeableBitmap">The WriteableBitmap object.</param> /// <param name="outputStream">The image data stream.</param> /// <param name="quality">This parameter represents the quality of the JPEG photo with a range between 0 and 100, with 100 being the best photo quality. We recommend that you do not fall lower than a value of 70. because JPEG picture quality diminishes significantly below that level. </param> /// <returns>The <see cref="Task"/> object representing the asynchronous operation.</returns> public static async Task SaveJpegAsync(this WriteableBitmap writeableBitmap, Stream outputStream, int quality) { var propertySet = new BitmapPropertySet { { "ImageQuality", new BitmapTypedValue(quality, PropertyType.Single) } }; var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, outputStream.AsRandomAccessStream(), propertySet); var pixels = writeableBitmap.PixelBuffer.ToArray(); encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied, (uint)writeableBitmap.PixelWidth, (uint)writeableBitmap.PixelHeight, ResolutionDpi, ResolutionDpi, pixels); await encoder.FlushAsync(); }
/// <summary> /// Instantiates a new instance <see cref="ByteStream"/> from a <see cref="Stream"/>. /// </summary> /// <msdn-id>hh162754</msdn-id> /// <unmanaged>HRESULT MFCreateMFByteStreamOnStreamEx([In] IUnknown* punkStream,[Out] IMFByteStream** ppByteStream)</unmanaged> /// <unmanaged-short>MFCreateMFByteStreamOnStreamEx</unmanaged-short> public ByteStream(Stream sourceStream) { this.sourceStream = sourceStream; #if WIN8METRO var randomAccessStream = sourceStream.AsRandomAccessStream(); randomAccessStreamCom = new ComObject(Marshal.GetIUnknownForObject(randomAccessStream)); MediaFactory.CreateMFByteStreamOnStreamEx(randomAccessStreamCom, this); #else streamProxy = new ComStreamProxy(sourceStream); IByteStream localStream; MediaFactory.CreateMFByteStreamOnStream(ComStream.ToIntPtr(streamProxy), out localStream); NativePointer = ((ByteStream) localStream).NativePointer; #endif }
public async Task<object> ConvertFromEncodedStream(Stream encodedStream, int width, int height) { if (encodedStream == null) return null; var image = new WriteableBitmap(width, height); encodedStream.Seek(0, SeekOrigin.Begin); await image.SetSourceAsync(encodedStream.AsRandomAccessStream()); return image; //var writeableImage = new WriteableBitmap(image.PixelWidth, image.PixelHeight); //image.SetSource(encodedStream.AsRandomAccessStream()); //return writeableImage; }
public CN1Media(Stream s, string mime, java.lang.Runnable onComplete, Canvas cl) { this.cl = cl; using (AutoResetEvent are = new AutoResetEvent(false)) { SilverlightImplementation.dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { elem = new MediaElement(); cl.Children.Add(elem); elem.MediaOpened += elem_MediaOpened; elem.SetSource(s.AsRandomAccessStream(), ""); video = mime.StartsWith("video"); this.onComplete = onComplete; elem.MediaEnded += elem_MediaEnded; are.Set(); }).AsTask().ConfigureAwait(false).GetAwaiter().GetResult(); are.WaitOne(); } }
public async Task<CallRet> CallWithBinary(string url, HttpMediaTypeHeaderValue contentType, Stream body, long length) { Debug.WriteLine("Client.PostWithBinary ==> URL: {0} Length:{1}", url, length); try { HttpClient client = new HttpClient(); body.Position = 0; HttpStreamContent streamContent = new HttpStreamContent(body.AsRandomAccessStream()); HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Post, new Uri(url)); req.Content = streamContent; SetAuth(req,client, body); var resp = await client.SendRequestAsync(req); return await HandleResult(resp); } catch (Exception e) { Debug.WriteLine(e.ToString()); return new CallRet(Windows.Web.Http.HttpStatusCode.BadRequest, e); } }
private static void RendererImage(Stream stream, SvgImageRendererSettings settings) { var svg = settings.Document; var viewPort = svg.RootElement.ViewPort; if (!viewPort.HasValue) throw new ArgumentException(nameof(settings)); var width = viewPort.Value.Width; var height = viewPort.Value.Height; var device = CanvasDevice.GetSharedDevice(); using (var offScreen = new CanvasRenderTarget(device, width, height, settings.Scaling * 96.0F)) { using (var renderer = new Win2dRenderer(offScreen, svg)) using (var session = offScreen.CreateDrawingSession()) { session.Clear(Colors.Transparent); renderer.Render(width, height, session); } offScreen.SaveAsync(stream.AsRandomAccessStream(), (CanvasBitmapFileFormat)settings.Format, settings.Quality).AsTask().GetAwaiter().GetResult(); } }
protected bool SaveCoverImages(string bookID, Stream imageStream) { var @event = new AutoResetEvent(false); bool result = false; ((Action)(() => { try { var bitmapImage = new BitmapImage(); bitmapImage.SetSource(imageStream.AsRandomAccessStream()); using (var isoStorage = IsolatedStorageFile.GetUserStoreForApplication()) { using (var iconImageFile = isoStorage.CreateFile(ModelExtensions.GetBookCoverPath(bookID))) { bitmapImage.SaveJpeg(iconImageFile, 300, 300, true); } using (var coverImageFile = isoStorage.CreateFile(ModelExtensions.GetBookFullCoverPath(bookID))) { bitmapImage.SaveJpeg(coverImageFile, bitmapImage.PixelWidth, bitmapImage.PixelHeight, false); } } result = true; } catch (Exception) { result = false; } finally { @event.Set(); } })).OnUIThread(); @event.WaitOne(); return result; }
public async void SavePictureToDiskWINRT(Stream imgStream, string Id, bool OverwriteIfExist = false) { var inStream = imgStream.AsRandomAccessStream(); var fileBytes = new byte[inStream.Size]; using (DataReader reader = new DataReader(inStream)) { await reader.LoadAsync((uint)inStream.Size); reader.ReadBytes(fileBytes); } var file = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFileAsync(Id+".jpg", Windows.Storage.CreationCollisionOption.ReplaceExisting); using (var fs = await file.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite)) { var outStream = fs.GetOutputStreamAt(0); var dataWriter = new DataWriter(outStream); dataWriter.WriteBytes(fileBytes); await dataWriter.StoreAsync(); dataWriter.DetachStream(); await outStream.FlushAsync(); outStream.Dispose(); fs.Dispose(); } }
public static async Task<BandImage> FromStreamAsync(Stream stream) { #if __ANDROID__ var image = await BitmapFactory.DecodeStreamAsync(stream); return FromBitmap(image); #elif __IOS__ var image = await Task.Run(() => { using (var data = NSData.FromStream(stream)) { return NativeBitmap.LoadFromData(data); } }); return FromUIImage(image); #elif WINDOWS_PHONE_APP using (var fileStream = stream.AsRandomAccessStream()) { var bitmap = new NativeBitmap(1, 1); await bitmap.SetSourceAsync(fileStream); return FromWriteableBitmap(bitmap); } #else // PORTABLE return null; #endif }
/// <summary> /// Sets the lock screen background image. /// </summary> /// <param name="stream">The file stream.</param> /// <returns>The <see cref="Task"/> object representing the asynchronous operation.</returns> public virtual async Task SetLockScreenAsync(Stream stream) { #if WINDOWS_PHONE using (var fileStream = await StorageService.LocalStorageServiceHandlerStatic.CreateFileAsync(LockScreenFile)) { await stream.CopyToAsync(fileStream); } ImageUri = new Uri(LockScreenImageUrl, UriKind.RelativeOrAbsolute); #elif WINDOWS_UWP || WINDOWS_APP await LockScreen.SetImageStreamAsync(stream.AsRandomAccessStream()); #else await ExceptionHelper.ThrowNotSupported<Task>(); #endif }
public virtual async Task SetLockScreenAsync(Stream stream) { await LockScreen.SetImageStreamAsync(stream.AsRandomAccessStream()); }
/// <summary> /// Uploads the photo. /// </summary> /// <param name="stream">The memory stream.</param> /// <param name="localPath">The local path.</param> /// <param name="caption">The caption.</param> /// <param name="categoryId">The id of the assocaited category.</param> /// <returns>The uploaded photo.</returns> public async Task<Photo> UploadPhoto(Stream stream, string localPath, string caption, string categoryId) { try { var sasContracts = await GetSasUrls(); // Upload photos into azure foreach (var sasContract in sasContracts) { var blob = new CloudBlockBlob( new Uri($"{sasContract.FullBlobUri}{sasContract.SasToken}")); var sideLength = sasContract.SasPhotoType.ToSideLength(); var resizedStream = await BitmapTools.Resize( stream.AsRandomAccessStream(), sideLength, sideLength); await blob.UploadFromStreamAsync(resizedStream); } var photoContract = new PhotoContract { CategoryId = categoryId, Description = caption, OSPlatform = AnalyticsInfo.VersionInfo.DeviceFamily, User = AppEnvironment.Instance.CurrentUser.ToDataContract(), ThumbnailUrl = sasContracts.FirstOrDefault(c => c.SasPhotoType == PhotoTypeContract.Thumbnail)? .FullBlobUri.ToString(), StandardUrl = sasContracts.FirstOrDefault(c => c.SasPhotoType == PhotoTypeContract.Standard)? .FullBlobUri.ToString(), HighResolutionUrl = sasContracts.FirstOrDefault(c => c.SasPhotoType == PhotoTypeContract.HighRes)? .FullBlobUri.ToString() }; var responsePhotoContract = await _mobileServiceClient.InvokeApiAsync<PhotoContract, PhotoContract>("Photo", photoContract, HttpMethod.Post, null); return responsePhotoContract.ToDataModel(); } catch (Exception e) { throw new ServiceException("UploadPhoto error", e); } }
private static async void InitAnimationAsync(Image image, Stream stream, RepeatBehavior repeatBehavior, int seqNum) { if (!CheckDesignMode(image, null, stream)) return; try { var animator = await ImageAnimator.CreateAsync(stream, repeatBehavior, image); await SetAnimatorCoreAsync(image, animator); // Check that the source hasn't changed while we were loading the animation if (GetSeqNum(image) != seqNum) { animator.Dispose(); return; } OnLoaded(image); } catch (InvalidSignatureException) { var bmp = new BitmapImage(); #if WPF bmp.BeginInit(); bmp.StreamSource = stream; bmp.EndInit(); #elif WINRT bmp.SetSource(stream.AsRandomAccessStream()); #elif SILVERLIGHT bmp.SetSource(stream); #endif image.Source = bmp; OnLoaded(image); } catch(Exception ex) { OnError(image, ex, AnimationErrorKind.Loading); } }
private async Task<Stream> CreateThumb(Stream orgStm, int width, int height, string filePath) { var ras = orgStm.AsRandomAccessStream(); var wb = new WriteableBitmap(width, height); ras.Seek(0); await wb.SetSourceAsync(ras); var stm = wb.PixelBuffer.AsStream(); var bytes = await stm.GetBytes(); using (var fs = await FileManager.Instance.Value.OpenFile(filePath)) { //BitmapEncoder 无法写入 MemoryStream BitmapEncoder encoder = await BitmapEncoder.CreateAsync( BitmapEncoder.JpegEncoderId, fs); encoder.BitmapTransform.ScaledWidth = (uint)width; encoder.BitmapTransform.ScaledHeight = (uint)height; //encoder.BitmapTransform.Rotation = BitmapRotation.Clockwise90Degrees; encoder.SetPixelData( BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight, (uint)wb.PixelWidth, (uint)wb.PixelHeight, 96.0, 96.0, bytes); await encoder.FlushAsync(); return fs.CloneStream().AsStream(); } }
/// <summary> /// Sets the current bitmap content that is stored in the clipboard. /// </summary> /// <param name="content">The bitmap content that is stored in the clipboard.</param> public virtual void SetBitmap(Stream content) { var package = new DataPackage(); var random = content.AsRandomAccessStream(); var reference = RandomAccessStreamReference.CreateFromStream(random); package.SetBitmap(reference); }
public static async Task<bool> TryWriteStreamAsync(this StorageFile storageFile, Stream stream) { return await TryWriteStreamAsync(storageFile, stream.AsRandomAccessStream()); }
public virtual Task SetLockScreenAsync(Stream stream) { return LockScreen.SetImageStreamAsync(stream.AsRandomAccessStream()).AsTask(); }
public Task<byte[]> ResizeImageAsync(Stream imageStream, double height, double width) { return Task.Run(async () => { try { var decoder = await BitmapDecoder.CreateAsync(imageStream.AsRandomAccessStream()); InMemoryRandomAccessStream resizedStream = new InMemoryRandomAccessStream(); if (decoder.OrientedPixelHeight > height || decoder.OrientedPixelWidth > width) { BitmapEncoder encoder = await BitmapEncoder.CreateForTranscodingAsync(resizedStream, decoder); double widthRatio = width / decoder.OrientedPixelWidth; double heightRatio = height / decoder.OrientedPixelHeight; // Use whichever ratio had to be sized down the most to make sure the image fits within our constraints. double scaleRatio = Math.Min(widthRatio, heightRatio); uint aspectHeight = (uint)Math.Floor(decoder.OrientedPixelHeight * scaleRatio); uint aspectWidth = (uint)Math.Floor(decoder.OrientedPixelWidth * scaleRatio); encoder.BitmapTransform.InterpolationMode = BitmapInterpolationMode.Fant; encoder.BitmapTransform.ScaledHeight = aspectHeight; encoder.BitmapTransform.ScaledWidth = aspectWidth; try { // write out to the stream // might fail cause https://msdn.microsoft.com/en-us/library/windows/apps/windows.graphics.imaging.bitmapencoder.bitmaptransform.aspx await encoder.FlushAsync(); } catch (Exception ex) { //from http://stackoverflow.com/questions/38617761/bitmapencoder-flush-throws-argument-exception/38633258#38633258 if (ex.HResult.ToString() == "WINCODEC_ERR_INVALIDPARAMETER" || ex.HResult == -2147024809) { resizedStream = new InMemoryRandomAccessStream(); BitmapEncoder pixelencoder = await BitmapEncoder.CreateForTranscodingAsync(resizedStream, decoder); BitmapTransform transform = new BitmapTransform { InterpolationMode = BitmapInterpolationMode.Fant, ScaledHeight = aspectHeight, ScaledWidth = aspectWidth }; var provider = await decoder.GetPixelDataAsync(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, transform, ExifOrientationMode.RespectExifOrientation, ColorManagementMode.DoNotColorManage); var pixels = provider.DetachPixelData(); pixelencoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, aspectWidth, aspectHeight, decoder.DpiX, decoder.DpiY, pixels); try { await pixelencoder.FlushAsync(); } catch (Exception ex2) { LogHelper.Instance.LogException(ex2); return null; } } else { LogHelper.Instance.LogException(ex); return null; } } // Reset the stream location. resizedStream.Seek(0); // Writes the image byte array in an InMemoryRandomAccessStream using (DataReader reader = new DataReader(resizedStream.GetInputStreamAt(0))) { var bytes = new byte[resizedStream.Size]; await reader.LoadAsync((uint)resizedStream.Size); reader.ReadBytes(bytes); return bytes; } } imageStream.Seek(0, SeekOrigin.Begin); using (var memoryStream = new MemoryStream()) { imageStream.CopyTo(memoryStream); return memoryStream.ToArray(); } } catch (Exception ex) { LogHelper.Instance.Log(LogLevel.Warning, "Download.cs", "ResizeImageAsync failed", ex); } return null; }); }
private static async void InitAnimationAsync(Image image, Stream stream, RepeatBehavior repeatBehavior) { if (!CheckDesignMode(image, null, stream)) return; try { var animator = await Animator.CreateAsync(stream, repeatBehavior); SetAnimatorCore(image, animator); OnLoaded(image); } catch (InvalidSignatureException) { var bmp = new BitmapImage(); #if WPF bmp.BeginInit(); bmp.StreamSource = stream; bmp.EndInit(); #elif WINRT bmp.SetSource(stream.AsRandomAccessStream()); #endif image.Source = bmp; OnLoaded(image); } catch(Exception ex) { OnError(image, ex, AnimationErrorKind.Loading); } }
public Task PlayStreamAsync(Stream stream, string mimeType) { return Play(stream.AsRandomAccessStream(), mimeType); }
private static bool CheckDesignMode(Image image, Uri sourceUri, Stream sourceStream) { if (IsInDesignMode(image) && !GetAnimateInDesignMode(image)) { var bmp = new BitmapImage(); #if WPF bmp.BeginInit(); #endif if (sourceStream != null) { #if WPF bmp.StreamSource = sourceStream; #elif WINRT bmp.SetSource(sourceStream.AsRandomAccessStream()); #elif SILVERLIGHT bmp.SetSource(sourceStream); #endif } else if (sourceUri != null) { bmp.UriSource = sourceUri; } #if WPF bmp.EndInit(); #endif image.Source = bmp; return false; } return true; }