示例#1
0
        private async void SaveSoftwareBitmapToFile(SoftwareBitmap softwareBitmap, StorageFile outputFile)
        {
            using (IRandomAccessStream stream = await outputFile.OpenAsync(FileAccessMode.ReadWrite))
            {
                // Create an encoder with the desired format
                BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, stream);

                // Set the software bitmap
                encoder.SetSoftwareBitmap(softwareBitmap);
                encoder.BitmapTransform.InterpolationMode = BitmapInterpolationMode.Fant;
                encoder.IsThumbnailGenerated = true;

                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();
                }
            }
        }
    /// <summary>
    /// Converts this SoftwareBitmap instance to a Stream.
    /// </summary>
    /// <param name="softwareBitmap"></param>
    /// <returns></returns>
    public static async Task <Stream> AsStream(this SoftwareBitmap softwareBitmap)
    {
        var stream = new InMemoryRandomAccessStream();

        BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, stream);

        encoder.SetSoftwareBitmap(softwareBitmap);
        encoder.BitmapTransform.ScaledWidth       = (uint)softwareBitmap.PixelWidth;
        encoder.BitmapTransform.ScaledHeight      = (uint)softwareBitmap.PixelHeight;
        encoder.BitmapTransform.InterpolationMode = BitmapInterpolationMode.Fant;
        await encoder.FlushAsync();

        return(stream.AsStreamForRead());
    }
示例#3
0
        private async Task <IRandomAccessStream> GetRandomAccessStreamFromSoftwareBitmap(SoftwareBitmap soft, Guid encoderId)
        {
            // Use an encoder to copy from SoftwareBitmap to an in-mem stream (FlushAsync)

            InMemoryRandomAccessStream inMemoryStream = new InMemoryRandomAccessStream();

            BitmapEncoder encoder = await BitmapEncoder.CreateAsync(encoderId, inMemoryStream);

            encoder.SetSoftwareBitmap(soft);

            await encoder.FlushAsync();

            return(inMemoryStream);
        }
示例#4
0
        /// <summary>
        /// Evaluates the frame for scene classification
        /// </summary>
        /// <param name="vf"></param>
        /// <returns></returns>
        private static async Task EvaluateFrameAsync(VideoFrame vf)
        {
            // Process 1 frame at a time, if busy return right away
            if (0 == Interlocked.Exchange(ref m_lock, 1))
            {
                // Update input image and run the skill against it
                await m_binding.SetInputImageAsync(vf);

                await m_skill.EvaluateAsync(m_binding);

                string outText = "";
                if (!m_binding.IsFaceFound)
                {
                    // if no face found, hide the rectangle in the UI
                    outText = "No face found";
                }
                else // Display the  sentiment on the console
                {
                    outText = "Your sentiment looks like: " + m_binding.PredominantSentiment.ToString();

                    var folder = await StorageFolder.GetFolderFromPathAsync(System.AppContext.BaseDirectory);

                    var file = await folder.CreateFileAsync(m_binding.PredominantSentiment.ToString() + "Face.jpg", CreationCollisionOption.ReplaceExisting);

                    using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite))
                    {
                        BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream);

                        SoftwareBitmap sb;
                        if (vf.SoftwareBitmap == null)
                        {
                            sb = await SoftwareBitmap.CreateCopyFromSurfaceAsync(vf.Direct3DSurface);
                        }
                        else
                        {
                            sb = vf.SoftwareBitmap;
                        }

                        encoder.SetSoftwareBitmap(
                            sb.BitmapPixelFormat.Equals(BitmapPixelFormat.Bgra8) ? sb : SoftwareBitmap.Convert(sb, BitmapPixelFormat.Bgra8)
                            );
                        await encoder.FlushAsync();
                    }
                }
                Console.Write("\r" + outText + "\t\t\t\t\t");

                // Release the lock
                Interlocked.Exchange(ref m_lock, 0);
            }
        }
        public static async Task <StorageFile> SoftwareBitmapSaveToFile(SoftwareBitmap softwareBitmap, StorageFile file)
        {
            if (softwareBitmap != null && file != null)
            {
                using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite))
                {
                    BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream);

                    encoder.SetSoftwareBitmap(softwareBitmap);
                    await encoder.FlushAsync();
                }
            }
            return(file);
        }
