예제 #1
0
        private static async Task <Stream> GetPhotoStreamAsync(MediaCapture mediaCapture)
        {
            InMemoryRandomAccessStream photoStream = new InMemoryRandomAccessStream();
            await mediaCapture.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), photoStream);

            photoStream.AsStreamForRead().Seek(0, SeekOrigin.Begin);
            return(photoStream.AsStreamForRead());
        }
예제 #2
0
        internal async Task <Stream> PlatformOpenReadAsync(ScreenshotFormat format)
        {
            if (bytes == null)
            {
                var pixels = await bmp.GetPixelsAsync().AsTask().ConfigureAwait(false);

                bytes = pixels.ToArray();
            }

            var f = format switch
            {
                ScreenshotFormat.Jpeg => BitmapEncoder.JpegEncoderId,
                _ => BitmapEncoder.PngEncoderId
            };

            var ms = new InMemoryRandomAccessStream();

            var encoder = await BitmapEncoder.CreateAsync(f, ms).AsTask().ConfigureAwait(false);

            encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)Width, (uint)Height, 96, 96, bytes);
            await encoder.FlushAsync().AsTask().ConfigureAwait(false);

            return(ms.AsStreamForRead());
        }
    }
예제 #3
0
        /// <inheritdoc/>
        public override async Task <(Stream stream, Exception error)> OpenEntryAsync(string entry)
        {
            var(irs, error) = await this.OpenEntryAsRandomAccessStreamAsync(entry);

            if (error != null)
            {
                return(null, error);
            }

            var decoder = await BitmapDecoder.CreateAsync(irs);

            var bitmap = decoder.GetSoftwareBitmapAsync();

            var outputIrs = new InMemoryRandomAccessStream();

            var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, outputIrs);

            encoder.SetSoftwareBitmap(await bitmap);

            await encoder.FlushAsync();

            var outputStream = new MemoryStream();

            outputIrs.Seek(0);
            outputIrs.AsStreamForRead().CopyTo(outputStream);

            outputIrs.Dispose();
            outputStream.Seek(0, SeekOrigin.Begin);

            return(outputStream, null);
        }
예제 #4
0
        public async Task <Stream> GetCurrentFrameAsync()
        {
            if (CurrentState != ScenarioState.Streaming)
            {
                return(null);
            }

            // If a lock is being held it means we're still waiting for processing work on the previous frame to complete.
            // In this situation, don't wait on the semaphore but exit immediately.
            if (!frameProcessingSemaphore.Wait(0))
            {
                return(null);
            }

            try
            {
                var stream = new InMemoryRandomAccessStream();
                await mediaCapture.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), stream);

                stream.Seek(0);
                return(stream.AsStreamForRead());
            }
            catch
            {
            }
            finally
            {
                frameProcessingSemaphore.Release();
            }

            return(null);
        }
예제 #5
0
        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);
                }
            }
        }
예제 #6
0
        public async Task <byte[]> CaptureAsync()
        {
            var rtb = new RenderTargetBitmap();
            await rtb.RenderAsync(Window.Current.Content);

            var pixelBuffer = await rtb.GetPixelsAsync();

            byte[] pixels;
            CryptographicBuffer.CopyToByteArray(pixelBuffer, out pixels);

            // Useful for rendering in the correct DPI
            var displayInformation = DisplayInformation.GetForCurrentView();

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

            encoder.SetPixelData(BitmapPixelFormat.Bgra8,
                                 BitmapAlphaMode.Premultiplied,
                                 (uint)rtb.PixelWidth,
                                 (uint)rtb.PixelHeight,
                                 displayInformation.RawDpiX,
                                 displayInformation.RawDpiY,
                                 pixels);

            await encoder.FlushAsync();

            stream.Seek(0);

            var readStram = stream.AsStreamForRead();
            var bytes     = new byte[readStram.Length];

            readStram.Read(bytes, 0, bytes.Length);

            return(bytes);
        }
