示例#1
0
        private async void captureBtn_Click(object sender, RoutedEventArgs e)
        {
            ////Sample Code 3
            captureStart = true;
            MediaCapture _mediaCapture;

            while (captureStart)
            {
                _mediaCapture = new MediaCapture();
                bool _isPreviewing;
                await _mediaCapture.InitializeAsync();

                //_mediaCapture.Failed += MediaCapture_Failed;
                var myPictures = await Windows.Storage.StorageLibrary.GetLibraryAsync(Windows.Storage.KnownLibraryId.Pictures);

                StorageFile file = await myPictures.SaveFolder.CreateFileAsync("photo.jpg", CreationCollisionOption.ReplaceExisting);

                using (var captureStream = new InMemoryRandomAccessStream())
                {
                    await _mediaCapture.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), captureStream);

                    using (var fileStream = await file.OpenAsync(FileAccessMode.ReadWrite))
                    {
                        var decoder = await BitmapDecoder.CreateAsync(captureStream);

                        var encoder = await BitmapEncoder.CreateForTranscodingAsync(fileStream, decoder);

                        var properties = new BitmapPropertySet {
                            { "System.Photo.Orientation", new BitmapTypedValue(PhotoOrientation.Normal, PropertyType.UInt16) }
                        };
                        await encoder.BitmapProperties.SetPropertiesAsync(properties);

                        await encoder.FlushAsync();
                    }
                }
            }
        }
        private async void OnDeferredImageRequestedHandler(DataProviderRequest request)
        {
            // In this delegate we provide updated Bitmap data using delayed rendering.

            if (_imageFile != null)
            {
                // If the delegate is calling any asynchronous operations it needs to acquire
                // the deferral first. This lets the system know that you are performing some
                // operations that might take a little longer and that the call to SetData
                // could happen after the delegate returns. Once you acquired the deferral object
                // you must call Complete on it after your final call to SetData.
                DataProviderDeferral       deferral       = request.GetDeferral();
                InMemoryRandomAccessStream inMemoryStream = new InMemoryRandomAccessStream();

                // Make sure to always call Complete when finished with the deferral.
                try
                {
                    // Decode the image and re-encode it at 50% width and height.
                    IRandomAccessStream imageStream = await _imageFile.OpenAsync(FileAccessMode.Read);

                    BitmapDecoder imageDecoder = await BitmapDecoder.CreateAsync(imageStream);

                    BitmapEncoder imageEncoder = await BitmapEncoder.CreateForTranscodingAsync(inMemoryStream, imageDecoder);

                    imageEncoder.BitmapTransform.ScaledWidth  = (uint)(imageDecoder.OrientedPixelWidth * 0.5);
                    imageEncoder.BitmapTransform.ScaledHeight = (uint)(imageDecoder.OrientedPixelHeight * 0.5);
                    await imageEncoder.FlushAsync();

                    request.SetData(RandomAccessStreamReference.CreateFromStream(inMemoryStream));
                }
                finally
                {
                    deferral.Complete();
                }
            }
        }
        public async static Task <IRandomAccessStream> ScaleImage2Fit(IRandomAccessStream source, int maxWidth)
        {
            InMemoryRandomAccessStream inMemoryStream = new InMemoryRandomAccessStream();

            // Decode the image
            BitmapDecoder imageDecoder = await BitmapDecoder.CreateAsync(source);

            // Re-encode the image at maxWidth
            if (imageDecoder.OrientedPixelWidth > maxWidth)
            {
                double        rat          = maxWidth / imageDecoder.OrientedPixelWidth;
                BitmapEncoder imageEncoder = await BitmapEncoder.CreateForTranscodingAsync(inMemoryStream, imageDecoder);

                imageEncoder.BitmapTransform.ScaledWidth  = (uint)(imageDecoder.OrientedPixelWidth * rat);
                imageEncoder.BitmapTransform.ScaledHeight = (uint)(imageDecoder.OrientedPixelHeight * rat);
                await imageEncoder.FlushAsync();

                return(inMemoryStream);
            }
            else
            {
                return(source);
            }
        }
        public async void CapturePhoto_Click(object sender, RoutedEventArgs e)
        {
            //Getting access to Pictures folder
            var myPictures = await StorageLibrary.GetLibraryAsync(KnownLibraryId.Pictures);

            //Createing the file that will be saved
            StorageFile file = await myPictures.SaveFolder.CreateFileAsync("night-photo.jpg", CreationCollisionOption.GenerateUniqueName);

            //Capture a photo to the stream
            using (var captureStream = new InMemoryRandomAccessStream())
            {
                //Common encoding with JPEG format
                await _mediaCapture.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), captureStream);

                using (var fileStream = await file.OpenAsync(FileAccessMode.ReadWrite))
                {
                    //Decode the image from the memory stream
                    var decoder = await BitmapDecoder.CreateAsync(captureStream);

                    //Encode the image to file
                    var encoder = await BitmapEncoder.CreateForTranscodingAsync(fileStream, decoder);

                    //Getting the current orientation of the device
                    var photoOrientation = CameraRotationHelper.ConvertSimpleOrientationToPhotoOrientation(_rotationHelper.GetCameraCaptureOrientation());

                    //Including metadata about the photo in the image file
                    var properties = new BitmapPropertySet
                    {
                        { "System.Photo.Orientation", new BitmapTypedValue(photoOrientation, PropertyType.UInt16) }
                    };
                    await encoder.BitmapProperties.SetPropertiesAsync(properties);

                    await encoder.FlushAsync();
                }
            }
        }