示例#6
0
        private async void MainPage_DataRequested(DataTransferManager sender, DataRequestedEventArgs args)
        {
            var GetFiles = args.Request.GetDeferral();

            try
            {
                var           name       = String.Format("{0}_{1:yyyy-MM-dd_HH-mm-ss}.jpg", "MyApp", DateTime.Now);
                StorageFolder tempFolder = await KnownFolders.PicturesLibrary.CreateFolderAsync("MidTermTemp", CreationCollisionOption.ReplaceExisting);

                StorageFile saveItem = await tempFolder.CreateFileAsync(name, CreationCollisionOption.ReplaceExisting);

                byte[] pixels;
                using (Stream pixelStream = srcWriteAbleBitmap.PixelBuffer.AsStream())
                {
                    pixels = new byte[pixelStream.Length];
                    pixelStream.Read(pixels, 0, pixels.Length);
                    for (int i = 0; i < pixels.Length; i += 4)
                    {
                        byte temp = pixels[i];
                        pixels[i]     = pixels[i + 2];
                        pixels[i + 2] = temp;
                    }
                }
                using (IRandomAccessStream fileStream = await saveItem.OpenAsync(FileAccessMode.ReadWrite))
                {
                    BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, fileStream);

                    encoder.SetPixelData(BitmapPixelFormat.Rgba8, BitmapAlphaMode.Straight,
                                         (uint)srcWriteAbleBitmap.PixelWidth, (uint)srcWriteAbleBitmap.PixelHeight, 96, 96, pixels);
                    await encoder.FlushAsync();

                    using (var outputStream = fileStream.GetOutputStreamAt(0))
                    {
                        await outputStream.FlushAsync();
                    }
                }

                DataPackage data = new DataPackage();
                data.Properties.Title       = "共享图片";
                data.Properties.Description = "分享一些内容。";
                List <IStorageItem> files = new List <IStorageItem>();
                files.Add(saveItem);
                data.SetStorageItems(files);
                args.Request.Data = data;
            }
            finally
            {
                GetFiles.Complete();
            }
        }
        private async Task ExecuteAddPersonCommand()
        {
            if (NewFaceName != string.Empty && Pictures.Count > 0 && SelectedPersonGroup != null)
            {
                IsLoading = true;
                try
                {
                    List <AddPersistedFaceResult> faces = new List <AddPersistedFaceResult>();

                    var result = await FaceService.CreatePersonAsync(SelectedPersonGroup.PersonGroupId, NewFaceName);

                    foreach (var picture in Pictures)
                    {
                        var currentPicture = picture.Bitmap;

                        IRandomAccessStream randomAccessStream = new InMemoryRandomAccessStream();

                        BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, randomAccessStream);

                        encoder.SetSoftwareBitmap(currentPicture);

                        await encoder.FlushAsync();

                        var stream = randomAccessStream.AsStreamForRead();

                        faces.Add(await FaceService.AddPersonFaceAsync(SelectedPersonGroup.PersonGroupId, result.PersonId, stream));
                    }

                    await new MessageDialog($"Successfully added {faces.Count} faces for person {NewFaceName} ({result.PersonId}).").ShowAsync();

                    //Reset the form
                    Pictures.Clear();
                    NewFaceName = "";
                }
                catch (FaceAPIException e)
                {
                    await new MessageDialog(e.ErrorMessage).ShowAsync();
                    //await new MessageDialog(loader.GetString("AddFace_CompleteInformation")).ShowAsync();
                }
                finally
                {
                    IsLoading = false;
                }
            }
            else
            {
                await new MessageDialog(loader.GetString("AddFace_CompleteInformation")).ShowAsync();
            }
        }
示例#8
0
        private async void image_Tapped(object sender, TappedRoutedEventArgs e)
        {
            ;
            FileOpenPicker openPicker = new FileOpenPicker();

            openPicker.ViewMode = PickerViewMode.Thumbnail;
            openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
            openPicker.FileTypeFilter.Add(".jpg");
            openPicker.FileTypeFilter.Add(".jpeg");
            openPicker.FileTypeFilter.Add(".png");

            StorageFile file = await openPicker.PickSingleFileAsync();

            if (file != null)
            {
                // Application now has read/write access to the picked file
                using (IRandomAccessStream fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read))
                {
                    try
                    {
                        BitmapImage bitmapImage = new BitmapImage();
                        //   bitmapImage.DecodePixelWidth = 300;
                        await bitmapImage.SetSourceAsync(fileStream);

                        image.Source = bitmapImage;
                        // Set the image source to the selected bitmap
                        int x = int.Parse(await FileIO.ReadTextAsync(await ApplicationData.Current.LocalFolder.GetFileAsync("count.txt")));
                        Debug.WriteLine(x);
                        BitmapDecoder decoder = await BitmapDecoder.CreateAsync(fileStream.CloneStream());

                        SoftwareBitmap softwareBitmap = await decoder.GetSoftwareBitmapAsync();

                        StorageFile file_Save = await ApplicationData.Current.LocalFolder.CreateFileAsync(x.ToString() + ".png", CreationCollisionOption.ReplaceExisting);

                        x++;
                        await FileIO.WriteTextAsync(await ApplicationData.Current.LocalFolder.CreateFileAsync("count.txt", CreationCollisionOption.ReplaceExisting), x.ToString());

                        BitmapEncoder encoder = await BitmapEncoder.CreateAsync(Windows.Graphics.Imaging.BitmapEncoder.PngEncoderId, await file_Save.OpenAsync(FileAccessMode.ReadWrite));

                        encoder.SetSoftwareBitmap(softwareBitmap);
                        await encoder.FlushAsync();
                    }
                    catch { }
                }
            }
            else
            {
            }
        }