예제 #7
0
        public async Task <Stream> PickImage(ImageLocation location = ImageLocation.All, int maxSize = int.MaxValue)
        {
            var raw = await PickImageRaw(location);

            if (raw == null)
            {
                return(null);
            }

            using (var stream = await raw.OpenReadAsync())
            {
                var decoder = await BitmapDecoder.CreateAsync(stream);

                var size = MediaHelper.Crop((int)decoder.PixelWidth, (int)decoder.PixelHeight, maxSize);
                if (size.Item1 != decoder.PixelWidth || size.Item2 != decoder.PixelHeight)
                {
                    var ms      = new InMemoryRandomAccessStream();
                    var encoder = await BitmapEncoder.CreateForTranscodingAsync(ms, decoder);

                    encoder.BitmapTransform.ScaledWidth  = (uint)size.Item1;
                    encoder.BitmapTransform.ScaledHeight = (uint)size.Item2;
                    await encoder.FlushAsync();

                    return(ms.AsStreamForRead());
                }
            }

            return(await raw.OpenStreamForReadAsync());
        }
        // encodes bytes into a b64 string in png format, must also specify height and width
        public static async Task <string> EncodeBytesToPNGString(byte[] bytes, uint width, uint height)
        {
            using (IRandomAccessStream destStream = new InMemoryRandomAccessStream())
            {
                // encoder, assumes input bytes are Bgra8
                var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, destStream);

                encoder.SetPixelData(
                    BitmapPixelFormat.Bgra8,
                    BitmapAlphaMode.Straight,
                    width,
                    height,
                    96,
                    96,
                    bytes
                    );

                // encode
                await encoder.FlushAsync();

                // convert the stream to bytes
                byte[] encodedBytes = new byte[destStream.Size];
                destStream.AsStreamForRead().Read(encodedBytes, 0, (int)destStream.Size);

                // and finally encode the bytes to a string
                return(Convert.ToBase64String(encodedBytes.ToArray()));
            }
        }
예제 #9
0
        /// <summary>
        /// Convert WriteableBitmap to byte
        /// </summary>
        /// <param name="writeableBitmap"></param>
        /// <returns></returns>
        public async static Task <byte[]> GetPhotoBytesAsync(this WriteableBitmap writeableBitmap)
        {
            if (writeableBitmap == null)
            {
                return new byte[0] {
                }
            }
            ;
            Stream stream = writeableBitmap.PixelBuffer.AsStream();

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

            ConvertToRGBA(writeableBitmap.PixelHeight, writeableBitmap.PixelWidth, pixels);
            InMemoryRandomAccessStream ims = new InMemoryRandomAccessStream();
            var imsWriter = ims.AsStreamForWrite();
            await Task.Factory.StartNew(() => stream.CopyTo(imsWriter));

            stream.Flush();
            stream.Dispose();
            BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, ims);

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

            stream = ims.AsStreamForRead();
            byte[] pixeBuffer = new byte[ims.Size];
            await stream.ReadAsync(pixeBuffer, 0, pixeBuffer.Length);

            stream.Flush();
            stream.Dispose();
            return(pixeBuffer);
        }
예제 #10
0
        async Task <Stream> PlatformOpenReadAsync(ScreenshotFormat format, int quality)
        {
            var ms = new InMemoryRandomAccessStream();

            await EncodeAsync(format, ms).ConfigureAwait(false);

            return(ms.AsStreamForRead());
        }
예제 #11
0
        private async Task <Dictionary <TimeSpan, Face[]> > DetectFace_Video(StorageFile fileData)
        {
            // Process configs
            const int frameJumpSize = 15;
            const int frameQuota    = 20;
            const int frameTimeout  = 60_000;

            // Video
            var videoProperties = await fileData.Properties.GetVideoPropertiesAsync();

            var videoTime  = TimeSpan.FromSeconds(0);
            var videoFrame = 0;

            // DetectedFaces
            var detectedFaces = new Dictionary <TimeSpan, Face[]>();

            // Process every frame
            while (videoTime < videoProperties.Duration)
            {
                // Frame cut
                var mediaClip = await MediaClip.CreateFromFileAsync(fileData);

                var mediaComposition = new MediaComposition();
                mediaComposition.Clips.Add(mediaClip);
                var frame = await mediaComposition.GetThumbnailAsync(
                    videoTime,
                    0,
                    0,
                    VideoFramePrecision.NearestFrame
                    );

                // Stream conversion
                var randomAccessStream = new InMemoryRandomAccessStream();
                await RandomAccessStream.CopyAsync(frame, randomAccessStream);

                randomAccessStream.Seek(0);

                // Process and add image
                var detectedFace = await DetectFace_Image(randomAccessStream.AsStreamForRead());

                if (detectedFace != null)
                {
                    detectedFaces.Add(videoTime, detectedFace);
                }

                // Quota overflow
                if (videoFrame != 0 && videoFrame % frameQuota == 0)
                {
                    await Task.Delay(frameTimeout);
                }

                // Frame and time incrementation
                videoTime  += TimeSpan.FromSeconds(frameJumpSize);
                videoFrame += 1;
            }

            return(detectedFaces);
        }
        internal static async Task <Stream> GetStreamFromVideoFrameAsync(VideoFrame frame)
        {
            InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream();
            BitmapEncoder encoder             = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream);

            encoder.SetSoftwareBitmap(frame.SoftwareBitmap);
            await encoder.FlushAsync();

            return(stream.AsStreamForRead());
        }