示例#5
0
        //public static async Task<bool> GenerateImageAsync(InMemoryRandomAccessStream ms, string newImageName)
        //{
        //    using (var a = ms.AsStream())
        //    {
        //        byte[] b = new byte[a.Length];
        //        await a.ReadAsync(b, 0, (int)a.Length);
        //        StorageFile sampleFile = await _originalFolder.CreateFileAsync(newImageName);
        //        await FileIO.WriteBytesAsync(sampleFile, b);
        //    }

        //    return true;
        //}

        //public async Task<bool> GenerateResizedImageAsyncOld(int longWidth, double srcWidth, double srcHeight, InMemoryRandomAccessStream srcMemoryStream, string newImageName, location subFolder, int longHeight = 0)
        //{
        //    if (_localFolder == null) InitFolders();

        //    try
        //    {
        //        int width = 0, height = 0;
        //        double factor = srcWidth / srcHeight;
        //        if (factor < 1)
        //        {
        //            height = longWidth;
        //            width = (int)(longWidth * factor);
        //        }
        //        else
        //        {
        //            width = longWidth;
        //            height = (int)(longWidth / factor);
        //        }

        //        if (longHeight > 0)
        //        {
        //            width = longWidth;
        //            height = longHeight;
        //        }

        //        WriteableBitmap wb = await BitmapFactory.New((int)srcWidth, (int)srcHeight).FromStream(srcMemoryStream);

        //        //WRITEABLE BITMAP IS THROWING AN ERROR

        //        var wbthumbnail = wb.Resize(width, height, Windows.UI.Xaml.Media.Imaging.WriteableBitmapExtensions.Interpolation.Bilinear);

        //        switch (subFolder)
        //        {
        //            case location.MediumFolder:
        //                StorageFile sampleFile1 = await _mediumFolder.CreateFileAsync(newImageName, CreationCollisionOption.ReplaceExisting);
        //                await wbthumbnail.SaveToFile(sampleFile1, BitmapEncoder.PngEncoderId);
        //                break;
        //            case location.ThumbFolder:
        //                StorageFile sampleFile2 = await _thumbFolder.CreateFileAsync(newImageName, CreationCollisionOption.ReplaceExisting);
        //                await wbthumbnail.SaveToFile(sampleFile2, BitmapEncoder.PngEncoderId);
        //                break;
        //            case location.TileFolder:
        //                StorageFile sampleFile3 = await _tileFolder.CreateFileAsync(newImageName, CreationCollisionOption.ReplaceExisting);
        //                await wbthumbnail.SaveToFile(sampleFile3, BitmapEncoder.PngEncoderId);
        //                break;
        //        }

        //        return true;
        //    }
        //    catch (Exception ex)
        //    {
        //        return false;
        //    }


        //}

        public async Task <bool> GenerateResizedImageAsync(int longWidth, double srcWidth, double srcHeight, InMemoryRandomAccessStream srcMemoryStream, string newImageName, location subFolder, int longHeight = 0)
        {
            if (_localFolder == null)
            {
                InitFolders();
            }
            if (srcMemoryStream.Size == 0)
            {
                return(false);
            }

            try
            {
                int    width = 0, height = 0;
                double factor = srcWidth / srcHeight;
                if (factor < 1)
                {
                    height = longWidth;
                    width  = (int)(longWidth * factor);
                }
                else
                {
                    width  = longWidth;
                    height = (int)(longWidth / factor);
                }

                if (longHeight > 0)
                {
                    width  = longWidth;
                    height = longHeight;
                }



                if (subFolder == location.MediumFolder)
                {
                    WriteableBitmap wb = await BitmapFactory.New((int)srcWidth, (int)srcHeight).FromStream(srcMemoryStream);

                    var         wbthumbnail = wb.Resize(width, height, Windows.UI.Xaml.Media.Imaging.WriteableBitmapExtensions.Interpolation.Bilinear);
                    StorageFile sampleFile1 = await _mediumFolder.CreateFileAsync(newImageName, CreationCollisionOption.ReplaceExisting);

                    await wbthumbnail.SaveToFile(sampleFile1, BitmapEncoder.PngEncoderId);
                }
                else if (subFolder == location.ThumbFolder)
                {
                    WriteableBitmap wb = await BitmapFactory.New((int)srcWidth, (int)srcHeight).FromStream(srcMemoryStream);

                    var         wbthumbnail = wb.Resize(width, height, Windows.UI.Xaml.Media.Imaging.WriteableBitmapExtensions.Interpolation.Bilinear);
                    StorageFile sampleFile2 = await _thumbFolder.CreateFileAsync(newImageName, CreationCollisionOption.ReplaceExisting);

                    await wbthumbnail.SaveToFile(sampleFile2, BitmapEncoder.PngEncoderId);
                }
                else if (subFolder == location.TileFolder)
                {
                    //https://social.msdn.microsoft.com/Forums/en-US/490b9c01-db4b-434f-8aff-d5c495e67e55/how-to-crop-an-image-using-bitmaptransform?forum=winappswithcsharp

                    BitmapDecoder decoder = await BitmapDecoder.CreateAsync(srcMemoryStream);

                    using (InMemoryRandomAccessStream ras = new InMemoryRandomAccessStream()) {
                        BitmapEncoder enc = await BitmapEncoder.CreateForTranscodingAsync(ras, decoder);

                        var h = longHeight / srcHeight;
                        var w = longWidth / srcWidth;
                        var r = Math.Max(h, w);

                        enc.BitmapTransform.ScaledWidth  = (uint)(srcWidth * r);
                        enc.BitmapTransform.ScaledHeight = (uint)(srcHeight * r);

                        BitmapBounds bounds = new BitmapBounds();
                        bounds.Width  = (uint)longWidth;
                        bounds.Height = (uint)longHeight;
                        bounds.X      = 0;
                        bounds.Y      = 0;
                        enc.BitmapTransform.Bounds = bounds;

                        await enc.FlushAsync();

                        WriteableBitmap wb = await BitmapFactory.New(longWidth, longHeight).FromStream(ras);

                        StorageFile sampleFile3 = await _tileFolder.CreateFileAsync(newImageName, CreationCollisionOption.ReplaceExisting);

                        await wb.SaveToFile(sampleFile3, BitmapEncoder.PngEncoderId);
                    }
                }



                return(true);
            }
            catch //(Exception ex)
            {
                return(false);
            }
        }