示例#9
0
        /// <summary>

        /// Resizes image data within a stream to a given width and height.

        /// </summary>

        /// <returns>

        /// Returns an image stream with the resized image data.

        /// </returns>

        private static async Task <IRandomAccessStream> ResizeImage(IRandomAccessStream imageStream, uint width, uint height)
        {
            IRandomAccessStream resizedStream = imageStream;

            var decoder = await BitmapDecoder.CreateAsync(imageStream);

            if (decoder.OrientedPixelHeight > height || decoder.OrientedPixelWidth > width)
            {
                resizedStream = new InMemoryRandomAccessStream();

                BitmapEncoder encoder = await BitmapEncoder.CreateForTranscodingAsync(resizedStream, decoder);

                double widthRatio = (double)width / decoder.OrientedPixelWidth;

                double heightRatio = (double)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((double)decoder.OrientedPixelHeight * scaleRatio);

                uint aspectWidth = (uint)Math.Floor((double)decoder.OrientedPixelWidth * scaleRatio);



                encoder.BitmapTransform.ScaledHeight = aspectHeight;

                encoder.BitmapTransform.ScaledWidth = aspectWidth;



                // write out to the stream

                await encoder.FlushAsync();



                // Reset the stream location.

                resizedStream.Seek(0);
            }



            return(resizedStream);
        }
        private async void PickerFile_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                FileOpenPicker Picker = new FileOpenPicker
                {
                    SuggestedStartLocation = PickerLocationId.ComputerFolder,
                    ViewMode = PickerViewMode.List
                };
                Picker.FileTypeFilter.Add(".exe");

                if (await Picker.PickSingleFileAsync() is StorageFile ExcuteFile)
                {
                    DisplayName.Text = Convert.ToString((await ExcuteFile.Properties.RetrievePropertiesAsync(new string[] { "System.FileDescription" }))["System.FileDescription"]);
                    Protocol.Text    = ExcuteFile.Path;

                    if (await ExcuteFile.GetThumbnailBitmapAsync().ConfigureAwait(true) is BitmapImage Image)
                    {
                        Icon.Source = Image;
                    }
                    else
                    {
                        Icon.Source = new BitmapImage(new Uri("ms-appx:///Assets/Page_Solid_White.png"));
                    }

                    RenderTargetBitmap RTB = new RenderTargetBitmap();
                    await RTB.RenderAsync(Icon);

                    StorageFile FileThumbnail = await ApplicationData.Current.TemporaryFolder.CreateFileAsync("FileThumbnail.png", CreationCollisionOption.ReplaceExisting);

                    using (IRandomAccessStream Stream = await FileThumbnail.OpenAsync(FileAccessMode.ReadWrite))
                    {
                        BitmapEncoder Encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, Stream);

                        byte[] PixelData = (await RTB.GetPixelsAsync()).ToArray();

                        Encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied, (uint)RTB.PixelWidth, (uint)RTB.PixelHeight, DisplayInformation.GetForCurrentView().LogicalDpi, DisplayInformation.GetForCurrentView().LogicalDpi, PixelData);

                        await Encoder.FlushAsync();
                    }

                    ImageFile = FileThumbnail;
                }
            }
            catch
            {
                FailureTips.IsOpen = true;
            }
        }
示例#11
0
        async Task <byte[]> GetFrameData(MediaFrameReference frame)
        {
            byte[] bytes = null;

            if (frame == null)
            {
                return(bytes);
            }

            VideoMediaFrame videoMediaFrame = frame.VideoMediaFrame;

            if (videoMediaFrame == null)
            {
                return(bytes);
            }

            VideoFrame     videoFrame     = videoMediaFrame.GetVideoFrame();
            SoftwareBitmap softwareBitmap = videoFrame.SoftwareBitmap;

            if (softwareBitmap == null)
            {
                return(bytes);
            }

            SoftwareBitmap bitmapBGRA8 = SoftwareBitmap.Convert(softwareBitmap, BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore);

            using (InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream())
            {
                BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream);

                // Set the software bitmap
                encoder.SetSoftwareBitmap(bitmapBGRA8);
                encoder.IsThumbnailGenerated = false;

                try
                {
                    await encoder.FlushAsync();

                    bytes = new byte[stream.Size];
                    await stream.AsStream().ReadAsync(bytes, 0, bytes.Length);
                }
                catch (Exception e)
                {
                    Debug.WriteLine($"Error while trying to encode frame into a byte array, expceiton {e.Message}");
                }
            }

            return(bytes);
        }
