public async Task <string> WriteToFile(SoftwareBitmap softwareBitmap) { string fileName = "ENRZ" + Guid.NewGuid().GetHashCode().ToString() + "FR" + DateTime.Now.Year.ToString() + "GR" + DateTime.Now.Month.ToString() + "VE" + DateTime.Now.Day.ToString() + "JU" + DateTime.Now.Hour.ToString() + "SW" + DateTime.Now.Minute.ToString() + "VJ" + DateTime.Now.Second.ToString() + "MQ" + DateTime.Now.Millisecond.ToString() + ".jpg"; if (softwareBitmap != null) { // save image file to cache StorageFile file = await( await KnownFolders.PicturesLibrary.CreateFolderAsync("ENRZ", CreationCollisionOption.OpenIfExists)) .CreateFileAsync(fileName, CreationCollisionOption.OpenIfExists); using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite)) { BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream); encoder.SetSoftwareBitmap(softwareBitmap); await encoder.FlushAsync(); } } return(fileName); }
public async Task <byte[]> EncodeBitmap(object bitmap) { byte[] array = null; var softwareBitmap = bitmap as SoftwareBitmap; if (softwareBitmap == null) { return(array = new byte[0]); } using (var ms = new InMemoryRandomAccessStream()) { BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, ms); encoder.SetSoftwareBitmap(softwareBitmap); try { await encoder.FlushAsync(); } catch { return(new byte[0]); } array = new byte[ms.Size]; await ms.ReadAsync(array.AsBuffer(), (uint)ms.Size, InputStreamOptions.None); } return(array); }
private async Task <SoftwareBitmap> ResizeBitmap(SoftwareBitmap softwareBitmap, int targetWidth, int targetHeight) { using (IRandomAccessStream stream = new InMemoryRandomAccessStream()) { // Create an encoder with the desired format BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.BmpEncoderId, stream); // Set the software bitmap encoder.SetSoftwareBitmap(softwareBitmap); encoder.BitmapTransform.ScaledWidth = (uint)targetWidth; encoder.BitmapTransform.ScaledHeight = (uint)targetHeight; encoder.BitmapTransform.InterpolationMode = BitmapInterpolationMode.NearestNeighbor; encoder.IsThumbnailGenerated = false; await encoder.FlushAsync(); stream.Seek(0); BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream); var result = await decoder.GetSoftwareBitmapAsync(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied); return(result); } }
private async void DataTransferManager_DataRequestedAsync(DataTransferManager manager, DataRequestedEventArgs args) { try { DataRequest request = args.Request; request.Data.Properties.Title = "Share image"; request.Data.Properties.Description = ""; var deferal = request.GetDeferral(); //TODO regionalise text //generate the bitmap Load.Show(); var result = ApplyImageEffect8bitsNoHistoAsync(rawImage.fullSize, EditionValue); InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream(); BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream); //Needs to run in the UI thread because f**k performance await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { encoder.SetSoftwareBitmap(result); }); await encoder.FlushAsync(); encoder = null; result.Dispose(); Load.Hide(); request.Data.SetBitmap(RandomAccessStreamReference.CreateFromStream(stream)); deferal.Complete(); } catch (Exception e) { TextDisplay.DisplayError(e.Message); } }
public static async Task <SoftwareBitmap> CreateFromBitmap(SoftwareBitmap softwareBitmap, uint width, uint heigth) { using (InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream()) { BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream); encoder.SetSoftwareBitmap(softwareBitmap); encoder.BitmapTransform.InterpolationMode = BitmapInterpolationMode.Linear; var ancho = width * (0.2); var alto = heigth * (0.2); encoder.BitmapTransform.ScaledWidth = (uint)ancho; encoder.BitmapTransform.ScaledHeight = (uint)alto; await encoder.FlushAsync(); BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream); return(await decoder.GetSoftwareBitmapAsync(softwareBitmap.BitmapPixelFormat, softwareBitmap.BitmapAlphaMode)); } }
public static async Task <bool> CreateImage(SoftwareBitmap bitmap, string name, string path = "") { try { if (!string.IsNullOrEmpty(path) && !await ExistsFolder(path)) { CreateFolder(path); } SoftwareBitmap softBmp = bitmap; StorageFile file = await LoaclFolder.CreateFileAsync(path + "\\" + name, CreationCollisionOption.ReplaceExisting); using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite)) { BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream); encoder.SetSoftwareBitmap(softBmp); await encoder.FlushAsync(); } return(true); } catch (Exception ex) { throw ex; } }
public async void AddImageAsync(SoftwareBitmap image, string imageName) { var outputFile = await(await ApplicationData.Current.LocalFolder.GetFolderAsync("Gallery")).CreateFileAsync($"{imageName}.png"); using (IRandomAccessStream stream = await outputFile.OpenAsync(FileAccessMode.ReadWrite)) { BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, stream); encoder.SetSoftwareBitmap(image); try { await encoder.FlushAsync(); } catch (Exception err) { const int WINCODEC_ERR_UNSUPPORTEDOPERATION = unchecked ((int)0x88982F81); switch (err.HResult) { case WINCODEC_ERR_UNSUPPORTEDOPERATION: encoder.IsThumbnailGenerated = false; break; default: throw; } } } }
public async Task <string> Classify(SoftwareBitmap image) { // First: Use an encoder to copy from SoftwareBitmap to an in-mem stream (FlushAsync) // Next: Use ReadAsync on the in-mem stream to get byte[] array //1) Convert SoftwareBitMap byte[] array = null; using (var ms = new InMemoryRandomAccessStream()) { BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, ms); encoder.SetSoftwareBitmap(image); try { await encoder.FlushAsync(); } catch (Exception ex) { throw new NotImplementedException(); } array = new byte[ms.Size]; await ms.ReadAsync(array.AsBuffer(), (uint)ms.Size, InputStreamOptions.None); } string response = string.Empty; //Use mutlipartformdata to send frame to classifier api var containerURL = @"http://127.0.0.1:4000/image"; response = await MultiForm_GetJsonData(containerURL, array); // parse response and get highest probability, if none, return null return(response); }
private async Task <byte[]> SaveSoftwareBitmapToBufferAsync(SoftwareBitmap softwareBitmap) { byte[] bytes = null; try { IRandomAccessStream stream = new InMemoryRandomAccessStream(); { // Create an encoder with the desired format BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.BmpEncoderId, stream); encoder.SetSoftwareBitmap(softwareBitmap); encoder.IsThumbnailGenerated = false; await encoder.FlushAsync(); bytes = new byte[stream.Size]; // This returns IAsyncOperationWithProgess, so you can add additional progress handling await stream.ReadAsync(bytes.AsBuffer(), (uint)stream.Size, Windows.Storage.Streams.InputStreamOptions.None); } } catch (Exception ex) { Debug.WriteLine(ex); } return(bytes); }
public async Task <StorageFile> WriteableBitmapSaveToFile(WriteableBitmap combine_wb) { if (combine_wb == null) { return(null); } var storageManager = await LocalCacheManager.InitializeAsync(StorageFolderType.Pictures); var filename = "ink" + SecurityHelper.MD5(DateTime.Now.ToString(("yyyy-MM-dd HH:mm:ss fff"))) + ".jpg"; var path = Path.Combine(storageManager.CurrentFolder.Path, filename); var md5Name = DownloadHelper.GetDownloadedLocalFileName(path); StorageFile file = await storageManager.CurrentFolder.CreateFileAsync(md5Name, CreationCollisionOption.ReplaceExisting); using (var fileStream = await file.OpenAsync(FileAccessMode.ReadWrite)) { //await renderTarget.SaveAsync(fileStream, CanvasBitmapFileFormat.Png, 1f); SoftwareBitmap softwareBitmap = new SoftwareBitmap(BitmapPixelFormat.Bgra8, combine_wb.PixelWidth, combine_wb.PixelHeight); softwareBitmap.CopyFromBuffer(combine_wb.PixelBuffer); BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, fileStream); encoder.SetSoftwareBitmap(softwareBitmap); await encoder.FlushAsync(); } return(file); }
private async Task <IDictionary <string, float> > GetPredictionFromServiceAsync(IList <InkStroke> strokes) { var bitmap = strokes.DrawInk(); using (IRandomAccessStream stream = new InMemoryRandomAccessStream()) { BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream); encoder.SetSoftwareBitmap(bitmap); encoder.BitmapTransform.InterpolationMode = BitmapInterpolationMode.Fant; try { await encoder.FlushAsync(); var result = await _prediction.GetPredictionAsync(stream.AsStreamForRead(), _state.CurrentProject.Id, SelectedIteration.Id); return(result); } catch (Exception err) { return(null); } } }
public async Task <byte[]> EncodedBytes(byte[] bitmapArray) { if (bitmapArray == null) { return(null); } SoftwareBitmap bitmapBgra8 = SoftwareBitmap.Convert(await bitmapArray.ToSoftwareBitmapAsync(), BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied); byte[] array = null; // First: Use an encoder to copy from SoftwareBitmap to an in-mem stream (FlushAsync) // Next: Use ReadAsync on the in-mem stream to get byte[] array using (var ms = new InMemoryRandomAccessStream()) { BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, ms); encoder.SetSoftwareBitmap(bitmapBgra8); try { await encoder.FlushAsync(); } catch (Exception ex) { return(new byte[0]); } array = new byte[ms.Size]; await ms.ReadAsync(array.AsBuffer(), (uint)ms.Size, InputStreamOptions.None); } return(array); }
private async Task <SoftwareBitmap> CorpBitmap(SoftwareBitmap softwareBitmap, Rect rect) { SoftwareBitmap result; using (SoftwareBitmap encoderBitmap = SoftwareBitmap.Convert(softwareBitmap, BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied)) { using (MemoryStream memoryStream = new MemoryStream()) { BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, memoryStream.AsRandomAccessStream()); encoder.SetSoftwareBitmap(encoderBitmap); encoder.BitmapTransform.Bounds = new BitmapBounds() { X = (uint)rect.X, Y = (uint)rect.Y, Height = (uint)rect.Height, Width = (uint)rect.Width }; await encoder.FlushAsync(); var decoder = await BitmapDecoder.CreateAsync(memoryStream.AsRandomAccessStream()); result = await decoder.GetSoftwareBitmapAsync(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied); } } return(result); }
public static async Task <byte[]> GetBytesFromSoftwareBitmap(this SoftwareBitmap softwareBitmap, Guid encoderId) { byte[] array = null; // First: Use an encoder to copy from SoftwareBitmap to an in-mem stream (FlushAsync) // Next: Use ReadAsync on the in-mem stream to get byte[] array using (InMemoryRandomAccessStream imras = new InMemoryRandomAccessStream()) { BitmapEncoder encoder = await BitmapEncoder.CreateAsync(encoderId, imras); encoder.SetSoftwareBitmap(softwareBitmap); try { await encoder.FlushAsync(); } catch (Exception ex) { Console.WriteLine(ex); return(new byte[0]); } array = new byte[imras.Size]; await imras.ReadAsync(array.AsBuffer(), (uint)imras.Size, InputStreamOptions.None); } return(array); }
async void OnFrameSampleAcquired(VideoCaptureSample sample) { if (frameProccessed == false) { cnt_out += 1; return; } cnt_in += 1; Debug.Log("cnt : in = " + cnt_in.ToString() + ", out = " + cnt_out); frameProccessed = false; Debug.Log("Frame sample acquired"); bool mappable = true; float[] cameraToWorldMatrixAsFloat; float[] projectionMatrixAsFloat; mappable &= sample.TryGetCameraToWorldMatrix(out cameraToWorldMatrixAsFloat); mappable &= sample.TryGetProjectionMatrix(out projectionMatrixAsFloat); //when copying the bytes out of the buffer, you must supply a byte[] that is appropriately sized. //you can reuse this byte[] until you need to resize it(for whatever reason). byte[] latestImageBytes = null; System.Diagnostics.Stopwatch st = new System.Diagnostics.Stopwatch(); st.Start(); using (var ms = new InMemoryRandomAccessStream()) { BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, ms); encoder.SetSoftwareBitmap(sample.Bitmap); try { await encoder.FlushAsync(); } catch (Exception err) { Debug.LogError(err.Message); return; } latestImageBytes = new byte[ms.Size]; await ms.ReadAsync(latestImageBytes.AsBuffer(), (uint)ms.Size, InputStreamOptions.None); } st.Stop(); Debug.Log("encoding time " + st.ElapsedMilliseconds.ToString()); // Right now we pass things across the pipe as a float array then convert them back into UnityEngine.Matrix using a utility method if (mappable) { st.Restart(); cameraToWorld = CameraStreamHelper.ConvertFloatArrayToMatrix4x4(cameraToWorldMatrixAsFloat); projection = CameraStreamHelper.ConvertFloatArrayToMatrix4x4(projectionMatrixAsFloat); await SocketManager.Instance.SendPhoto(latestImageBytes); st.Stop(); Debug.Log("network time " + st.ElapsedMilliseconds.ToString()); BoundingBox[] boxes = await SocketManager.Instance.RecvDetections(); SceneUnderstanding.Instance.RecvDetections(cameraToWorld, projection, boxes, mappable); } frameProccessed = true; }
public static SKImage SoftwareBitmapToSKImage(SoftwareBitmap bitmap) { using InMemoryRandomAccessStream randomAccessStream = new InMemoryRandomAccessStream(); var task = BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, randomAccessStream); while (task.Status == AsyncStatus.Started) { Thread.Sleep(50); } BitmapEncoder encoder = task.GetResults(); encoder.SetSoftwareBitmap(SoftwareBitmap.Convert(bitmap, BitmapPixelFormat.Rgba8)); try { var Task = encoder.FlushAsync(); while (Task.Status == AsyncStatus.Started) { Thread.Sleep(50); } } catch { } byte[] array = new byte[randomAccessStream.Size]; var ReadTask = randomAccessStream.ReadAsync(array.AsBuffer(), (uint)randomAccessStream.Size, InputStreamOptions.None); while (ReadTask.Status == AsyncStatus.Started) { Thread.Sleep(50); } return(SKImage.FromEncodedData(array)); }
private async Task <byte[]> EncodedBytes(SoftwareBitmap soft, Guid encoderId) { byte[] array = null; // First: Use an encoder to copy from SoftwareBitmap to an in-mem stream (FlushAsync) // Next: Use ReadAsync on the in-mem stream to get byte[] array using (var ms = new InMemoryRandomAccessStream()) { BitmapEncoder encoder = await BitmapEncoder.CreateAsync(encoderId, ms); encoder.SetSoftwareBitmap(soft); try { await encoder.FlushAsync(); } catch { return(new byte[0]); } array = new byte[ms.Size]; await ms.ReadAsync(array.AsBuffer(), (uint)ms.Size, InputStreamOptions.None); } return(array); }
public async Task SaveGraphicFile(StorageFile outputFile) { using (IRandomAccessStream stream = await outputFile.OpenAsync(FileAccessMode.ReadWrite)) { BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream); encoder.SetSoftwareBitmap(softwareBitmap); encoder.BitmapTransform.InterpolationMode = BitmapInterpolationMode.Fant; encoder.IsThumbnailGenerated = true; try { await encoder.FlushAsync(); } catch (Exception err) { switch (err.HResult) { case unchecked ((int)0x88982F81): // WINCODEC_ERR_UNSUPPORTEDOPERATION // If the encoder does not support writing a thumbnail, then try again // but disable thumbnail generation. encoder.IsThumbnailGenerated = false; break; default: throw err; } } if (encoder.IsThumbnailGenerated == false) { await encoder.FlushAsync(); } } }
/* * static public async Task<string> Opener(StorageFile file) * { * string bitmap; * using (IRandomAccessStream fileStream * = await file.OpenAsync(FileAccessMode.Read)) * { * StorageFolder localFolder = ApplicationData.Current.LocalFolder; * String Path = localFolder.Path; * BitmapDecoder decoder = await BitmapDecoder.CreateAsync(fileStream); * SoftwareBitmap softwareBitmap = await decoder.GetSoftwareBitmapAsync(); * * StorageFile localFile = await localFolder.CreateFileAsync(file.Name, CreationCollisionOption.ReplaceExisting); * await SaveSoftwareBitmapToFile(softwareBitmap, localFile); * * bitmap = localFile.Path; * } * return bitmap; * } */ static public async Task <string> SaveSoftwareBitmapToFile(SoftwareBitmap softwareBitmap, StorageFile outputFile) { using (IRandomAccessStream stream = await outputFile.OpenAsync(FileAccessMode.ReadWrite)) { BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream); encoder.SetSoftwareBitmap(softwareBitmap); encoder.IsThumbnailGenerated = true; try { await encoder.FlushAsync(); } catch (Exception err) { switch (err.HResult) { case unchecked ((int)0x88982F81): encoder.IsThumbnailGenerated = false; break; default: throw err; } } if (encoder.IsThumbnailGenerated == false) { await encoder.FlushAsync(); } return(""); } }
// // Save a modified VideoFrame using an existing image file path with an appended suffix // static async Task <string> SaveModifiedVideoFrameToFileAsync(string imageFilePath, VideoFrame frame) { try { StorageFile file = await StorageFile.GetFileFromPathAsync(imageFilePath); StorageFolder folder = await file.GetParentAsync(); imageFilePath = file.Name.Replace(file.FileType, "_mod.jpg"); StorageFile modifiedFile = await folder.CreateFileAsync(imageFilePath, CreationCollisionOption.GenerateUniqueName); imageFilePath = modifiedFile.Path; // Create the encoder from the stream using (IRandomAccessStream stream = await modifiedFile.OpenAsync(FileAccessMode.ReadWrite)) { BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream); SoftwareBitmap softwareBitmap = frame.SoftwareBitmap; encoder.SetSoftwareBitmap(softwareBitmap); await encoder.FlushAsync(); } } catch (Exception ex) { Console.WriteLine($"Could not save modified VideoFrame from file: {imageFilePath}"); throw ex; } return(imageFilePath); }
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 static async Task <string> SendImage() { try { if (MainPage.oldImg == null) { return(""); } var stream = new InMemoryRandomAccessStream(); BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream); encoder.SetSoftwareBitmap(MainPage.oldImg); await encoder.FlushAsync(); var ms = new MemoryStream(); stream.AsStream().CopyTo(ms); var tdata = ms.ToArray(); var x = Convert.ToBase64String(tdata); ms.Dispose(); stream.Dispose(); return(x); } catch (Exception e) { Debug.WriteLine(e.Message); return(""); } }
public async static Task <SoftwareBitmap> GetCroppedBitmapAsync( SoftwareBitmap softwareBitmap, uint startPointX, uint startPointY, uint width, uint height) { using (InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream()) { BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.BmpEncoderId, stream); encoder.SetSoftwareBitmap(SoftwareBitmap.Convert(softwareBitmap, BitmapPixelFormat.Bgra8)); encoder.BitmapTransform.Bounds = new BitmapBounds() { X = startPointX, Y = startPointY, Height = height, Width = width }; await encoder.FlushAsync(); BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream); return(await decoder.GetSoftwareBitmapAsync(softwareBitmap.BitmapPixelFormat, softwareBitmap.BitmapAlphaMode)); } }
public static async Task <byte[]> EncodedBytes(SoftwareBitmap soft, Guid encoderId) //see https://stackoverflow.com/questions/31188479/converting-a-videoframe-to-a-byte-array { byte[] array = null; // First: Use an encoder to copy from SoftwareBitmap to an in-mem stream (FlushAsync) // Next: Use ReadAsync on the in-mem stream to get byte[] array using (var ms = new InMemoryRandomAccessStream()) { BitmapEncoder encoder = await BitmapEncoder.CreateAsync(encoderId, ms); encoder.SetSoftwareBitmap(soft); try { await encoder.FlushAsync(); } catch (Exception e) { System.Diagnostics.Debug.WriteLine(e.Message); return(new byte[0]); } array = new byte[ms.Size]; await ms.ReadAsync(array.AsBuffer(), (uint)ms.Size, InputStreamOptions.None); } return(array); }
public static async Task <byte[]> Convert(SoftwareBitmap image) { byte[] byteData = null; if (image == null) { return(new byte[0]); } using (var ms = new InMemoryRandomAccessStream()) { BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, ms); encoder.SetSoftwareBitmap(image); try { await encoder.FlushAsync(); } catch (Exception ex) { System.Diagnostics.Trace.WriteLine(ex.Message); return(new byte[0]); } byteData = new byte[ms.Size]; await ms.ReadAsync(byteData.AsBuffer(), (uint)ms.Size, InputStreamOptions.None); } // Request body. Posts a locally stored JPEG image. return(byteData); }
private async void UISaveImageButton_Click(object sender, RoutedEventArgs e) { FileSavePicker fileSavePicker = new FileSavePicker(); fileSavePicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary; fileSavePicker.DefaultFileExtension = ".jpg"; fileSavePicker.SuggestedFileName = "Cleaned"; fileSavePicker.FileTypeChoices.Add("image", new List <string>() { ".jpg" }); var file = await fileSavePicker.PickSaveFileAsync(); if (file != null) { // Create the encoder from the stream using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite)) { BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream); encoder.SetSoftwareBitmap(m_cachedRectifiedImage.SoftwareBitmap); await encoder.FlushAsync(); } } }
private async Task PasteBitmapImage(DataPackageView dataPackageView) { IRandomAccessStreamReference imageReceived = null; imageReceived = await dataPackageView.GetBitmapAsync(); if (imageReceived != null) { StorageFile file; using (var imageStream = await imageReceived.OpenReadAsync()) { BitmapDecoder decoder = await BitmapDecoder.CreateAsync(imageStream); var softwareBitmap = await decoder.GetSoftwareBitmapAsync(); file = await CreateBitmapFileWithUniqueName(); using (var stream = await file.OpenAsync(FileAccessMode.ReadWrite)) { BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream); encoder.SetSoftwareBitmap(softwareBitmap); encoder.IsThumbnailGenerated = false; await encoder.FlushAsync(); } } await TryAddMedia(file); } }
private async void SaveSoftwareBitmapToFile(SoftwareBitmap softwareBitmap) { FileSavePicker fileSavePicker = new FileSavePicker(); fileSavePicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary; fileSavePicker.FileTypeChoices.Add("JPEG files", new List <string>() { ".jpg" }); fileSavePicker.SuggestedFileName = "image"; var outputFile = await fileSavePicker.PickSaveFileAsync(); if (outputFile != null) { using (IRandomAccessStream stream = await outputFile.OpenAsync(FileAccessMode.ReadWrite)) { // Create an encoder with the desired format BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream); // Set the software bitmap encoder.SetSoftwareBitmap(softwareBitmap); await encoder.FlushAsync(); } } }
/// <summary> /// This function encodes a software bitmap with the specified encoder and saves it to a file /// </summary> /// <param name="softwareBitmap"></param> /// <param name="outputFile"></param> /// <param name="encoderId">The guid of the image encoder type</param> /// <returns></returns> public static async Task SaveSoftwareBitmapToFile(SoftwareBitmap softwareBitmap, StorageFile outputFile, Guid encoderId) { using IRandomAccessStream stream = await outputFile.OpenAsync(FileAccessMode.ReadWrite); // Create an encoder with the desired format BitmapEncoder encoder = await BitmapEncoder.CreateAsync(encoderId, stream); // Set the software bitmap encoder.SetSoftwareBitmap(softwareBitmap); try { await encoder.FlushAsync(); } catch (Exception err) { const int WINCODEC_ERR_UNSUPPORTEDOPERATION = unchecked ((int)0x88982F81); switch (err.HResult) { case WINCODEC_ERR_UNSUPPORTEDOPERATION: // If the encoder does not support writing a thumbnail, then try again // but disable thumbnail generation. encoder.IsThumbnailGenerated = false; break; default: throw; } } if (encoder.IsThumbnailGenerated == false) { await encoder.FlushAsync(); } }
public static async Task <ProgramPickerItem> CreateAsync(AppInfo App) { try { using (IRandomAccessStreamWithContentType LogoStream = await App.DisplayInfo.GetLogo(new Windows.Foundation.Size(128, 128)).OpenReadAsync()) { BitmapDecoder Decoder = await BitmapDecoder.CreateAsync(LogoStream); using (SoftwareBitmap SBitmap = await Decoder.GetSoftwareBitmapAsync(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied)) using (SoftwareBitmap ResizeBitmap = ComputerVisionProvider.ResizeToActual(SBitmap)) using (InMemoryRandomAccessStream Stream = new InMemoryRandomAccessStream()) { BitmapEncoder Encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, Stream); Encoder.SetSoftwareBitmap(ResizeBitmap); await Encoder.FlushAsync(); BitmapImage Logo = new BitmapImage(); await Logo.SetSourceAsync(Stream); return(new ProgramPickerItem(Logo, App.DisplayInfo.DisplayName, App.DisplayInfo.Description, App.PackageFamilyName)); } } } catch (Exception ex) { LogTracer.Log(ex, "An exception was threw when getting or processing App Logo"); return(new ProgramPickerItem(App.DisplayInfo.DisplayName, App.DisplayInfo.Description, App.PackageFamilyName)); } }