예제 #13
0
        // TODO: in x64 Release mode doesn't work
        // with the current SixLabors.ImageSharp.Drawing beta version
        //public Image<Rgba32> SearchAndReplace(Image<Rgba32> masterImage, int ratio = 5)
        //{
        //    var text = GenerateText(masterImage, ratio);
        //    var font = SystemFonts.CreateFont("Courier New", 14);
        //    var size = TextMeasurer.Measure(text, new RendererOptions(font));

        //    var finalImage = new Image<Rgba32>((int)size.Width, (int)size.Height);
        //    finalImage.Mutate(i =>
        //    {
        //        i.Fill(Color.White);
        //        i.DrawText(text, font, Color.Black, new PointF(0, 0));
        //    });

        //    return finalImage;
        //}

        private async Task <Image <Rgba32> > Generate(CanvasRenderTarget renderTarget)
        {
            Image <Rgba32>      finalImage;
            IRandomAccessStream inputRandomAccessStream = new InMemoryRandomAccessStream();
            await renderTarget.SaveAsync(inputRandomAccessStream, CanvasBitmapFileFormat.Png);

            finalImage = Image.Load <Rgba32>(inputRandomAccessStream.AsStreamForRead());

            return(finalImage);
        }
예제 #14
0
        public static async Task <string> ToBase64String(this CanvasBitmap bitmap)
        {
            using var ms = new InMemoryRandomAccessStream();
            await bitmap.SaveAsync(ms, CanvasBitmapFileFormat.Png);

            using var ms2 = new MemoryStream();
            await ms.AsStreamForRead().CopyToAsync(ms2);

            return(Convert.ToBase64String(ms2.ToArray()));
        }
예제 #15
0
        public Stream CompressBitmap(byte[] data, int w, int h)
        {
            var memStream = new InMemoryRandomAccessStream();

            Encode(data, (uint)w, (uint)h, memStream);
            var stream = memStream.AsStreamForRead();

            Logger($"Log Encode stream for bugfix:{memStream.Size} => {stream.Length} bytes");
            return(stream);
        }
        public void WriteJpeg(InMemoryRandomAccessStream imageStream)
        {
            Write("Content-Length: " + imageStream.Size.ToString() + "\r\n\r\n");
            Stream s = imageStream.AsStreamForRead();

            s.Position = 0;
            s.CopyTo(_httpSocketStream);
            _httpSocketStream.Flush();
            _httpSocketStream.Close();
        }