示例#12
0
        private async void CropperDialogPrimaryButton_Click(object sender, RoutedEventArgs e)
        {
            var imageSource = EditPicture.ProfilePicture;

            byte[] imageBuffer;
            var    localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
            var    file        = await localFolder.CreateFileAsync("temp.jpg", CreationCollisionOption.ReplaceExisting);

            try
            {
                using (var ras = await file.OpenAsync(FileAccessMode.ReadWrite, StorageOpenOptions.None))
                {
                    WriteableBitmap bitmap = imageSource as WriteableBitmap;
                    var             stream = bitmap.PixelBuffer.AsStream();
                    byte[]          buffer = new byte[stream.Length];
                    await stream.ReadAsync(buffer, 0, buffer.Length);

                    BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, ras);

                    encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)bitmap.PixelWidth, (uint)bitmap.PixelHeight, 96.0, 96.0, buffer);
                    await encoder.FlushAsync();

                    var imageStream = ras.AsStream();
                    imageStream.Seek(0, SeekOrigin.Begin);
                    imageBuffer = new byte[imageStream.Length];
                    var re = await imageStream.ReadAsync(imageBuffer, 0, imageBuffer.Length);
                }
                await file.DeleteAsync(StorageDeleteOption.Default);

                List <PersonPictures> datalist = conn.Query <PersonPictures>("select * from PersonPictures where pictureName = ?", "picture");
                if (datalist != null)
                {
                    conn.Execute("delete from PersonPictures where pictureName = ?", "picture");
                }
                conn.Insert(new PersonPictures()
                {
                    pictureName = "picture", picture = imageBuffer
                });
                SetPersonPicture();
                PopupNotice popupNotice = new PopupNotice("头像已更新");
                popupNotice.ShowAPopup();
            }
            catch
            {
                TempPicture.Visibility = Visibility.Visible;
                EditPicture.Visibility = Visibility.Collapsed;
            };
            CropperDialog.Hide();
        }
示例#13
0
        public static async Task <byte[]> ResizeImageByteAsync(byte[] imageByteData, int reqWidth, int reqHeight)
        {
            var memStream = new MemoryStream(imageByteData);

            IRandomAccessStream imageStream = memStream.AsRandomAccessStream();
            var decoder = await BitmapDecoder.CreateAsync(imageStream);

            if (decoder.PixelHeight > reqHeight || decoder.PixelWidth > reqWidth)
            {
                using (imageStream)
                {
                    var resizedStream = new InMemoryRandomAccessStream();

                    BitmapEncoder encoder = await BitmapEncoder.CreateForTranscodingAsync(resizedStream, decoder);

                    double widthRatio  = (double)reqWidth / decoder.PixelWidth;
                    double heightRatio = (double)reqHeight / decoder.PixelHeight;

                    double scaleRatio = Math.Min(widthRatio, heightRatio);

                    if (reqWidth == 0)
                    {
                        scaleRatio = heightRatio;
                    }

                    if (reqHeight == 0)
                    {
                        scaleRatio = widthRatio;
                    }

                    uint aspectHeight = (uint)Math.Floor(decoder.PixelHeight * scaleRatio);
                    uint aspectWidth  = (uint)Math.Floor(decoder.PixelWidth * scaleRatio);

                    encoder.BitmapTransform.InterpolationMode = BitmapInterpolationMode.Linear;

                    encoder.BitmapTransform.ScaledHeight = aspectHeight;
                    encoder.BitmapTransform.ScaledWidth  = aspectWidth;

                    await encoder.FlushAsync();

                    resizedStream.Seek(0);
                    var outBuffer = new byte[resizedStream.Size];
                    await resizedStream.ReadAsync(outBuffer.AsBuffer(), (uint)resizedStream.Size, InputStreamOptions.None);

                    return(outBuffer);
                }
            }
            return(imageByteData);
        }
示例#14
0
        public static async Task SaveToFileAsync(this WriteableBitmap image, StorageFile newFile)
        {
            if (image == null)
            {
                return;
            }
            Guid BitmapEncoderGuid = BitmapEncoder.JpegEncoderId;
            var  path = newFile.Path;

            if (path.EndsWith("jpg"))
            {
                BitmapEncoderGuid = BitmapEncoder.JpegEncoderId;
            }
            else if (path.EndsWith("png"))
            {
                BitmapEncoderGuid = BitmapEncoder.PngEncoderId;
            }
            else if (path.EndsWith("bmp"))
            {
                BitmapEncoderGuid = BitmapEncoder.BmpEncoderId;
            }
            else if (path.EndsWith("tiff"))
            {
                BitmapEncoderGuid = BitmapEncoder.TiffEncoderId;
            }
            else if (path.EndsWith("gif"))
            {
                BitmapEncoderGuid = BitmapEncoder.GifEncoderId;
            }
            //var folder = await _local_folder.CreateFolderAsync("images_cache", CreationCollisionOption.OpenIfExists);
            //var file = await KnownFolders.PicturesLibrary.CreateFileAsync(newFile, CreationCollisionOption.GenerateUniqueName);

            using (IRandomAccessStream stream = await newFile.OpenAsync(FileAccessMode.ReadWrite))
            {
                BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoderGuid, stream);

                Stream pixelStream = image.PixelBuffer.AsStream();
                byte[] pixels      = new byte[pixelStream.Length];
                await pixelStream.ReadAsync(pixels, 0, pixels.Length);

                encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore,
                                     (uint)image.PixelWidth,
                                     (uint)image.PixelHeight,
                                     96.0,
                                     96.0,
                                     pixels);
                await encoder.FlushAsync();
            }
        }