示例#6
0
        //Download and resize image
        public async Task <Stream> DownloadResizeImage(Uri downloadUri, uint maxWidth, uint maxHeight)
        {
            try
            {
                //Check local cache
                Stream imageStream = null;
                string cacheFile   = Path.Combine("Cache", AVFunctions.StringToHash(downloadUri.ToString()));
                if (AVFiles.File_Exists(cacheFile, true))
                {
                    //Load cached image
                    imageStream = AVFiles.File_LoadStream(cacheFile, true);

                    Debug.WriteLine("Windows cache image length: " + imageStream.Length);
                }
                else
                {
                    //Download image
                    imageStream = await AVDownloader.DownloadStreamAsync(8000, null, null, downloadUri);

                    //Save cache image
                    AVFiles.File_SaveStream(cacheFile, imageStream, true, true);

                    Debug.WriteLine("Windows download image length: " + imageStream.Length);
                }

                //Decode image
                if (imageStream.CanSeek)
                {
                    imageStream.Position = 0;
                }
                BitmapDecoder bitmapDecoder = await BitmapDecoder.CreateAsync(imageStream.AsRandomAccessStream());

                //Calculate size
                uint  resizeWidth    = 0;
                uint  resizeHeight   = 0;
                uint  originalWidth  = bitmapDecoder.PixelWidth;
                uint  originalHeight = bitmapDecoder.PixelHeight;
                float originalAspect = (float)originalWidth / (float)originalHeight;
                if (originalWidth > maxWidth)
                {
                    resizeWidth  = maxWidth;
                    resizeHeight = (uint)(maxWidth / originalAspect);
                }
                else if (originalHeight > maxHeight)
                {
                    resizeWidth  = (uint)(maxHeight / originalAspect);
                    resizeHeight = maxHeight;
                }
                else
                {
                    resizeWidth  = originalWidth;
                    resizeHeight = originalHeight;
                }
                //Debug.WriteLine("Resizing image to: " + resizeWidth + "w/" + resizeHeight + "h/" + originalAspect + "a");

                //Resize image
                InMemoryRandomAccessStream resizeStream = new InMemoryRandomAccessStream();
                BitmapEncoder bitmapEncoder             = await BitmapEncoder.CreateForTranscodingAsync(resizeStream, bitmapDecoder);

                bitmapEncoder.BitmapTransform.ScaledWidth  = resizeWidth;
                bitmapEncoder.BitmapTransform.ScaledHeight = resizeHeight;
                await bitmapEncoder.FlushAsync();

                //Dispose resources
                imageStream.Dispose();

                //Convert stream
                return(resizeStream.AsStream());
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Failed to download and resize image: " + ex.Message);
                return(null);
            }
        }