예제 #17
0
        /// <summary>
        /// Handle a face detected event
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        private async void FaceDetectionEffect_FaceDetected(FaceDetectionEffect sender, FaceDetectedEventArgs args)
        {
            // Only run one face detection call to Cognitive Services at a time
            if (!_isRecognizing)
            {
                //If we need the box for the detected face we can get them here
                //foreach (Windows.Media.FaceAnalysis.DetectedFace face in args.ResultFrame.DetectedFaces)
                //{
                //    BitmapBounds faceRect = face.FaceBox;
                //}

                _isRecognizing = true;

                var lowLagCapture = await _mediaCapture.PrepareLowLagPhotoCaptureAsync(ImageEncodingProperties.CreateUncompressed(MediaPixelFormat.Bgra8));

                var capturedPhoto = await lowLagCapture.CaptureAsync();

                var softwareBitmap = capturedPhoto.Frame.SoftwareBitmap;

                await lowLagCapture.FinishAsync();

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

                    encoder.SetSoftwareBitmap(softwareBitmap);

                    await encoder.FlushAsync();

                    var stream = randomAccessStream.AsStreamForRead();

                    try
                    {
                        //This call the Cognitive Services face API to detect the faces
                        var faces = await FaceService.DetectAsync(stream, true, false);

                        List <Guid> faceList = new List <Guid>();

                        foreach (var face in faces)
                        {
                            faceList.Add(face.FaceId);
                        }

                        LastFaces = faceList.ToArray();
                    }
                    catch
                    {
                        //We could not detect faces using Cognitive Services
                    }
                }

                _isRecognizing = false;
            }
        }
        public static async Task LoadImages()
        {
            double dpiMultiplier = Windows.Graphics.Display.DisplayInformation.GetForCurrentView().LogicalDpi / 96.0;

            for (int i = 0; i < NUM_ICON_SIZES; i++)
            {
                for (int j = 0; j < NUM_ICON_TYPES; j++)
                {
                    //string postfix;
                    //if (j >= 1 && j <= 8)
                    //    postfix = "BusDirection" + ((StopDirection)j).ToString();
                    //else if (j == 0)
                    //    postfix = "BusBase";
                    //else
                    //    postfix = j == 9 ? "BusAlert" : "BusClosed";
                    //postfix += (i == 0 ? "20" : "40");
                    //var sprite = new Sprite() { ImageUri = new Uri($"ms-appx:///Assets/Icons/{postfix}.png") };
                    //await sprite.Load();
                    //sprite.Unlock();
                    //var buffer1 = new SpriteBitmapStream(sprite).GetFullBuffer();
                    //using (MemoryStream stream1 = new MemoryStream(buffer1, true))
                    //{
                    //    BusIconStreams[i * NUM_ICON_TYPES + j] = stream1.AsRandomAccessStream();
                    //}
                    //var bitmap = await WriteableBitmapExtensions.FromContent(null, new Uri($"ms-appx:///Assets/Icons/{postfix}.png"));
                    WriteableBitmap bitmap;
                    if (j >= 1 && j <= 8)
                    {
                        bitmap = await MapIconImageGenerator.GenerateBusMapIcon((StopDirection)j);
                    }
                    else
                    {
                        bitmap = await MapIconImageGenerator.GenerateBusMapIcon();
                    }
                    double size = (i + 1) * 20 * dpiMultiplier;
                    bitmap = bitmap.Resize((int)size, (int)size, WriteableBitmapExtensions.Interpolation.Bilinear);

                    InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream();

                    await bitmap.ToStream(stream, BitmapEncoder.PngEncoderId);

                    BusIconStreams[i * NUM_ICON_TYPES + j] = stream;
                    byte[] buffer = new byte[stream.Size];
                    stream.AsStreamForRead().Read(buffer, 0, buffer.Length);
                    for (int k = 0; k < buffer.Length; k++)
                    {
                        //if (buffer[k] != buffer1[k])
                        //{
                        //    //System.Diagnostics.Debug.WriteLine($"{buffer[k]} vs {buffer1[k]}");
                        //}
                    }
                }
            }
        }
예제 #19
0
        private async void AnalyzeButton_Click(object sender, RoutedEventArgs e)
        {
            if (processingImage)
            {
                // Ignore button presses while processing the image
                return;
            }

            if (inCaptureState)
            {
                processingImage = true;
                inCaptureState  = false;

                // Make the 'Processing...' label visible
                canvasControl.Visibility = Visibility.Visible;
                AnalyzeButton.Content    = "...";

                canvasControl.Invalidate();

                var originalPhoto  = new InMemoryRandomAccessStream();
                var reencodedPhoto = new InMemoryRandomAccessStream();
                await mediaCapture.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), originalPhoto);

                await originalPhoto.FlushAsync();

                originalPhoto.Seek(0);

                captureElement.Visibility = Visibility.Collapsed;

                // Store the captured photo as a Win2D type for later use
                photoCanvasBitmap = await CanvasBitmap.LoadAsync(canvasControl, originalPhoto);

                // Send the photo to Project Oxford to detect the faces
                lastCapturedFaces = await faceServiceClient.DetectAsync(originalPhoto.AsStreamForRead(), true, true, true, false);

                // Force the canvasControl to be redrawn now that the photo is available
                canvasControl.Invalidate();

                processingImage       = false;
                AnalyzeButton.Content = "Restart";
            }
            else
            {
                canvasControl.Visibility  = Visibility.Collapsed;
                captureElement.Visibility = Visibility.Visible;
                AnalyzeButton.Content     = "Capture Photo";

                photoCanvasBitmap = null;
                canvasControl.Invalidate();

                inCaptureState = true;
            }
        }
예제 #20
0
        // Convert frame from mediacapture into byte array
        public async Task <byte[]> CaptureImageToByteArray()
        {
            var stream = new InMemoryRandomAccessStream();
            await _video.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), stream);

            stream.Seek(0);
            var readStream = stream.AsStreamForRead();
            var byteArray  = new byte[readStream.Length];
            await readStream.ReadAsync(byteArray, 0, byteArray.Length);

            return(byteArray);
        }
예제 #21
0
        public static async Task <string> CreateColorError(this CanvasBitmap bitmap, string message)
        {
            using var ms = new InMemoryRandomAccessStream();
            await bitmap.SaveAsync(ms, CanvasBitmapFileFormat.Png);

            using var ms2 = new MemoryStream();
            await ms.AsStreamForRead().CopyToAsync(ms2);

            var imageAsString = Convert.ToBase64String(ms2.ToArray());

            return($"{message}. This is what it looked like:<img>{imageAsString}</img>");
        }