示例#15
0
        private async void EncodedPhoto(IRandomAccessStream inStream, IRandomAccessStream outStream)
        {
            Guid          JpegDecodderID = BitmapDecoder.JpegDecoderId;
            Guid          JpegEncoderID  = BitmapEncoder.JpegEncoderId;
            BitmapDecoder decoder        = await BitmapDecoder.CreateAsync(JpegDecodderID, inStream);

            BitmapEncoder encoder = await BitmapEncoder.CreateForTranscodingAsync(outStream, decoder);

            encoder.BitmapTransform.Flip = BitmapFlip.Horizontal;
            encoder.BitmapTransform.InterpolationMode = Windows.Graphics.Imaging.BitmapInterpolationMode.Fant;
            encoder.IsThumbnailGenerated = true;
            await encoder.FlushAsync();

            (App.Current as App).IsProcessingPicture = false;
        }
        /// <summary>
        /// Uploads a photo as a WriteableBitmap. This methods converts the given bitmap to a PNG file before sending it to the server.
        /// </summary>
        /// <param name="uri"></param>
        /// <param name="bmp"></param>
        /// <returns></returns>
        public static async Task UploadImage(string uri, WriteableBitmap bmp)
        {
            InMemoryRandomAccessStream memoryStream = new InMemoryRandomAccessStream();
            BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, memoryStream);

            encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied, (uint)bmp.PixelWidth, (uint)bmp.PixelHeight, 96, 96, bmp.PixelBuffer.ToArray());
            await encoder.FlushAsync();

            Stream stream = memoryStream.AsStreamForRead();

            byte[] pngBuffer = new byte[stream.Length];
            stream.Read(pngBuffer, 0, pngBuffer.Length);

            await UploadImage(uri, pngBuffer);
        }
示例#17
0
        public static async Task <byte[]> AsImageBytesAsync(this RenderTargetBitmap bitmap, IBuffer pixelBuffer, BitmapEncoder enc, IRandomAccessStream memoryStream)
        {
            var alphaMode = enc.EncoderInformation.CodecId == BitmapEncoder.JpegEncoderId ? BitmapAlphaMode.Ignore : BitmapAlphaMode.Premultiplied;

            enc.SetPixelData(BitmapPixelFormat.Bgra8, alphaMode, (uint)bitmap.PixelWidth, (uint)bitmap.PixelHeight, 1, 1, pixelBuffer.ToArray());
            await enc.FlushAsync();

            await memoryStream.FlushAsync();

            var stream = memoryStream.AsStream();

            byte[] result = new byte[stream.Length];
            stream.Read(result, 0, result.Length);
            return(result);
        }
示例#18
0
        private async Task <IRandomAccessStream> Convert(WriteableBitmap writeableBitmap)
        {
            var           stream  = new InMemoryRandomAccessStream();
            BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, stream);

            Stream pixelStream = writeableBitmap.PixelBuffer.AsStream();

            byte[] pixels = new byte[pixelStream.Length];
            await pixelStream.ReadAsync(pixels, 0, pixels.Length);

            encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight, (uint)writeableBitmap.PixelWidth, (uint)writeableBitmap.PixelHeight, 96.0, 96.0, pixels);
            await encoder.FlushAsync();

            return(stream);
        }
示例#19
0
        private static async Task WriteToFileAsync(StorageFolder folder, SoftwareBitmap sb, string fileName)
        {
            if (sb != null)
            {
                // save image file to cache
                StorageFile file = await folder.CreateFileAsync(fileName, CreationCollisionOption.OpenIfExists);

                using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite)) {
                    BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream);

                    encoder.SetSoftwareBitmap(sb);
                    await encoder.FlushAsync();
                }
            }
        }