示例#7
0
        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            //拍照
            var myPictures = await Windows.Storage.StorageLibrary.GetLibraryAsync(Windows.Storage.KnownLibraryId.Pictures);

            StorageFile file = await myPictures.SaveFolder.CreateFileAsync("photo.jpg", CreationCollisionOption.GenerateUniqueName);

            using (var captureStream = new InMemoryRandomAccessStream())
            {
                await mediaCapture.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), captureStream);

                using (var fileStream = await file.OpenAsync(FileAccessMode.ReadWrite))
                {
                    var decoder = await BitmapDecoder.CreateAsync(captureStream);

                    var encoder = await BitmapEncoder.CreateForTranscodingAsync(fileStream, decoder);

                    var properties = new BitmapPropertySet {
                        { "System.Photo.Orientation", new BitmapTypedValue(PhotoOrientation.Normal, PropertyType.UInt16) }
                    };
                    await encoder.BitmapProperties.SetPropertiesAsync(properties);

                    await encoder.FlushAsync();
                }
            }

            //选择照片
            FileOpenPicker openPicker = new FileOpenPicker();

            openPicker.ViewMode = PickerViewMode.Thumbnail;
            openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
            openPicker.FileTypeFilter.Add(".jpg");
            openPicker.FileTypeFilter.Add(".PNG");
            StorageFile image = await openPicker.PickSingleFileAsync();


            BitmapImage bi = new BitmapImage();

            if (image != null)
            {
                IRandomAccessStream ir = await image.OpenAsync(FileAccessMode.Read);

                await bi.SetSourceAsync(ir);

                imageControl.Source = bi;
            }


            //请求API
            var OCRresult = await OCRAPI.OCRRequests(image);

            StringBuilder sb = new StringBuilder();

            //遍历API结果
            foreach (var region in OCRresult.regions)
            {
                foreach (var line in region.lines)
                {
                    foreach (var word in line.words)
                    {
                        sb.Append(word.text);
                    }
                }
            }

            resultText.Text = sb.ToString();
        }
示例#8
0
        public async Task SaveImageAsync(string path, PortableImage image, bool deleteExisting, ImageFormat format)
        {
            var withoutExtension = Path.GetFileNameWithoutExtension(path);
            var thumbnailPath    = string.Format("{0}{1}", withoutExtension, StorageConstants.ImageThumbnailExtension);

            if (deleteExisting)
            {
                await DeleteFileAsync(path);
                await DeleteFileAsync(thumbnailPath);
            }

            Stream stream = null;

            try
            {
                stream = await OpenFileAsync(path, StorageFileMode.CreateNew, StorageFileAccess.Write);

                switch (format)
                {
                case ImageFormat.Png:
                    if (image.EncodedData != null)
                    {
                        await image.EncodedData.CopyToAsync(stream);
                    }
                    else
                    {
                        throw new NotImplementedException("This code does not work properly");

                        BitmapDecoder decoder = await BitmapDecoder.CreateAsync(((Stream)image.EncodedData).AsRandomAccessStream());

                        var           memoryStream = new InMemoryRandomAccessStream();
                        BitmapEncoder encoder      = await BitmapEncoder.CreateForTranscodingAsync(memoryStream, decoder);

                        try
                        {
                            await encoder.FlushAsync();
                        }
                        catch (Exception exc)
                        {
                            var message = "Error on writing the image: ";

                            if (exc.Message != null)
                            {
                                message += exc.Message;
                            }

                            throw new Exception(message);
                        }

                        //await ((WriteableBitmap)image.ImageSource).ToStreamAsJpeg(stream.AsRandomAccessStream());
                        //await PNGWriter.WritePNG((WriteableBitmap)image.ImageSource, stream, 95);
                    }

                    //throw new NotImplementedException();
                    //
                    break;

                case ImageFormat.Jpg:
                    //await ((WriteableBitmap) image.ImageSource).ToStreamAsJpeg(stream.AsRandomAccessStream());
                    //((WriteableBitmap)image.ImageSource).SaveJpeg(stream, image.Width, image.Height, 0, 95);
                    throw new NotImplementedException();

                    break;

                default:
                    throw new ArgumentOutOfRangeException("format");
                }
            }
            catch (Exception exc)
            {
                throw;
            }
            finally
            {
                if (stream != null)
                {
                    stream.Flush();
                    stream.Dispose();
                }
            }
        }