예제 #22
0
        private async Task <Stream> ResizeImage(Stream imageData, int desiredWidth, int desiredHeight, CancellationToken cancellationToken)
        {
            IRandomAccessStream imageStream = imageData.AsRandomAccessStream();
            BitmapDecoder       decoder     = await BitmapDecoder.CreateAsync(imageStream);

            cancellationToken.ThrowIfCancellationRequested();

            if (decoder.PixelWidth > desiredWidth || decoder.PixelHeight > desiredHeight)
            {
                using (imageData)
                    using (imageStream)
                    {
                        InMemoryRandomAccessStream resizedStream = new InMemoryRandomAccessStream();

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

                        cancellationToken.ThrowIfCancellationRequested();

                        double widthRatio  = (double)desiredWidth / decoder.PixelWidth;
                        double heightRatio = (double)desiredHeight / decoder.PixelHeight;

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

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

                        if (desiredHeight == 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();

                        cancellationToken.ThrowIfCancellationRequested();

                        resizedStream.Seek(0);
                        return(resizedStream.AsStreamForRead());
                    }
            }

            return(imageData);
        }
예제 #23
0
        public static async Task <Image <TColor, TDepth> > FromMediaCapture(MediaCapture _mediaCapture)
        {
            using (InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream())
            {
                await _mediaCapture.CapturePhotoToStreamAsync(Windows.Media.MediaProperties.ImageEncodingProperties.CreateJpeg(), stream);

                stream.Seek(0);
                byte[] data = new byte[stream.Size];
                await stream.AsStreamForRead().ReadAsync(data, 0, data.Length);

                return(Image <TColor, TDepth> .FromRawImageData(data));
            }
        }
예제 #24
0
파일: AIBot.cs 프로젝트: zergmk2/Roro
        private static async Task <Bitmap> GetBitmapFromSoftwareBitmap(SoftwareBitmap softwareBitmap)
        {
            using (IRandomAccessStream ras = new InMemoryRandomAccessStream())
            {
                BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.BmpEncoderId, ras);

                encoder.SetSoftwareBitmap(SoftwareBitmap.Convert(softwareBitmap, BitmapPixelFormat.Bgra8));
                await encoder.FlushAsync();

                Bitmap bmp = new Bitmap(ras.AsStreamForRead());
                return(bmp.Clone(new Rectangle(Point.Empty, bmp.Size), PixelFormat.Format32bppArgb));
            }
        }
예제 #25
0
        public static async Task ToMat(this MediaCapture mediaCapture, Mat result)
        {
            using (InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream())
            {
                await mediaCapture.CapturePhotoToStreamAsync(Windows.Media.MediaProperties.ImageEncodingProperties.CreateJpeg(), stream);

                stream.Seek(0);
                byte[] data = new byte[stream.Size];
                await stream.AsStreamForRead().ReadAsync(data, 0, data.Length);

                CvInvoke.Imdecode(data, ImreadModes.Color, result);
            }
        }
예제 #26
0
 public static async Task<Mat> FromMediaCapture(MediaCapture _mediaCapture)
 {
    using (InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream())
    {
       await _mediaCapture.CapturePhotoToStreamAsync(Windows.Media.MediaProperties.ImageEncodingProperties.CreateJpeg(), stream);
       stream.Seek(0);
       byte[] data = new byte[stream.Size];
       await stream.AsStreamForRead().ReadAsync(data, 0, data.Length);
       Mat result = new Mat();
       CvInvoke.Imdecode(data, LoadImageType.Color, result);
       return result;
    }
 }
예제 #27
0
    private int PreparePacket()
    {
        Stream stream;
        int    offset = CEEnum.BMP == config.Encoder ? 54 : 0;
        int    size   = (int)inMemStream.Size - offset;

        stream = inMemStream.AsStreamForRead();
        stream.Seek(offset, SeekOrigin.Begin);

        int read_size = stream.Read(buffer, OVERHEAD_SIZE, size); //removing BMP header

        if (size != read_size)
        {
            throw new Exception(string.Format("Reading error: read {0} on {1}.", read_size, size));
        }

        Array.Copy(BitConverter.GetBytes(photoIndex), 0, buffer, 4, 4);
        Array.Copy(BitConverter.GetBytes(size), 0, buffer, 8, 4);

        //Debug.Log(string.Format("\nSending {0} bytes, index {1}, STX {2}.\n", size, BitConverter.ToInt32(buffer, 4), BitConverter.ToInt32(buffer, 0)));
        return(size);
    }
    /// <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());
    }
        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();
            }
        }
        /// <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);
        }