示例#20
0
        public static async Task SaveCroppedBitmap(StorageFile origintalImageFile, StorageFile croppedImageFile, Point startPoint, Size cropSize)
        {
            uint startPointX = (uint)Math.Floor(startPoint.X);
            uint startPointY = (uint)Math.Floor(startPoint.Y);
            uint height      = (uint)Math.Floor(cropSize.Height);
            uint width       = (uint)Math.Floor(cropSize.Width);

            using (IRandomAccessStream originalImageFileStream = await origintalImageFile.OpenReadAsync())
            {
                BitmapDecoder decoder = await BitmapDecoder.CreateAsync(originalImageFileStream);

                if (startPointX + width > decoder.PixelWidth)
                {
                    startPointX = decoder.PixelWidth - width;
                }
                if (startPointY + height > decoder.PixelHeight)
                {
                    startPointY = decoder.PixelHeight - height;
                }

                byte[] pixels = await GetPixelData(decoder, startPointX, startPointY, width, height, decoder.PixelWidth, decoder.PixelHeight);

                using (IRandomAccessStream newImageFileStream = await croppedImageFile.OpenAsync(FileAccessMode.ReadWrite))
                {
                    Guid encoderID = Guid.Empty;

                    switch (croppedImageFile.FileType.ToLower())
                    {
                    case ".png":
                        encoderID = BitmapEncoder.PngEncoderId;
                        break;

                    case ".bmp":
                        encoderID = BitmapEncoder.BmpEncoderId;
                        break;

                    default:
                        encoderID = BitmapEncoder.JpegEncoderId;
                        break;
                    }

                    BitmapEncoder bmpEncoder = await BitmapEncoder.CreateAsync(encoderID, newImageFileStream);

                    bmpEncoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight, width, height, decoder.DpiX, decoder.DpiY, pixels);
                    await bmpEncoder.FlushAsync();
                }
            }
        }
        private async Task ResizeImageWithoutBitmap(StorageFile file, int width, int height)
        {
            using (IRandomAccessStream fileStream = await file.OpenAsync(FileAccessMode.ReadWrite))
            {
                var decoder = await BitmapDecoder.CreateAsync(fileStream);

                var resizedStream = new InMemoryRandomAccessStream();

                BitmapEncoder encoder = await BitmapEncoder.CreateForTranscodingAsync(resizedStream, decoder);

                double widthRatio  = (double)width / decoder.PixelWidth;
                double heightRatio = (double)height / decoder.PixelHeight;

                double scaleRatio = Math.Min(widthRatio, heightRatio);

                if (width == 0)
                {
                    scaleRatio = heightRatio;
                }

                if (height == 0)
                {
                    scaleRatio = widthRatio;
                }

                uint aspectHeight = (uint)Math.Floor(decoder.PixelHeight * scaleRatio);
                uint aspectWidth  = (uint)Math.Floor(decoder.PixelWidth * scaleRatio);

                encoder.BitmapTransform.InterpolationMode = BitmapInterpolationMode.Linear;

                encoder.BitmapTransform.ScaledHeight = aspectHeight;
                encoder.BitmapTransform.ScaledWidth  = aspectWidth;

                await encoder.FlushAsync();

                resizedStream.Seek(0);
                var outBuffer = new byte[resizedStream.Size];
                await resizedStream.ReadAsync(outBuffer.AsBuffer(), (uint)resizedStream.Size, InputStreamOptions.None);



                StorageFolder storageFolder = ApplicationData.Current.LocalFolder;
                Debug.WriteLine(storageFolder.Path);
                StorageFile sampleFile = await storageFolder.CreateFileAsync(Guid.NewGuid().ToString() + ".png", CreationCollisionOption.ReplaceExisting);

                await FileIO.WriteBytesAsync(sampleFile, outBuffer);
            }
        }
示例#22
0
        public async Task LoadFromBytes(byte[] bytes, int width, int height)
        {
            this.bytes  = bytes;
            this.width  = width;
            this.height = height;

            //error checking
            if ((width * height) != (bytes.Length / 4))
            {
                throw new ArgumentException();
            }

            //creates the stream from the byte array

            /*
             *
             * stream = new InMemoryRandomAccessStream();
             * await stream.WriteAsync(bytes.AsBuffer());
             * stream.Seek(0);
             *
             * //creats the bitmapImage from the stream
             * image = new BitmapImage();
             * image.SetSource(stream);
             *
             */

            // Uh yeah sure
            stream      = new InMemoryRandomAccessStream();
            stream.Size = 0;
            BitmapEncoder encode = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, stream);

            // Set the byte array
            encode.SetPixelData(BitmapPixelFormat.Rgba8, BitmapAlphaMode.Straight,
                                (uint)width, (uint)height, 96.0, 96.0,
                                bytes);

            // Go into the stream plz
            await encode.FlushAsync();

            image = new BitmapImage();
            image.SetSource(stream);

            //read only stream to initialize the decoder and softwareBitmap
            decoder = await BitmapDecoder.CreateAsync(stream);

            // There's probably a way to do this better...
            softMap = await decoder.GetSoftwareBitmapAsync();
        }
示例#23
0
        /// <summary>
        /// captures and saves the 16:9 image with only rotation applied, as no cropping is needed
        /// </summary>
        private async void CaptureSixteenByNineImage()
        {
            //declare string for filename
            string captureFileName = string.Empty;
            //declare image format
            ImageEncodingProperties format = ImageEncodingProperties.CreateJpeg();

            //rotate and save the image
            using (var imageStream = new InMemoryRandomAccessStream())
            {
                //generate stream from MediaCapture
                await captureManager.CapturePhotoToStreamAsync(format, imageStream);

                //create decoder and encoder
                BitmapDecoder dec = await BitmapDecoder.CreateAsync(imageStream);

                BitmapEncoder enc = await BitmapEncoder.CreateForTranscodingAsync(imageStream, dec);

                //roate the image
                enc.BitmapTransform.Rotation = BitmapRotation.Clockwise90Degrees;

                //write changes to the image stream
                await enc.FlushAsync();

                //save the image
                StorageFolder folder      = KnownFolders.SavedPictures;
                StorageFile   capturefile = await folder.CreateFileAsync("photo_" + DateTime.Now.Ticks.ToString() + ".jpg", CreationCollisionOption.ReplaceExisting);

                captureFileName = capturefile.Name;

                //store stream in file
                using (var fileStream = await capturefile.OpenStreamForWriteAsync())
                {
                    try
                    {
                        //because of using statement stream will be closed automatically after copying finished
                        await RandomAccessStream.CopyAsync(imageStream, fileStream.AsOutputStream());
                    }
                    catch
                    {
                    }
                }
            }
            CleanCapture();

            //load saved image
            LoadCapturedphoto(captureFileName);
        }
        private async Task CheckSmileAsync()
        {
            if (IsCheckSmileEnabled && _isCheckingSmile != 1 && (_lastSmileCheck == null || _lastSmileCheck < DateTime.Now.AddSeconds(-1)))
            {
                // 0 indicates that the method is not in use.
                if (0 == Interlocked.Exchange(ref _isCheckingSmile, 1))
                {
                    _lastSmileCheck = DateTime.Now;

                    var requiedFaceAttributes = new[] { FaceAttributeType.Smile };
                    if (VideoCapture.VideoDeviceController.GetMediaStreamProperties(MediaStreamType.VideoPreview) is VideoEncodingProperties previewProperties)
                    {
                        double     scale      = 480d / previewProperties.Height;
                        VideoFrame videoFrame = new VideoFrame(BitmapPixelFormat.Bgra8, (int)(previewProperties.Width * scale), 480);
                        using (var frame = await VideoCapture.GetPreviewFrameAsync(videoFrame))
                        {
                            if (frame.SoftwareBitmap != null)
                            {
                                var bitmap = frame.SoftwareBitmap;

                                InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream();
                                BitmapEncoder encoder             = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream);

                                encoder.SetSoftwareBitmap(bitmap);

                                await encoder.FlushAsync();

                                if (NetworkHelper.Instance.ConnectionInformation.IsInternetAvailable)
                                {
                                    var detect = await FaceClient.DetectAsync(stream.AsStream(), false, false, requiedFaceAttributes);

                                    if (detect.Any())
                                    {
                                        var biggestFace = detect.OrderByDescending(f => f.FaceRectangle.Height * f.FaceRectangle.Width).First();
                                        if (biggestFace.FaceAttributes.Smile > 0.5)//TODO add || no internet
                                        {
                                            SmileDetected?.Invoke(this, biggestFace);
                                        }
                                    }
                                }
                            }
                        }
                    }

                    Interlocked.Exchange(ref _isCheckingSmile, 0);
                }
            }
        }
示例#25
0
        private async void Grid_KeyDown(object sender, KeyRoutedEventArgs e)
        {
            if (e.Key == VirtualKey.V)
            {
                bool ctrl = CoreWindow.GetForCurrentThread().GetKeyState(VirtualKey.Control).HasFlag(CoreVirtualKeyStates.Down);
                if (ctrl)
                {
                    var dataPackageView = Clipboard.GetContent();
                    if (dataPackageView.Contains(StandardDataFormats.StorageItems))
                    {
                        var pastedFiles = await dataPackageView.GetStorageItemsAsync();

                        var pastedFile = pastedFiles[0];
                        SelectedFile = pastedFile as StorageFile;
                        AddedAttachmentDisplay.ShowAttachment(SelectedFile.Name);
                        UpdateSendButtonIcon();
                    }
                    else if (dataPackageView.Contains(StandardDataFormats.Bitmap))
                    {
                        RandomAccessStreamReference pastedBitmap = await dataPackageView.GetBitmapAsync();

                        var pastedBitmapStream = await pastedBitmap.OpenReadAsync();

                        var tmpFile = await ApplicationData.Current.TemporaryFolder.CreateFileAsync("Signal-Windows-Screenshot.png", CreationCollisionOption.GenerateUniqueName);

                        using (var tmpFileStream = await tmpFile.OpenAsync(FileAccessMode.ReadWrite))
                        {
                            BitmapDecoder decoder = await BitmapDecoder.CreateAsync(pastedBitmapStream);

                            var pixels = await decoder.GetPixelDataAsync();

                            BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, tmpFileStream);

                            encoder.SetPixelData(decoder.BitmapPixelFormat,
                                                 BitmapAlphaMode.Ignore, // Alpha is not used
                                                 decoder.OrientedPixelWidth,
                                                 decoder.OrientedPixelHeight,
                                                 decoder.DpiX, decoder.DpiY,
                                                 pixels.DetachPixelData());
                            await encoder.FlushAsync();
                        }
                        SelectedFile = tmpFile;
                        AddedAttachmentDisplay.ShowAttachment(SelectedFile.Name);
                        UpdateSendButtonIcon();
                    }
                }
            }
        }
示例#26
0
        public static async Task <FileUpdateStatus> SaveStreamToImage(PickerLocationId location, string fileName, Stream stream, int pixelWidth, int pixelHeight)
        {
            var savePicker = new FileSavePicker
            {
                SuggestedStartLocation = location
            };

            savePicker.FileTypeChoices.Add("Png Image", new[] { ".png" });
            savePicker.SuggestedFileName = fileName;
            StorageFile sFile = await savePicker.PickSaveFileAsync();

            if (sFile != null)
            {
                CachedFileManager.DeferUpdates(sFile);

                using (var fileStream = await sFile.OpenAsync(FileAccessMode.ReadWrite))
                {
                    var localDpi = Windows.Graphics.Display.DisplayInformation.GetForCurrentView().LogicalDpi;

                    BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, fileStream);

                    await encoder.BitmapContainerProperties.SetPropertiesAsync(new BitmapPropertySet
                    {
                        {
                            "System.Comment",
                            new BitmapTypedValue("Exported via Character Map UWP", Windows.Foundation.PropertyType.String)
                        }
                    });

                    Stream pixelStream = stream;
                    byte[] pixels      = new byte[pixelStream.Length];
                    await pixelStream.ReadAsync(pixels, 0, pixels.Length);

                    encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight,
                                         (uint)pixelWidth,
                                         (uint)pixelHeight,
                                         localDpi,
                                         localDpi,
                                         pixels);
                    await encoder.FlushAsync();
                }

                FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(sFile);

                return(status);
            }
            return(FileUpdateStatus.Failed);
        }
示例#27
0
        private async Task SaveWizSFTBPAsync(IRandomAccessStream randomStream)
        {
            BitmapDecoder decoder = await BitmapDecoder.CreateAsync(randomStream);

            SoftwareBitmap softBmp = await decoder.GetSoftwareBitmapAsync(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied);

            var file = await ApplicationData.Current.LocalFolder.CreateFileAsync("Testimage.jpg", CreationCollisionOption.GenerateUniqueName);

            using (var stream = await file.OpenAsync(FileAccessMode.ReadWrite))
            {
                BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream);

                encoder.SetSoftwareBitmap(softBmp);
                await encoder.FlushAsync();
            }
        }
示例#28
0
        private async Task SaveCanvasAsImage(StorageFile file)
        {
            using (var stream = await file.OpenAsync(FileAccessMode.ReadWrite))
            {
                RenderTargetBitmap rtb        = new RenderTargetBitmap();
                BitmapEncoder      bmpEncoder = await BitmapEncoder.CreateAsync(BitmapEncoder.BmpEncoderId, stream);

                await rtb.RenderAsync(MyCanvas);

                var buffer = await rtb.GetPixelsAsync();

                SoftwareBitmap softwareBitmap = SoftwareBitmap.CreateCopyFromBuffer(buffer, BitmapPixelFormat.Bgra8, rtb.PixelWidth, rtb.PixelHeight);
                bmpEncoder.SetSoftwareBitmap(softwareBitmap);
                await bmpEncoder.FlushAsync();
            }
        }
示例#29
0
        // Variant of CopyImageUsingMemoryStream avoiding use of pixelBuffer.ToArray(), but
        // new SoftwareBitmap() and SoftwareBitmap.CopyFromBuffer have the save duplication cost
        internal async static Task CopyImageUsingMemoryStreamAndSoftwareBitmap(IBuffer pixelBuffer, int width, int height)
        {
            SoftwareBitmap sbmp = new SoftwareBitmap(BitmapPixelFormat.Bgra8, width, height, BitmapAlphaMode.Straight);

            sbmp.CopyFromBuffer(pixelBuffer);

            ma1 = new InMemoryRandomAccessStream();
            BitmapEncoder be = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, ma1);

            be.SetSoftwareBitmap(sbmp);
            await be.FlushAsync();

            var rasr = RandomAccessStreamReference.CreateFromStream(ma1);

            ClipboardSetImage(rasr);
        }
示例#30
0
        /// <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()");
        }