Beispiel #1
0
        public static async Task <byte[]> TranscodeImageFile(byte[] data)
        {
            using (IRandomAccessStream stream = data.AsBuffer().AsStream().AsRandomAccessStream())
            {
                BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream);

                var           memStream = new Windows.Storage.Streams.InMemoryRandomAccessStream();
                var           outstream = new InMemoryRandomAccessStream();
                BitmapEncoder encoder   = await BitmapEncoder.CreateForTranscodingAsync(memStream, decoder);

                encoder.BitmapTransform.ScaledWidth  = 320;
                encoder.BitmapTransform.ScaledHeight = 240;

                await encoder.FlushAsync();

                memStream.Seek(0);
                await RandomAccessStream.CopyAsync(memStream, outstream);

                memStream.Dispose();

                var outbuff = new byte[outstream.Size];
                await outstream.WriteAsync(outbuff.AsBuffer());

                return(outbuff);
            }
        }
        private async Task WriteImage()
        {
            if (currentImageIndex == -1)
            {
                return;
            }
            try
            {
                await CreateFolder();

                StorageFile outputFile = await projectFolder.CreateFileAsync(filesNames.ElementAt(currentImageIndex), CreationCollisionOption.ReplaceExisting);

                var stream = (await outputFile.OpenStreamForWriteAsync()).AsRandomAccessStream();

                Guid encoderId;
                if (filesNames.ElementAt(currentImageIndex).Contains(".jpg"))
                {
                    encoderId = Windows.Graphics.Imaging.BitmapEncoder.JpegEncoderId;
                }

                var inputStream = await files.ElementAt(currentImageIndex).OpenStreamForReadAsync();

                BitmapDecoder decoder = await BitmapDecoder.CreateAsync(inputStream.AsRandomAccessStream());

                var           inputProperties = decoder.BitmapProperties;
                var           memStream       = new Windows.Storage.Streams.InMemoryRandomAccessStream();
                BitmapEncoder encoder2        = await BitmapEncoder.CreateForTranscodingAsync(memStream, decoder);

                WriteImageMetadata(encoder2, inputProperties);
                await encoder2.FlushAsync();

                memStream.Seek(0);
                stream.Seek(0);
                stream.Size = 0;
                await RandomAccessStream.CopyAsync(memStream, stream);

                memStream.Dispose();

                stream.Dispose();
                inputStream.Dispose();
                if (latitude.Text != null)
                {
                    await GeotagHelper.SetGeotagAsync(outputFile, myLocation);
                }
            }
            catch (Exception err)
            {
                switch (err.HResult)
                {
                case unchecked ((int)0x88982F41):    // WINCODEC_ERR_PROPERTYNOTSUPPORTED
                                                     // The file format does not support this property.
                    break;

                default:
                    break;
                }
            }
        }
        public void LoadFromResource(string assemblyName, MvxResourcePath resourceName)
        {
            //Package.Current.InstalledLocation.GetFileAsync()
            var path = resourceName.GetResourcePath(".", true);
            //   bitmap = new BitmapImage(new Uri("ms-appx:///" + assemblyName + "/" + path, UriKind.RelativeOrAbsolute));
            var strm = Assembly.Load(new AssemblyName(assemblyName)).GetManifestResourceStream(path);
            byte[] bts = new byte[strm.Length];
            strm.Read(bts, 0, (int)strm.Length);
            InMemoryRandomAccessStream ras = new InMemoryRandomAccessStream();

            ras.GetOutputStreamAt(0).WriteAsync(bts.AsBuffer());
            //strm.CopyToAsync(ras.AsStreamForWrite()).Wait();

            ras.Seek(0);
            bitmap = new BitmapImage();
            bitmap.SetSource(ras);
            ras.Dispose();
            strm.Dispose();
        }
Beispiel #4
0
        // </SnippetCreateSoftwareBitmapFromSurface>

        // <SnippetTranscodeImageFile>
        private async void TranscodeImageFile(StorageFile imageFile)
        {
            using (IRandomAccessStream fileStream = await imageFile.OpenAsync(FileAccessMode.ReadWrite))
            {
                BitmapDecoder decoder = await BitmapDecoder.CreateAsync(fileStream);

                var           memStream = new Windows.Storage.Streams.InMemoryRandomAccessStream();
                BitmapEncoder encoder   = await BitmapEncoder.CreateForTranscodingAsync(memStream, decoder);

                encoder.BitmapTransform.ScaledWidth  = 320;
                encoder.BitmapTransform.ScaledHeight = 240;

                await encoder.FlushAsync();

                memStream.Seek(0);
                fileStream.Seek(0);
                fileStream.Size = 0;
                await RandomAccessStream.CopyAsync(memStream, fileStream);

                memStream.Dispose();
            }
        }
        private async Task<Image> DataToImage(Tile tile)
        {
            BitmapImage bitmapImage = new BitmapImage();
            if (tile.IsSuccessd)
            {
                InMemoryRandomAccessStream randomAccessStream = new InMemoryRandomAccessStream();
                DataWriter writer = new DataWriter(randomAccessStream.GetOutputStreamAt(0));
                writer.WriteBytes(tile.MapImage.Data);
                await writer.StoreAsync();

                bitmapImage.SetSource(randomAccessStream);
                writer.Dispose();
                randomAccessStream.Dispose();
            }
            Image image = new Image()
            {
                Opacity = 1.0,
                Tag = tile,
                IsHitTestVisible = false,
                Name = tile.TileKey,
                Stretch = Stretch.Fill,
                Source = bitmapImage
            };

            double resolution = tile.Resolution;
            LayerContainer.SetBounds(image, GetTilesBounds(tile.Column, tile.Row, tile.Resolution));//计算该image的范围
            return image;
        }
 private async void LoadImageFromUriAsync(Uri url)
 {
     HttpClient httpClient = new HttpClient();
     HttpResponseMessage result = httpClient.GetAsync(url).Result;
     byte[] array = await result.Content.ReadAsByteArrayAsync();
     InMemoryRandomAccessStream inMemoryRandomAccessStream = new InMemoryRandomAccessStream();
     DataWriter dataWriter = new DataWriter(inMemoryRandomAccessStream.GetOutputStreamAt(0uL));
     dataWriter.WriteBytes(array);
     await dataWriter.StoreAsync();
     BitmapImage bitmapImage = new BitmapImage();
     bitmapImage.SetSource(inMemoryRandomAccessStream);
     this._image = bitmapImage;
     httpClient.Dispose();
     result.Dispose();
     array = null;
     inMemoryRandomAccessStream.Dispose();
     dataWriter.Dispose();
     bitmapImage = null;
 }
Beispiel #7
0
 public void Dispose()
 {
     internalStream.Dispose();
     internalStream = null;
 }
Beispiel #8
0
        /// <summary>
        /// Perform image capture from mediaCapture object
        /// </summary>
        /// <param name="cancelToken">
        /// The cancel Token.
        /// </param>
        /// <returns>
        /// Decoded barcode string.
        /// </returns>
        private async Task<Result> GetCameraImage(CancellationToken cancelToken)
        {
            if (cancelToken.IsCancellationRequested)
            {
                throw new OperationCanceledException(cancelToken);
            }

            imageStream = new InMemoryRandomAccessStream();

            await capture.CapturePhotoToStreamAsync(encodingProps, imageStream);
            await imageStream.FlushAsync();

            var decoder = await BitmapDecoder.CreateAsync(imageStream);

            byte[] pixels = (await decoder.GetPixelDataAsync(BitmapPixelFormat.Rgba8,
                BitmapAlphaMode.Ignore,
                new BitmapTransform(),
                ExifOrientationMode.IgnoreExifOrientation,
                ColorManagementMode.DoNotColorManage)).DetachPixelData();

            const BitmapFormat format = BitmapFormat.RGB32;

            imageStream.Dispose();

            var result =
                await
                    Task.Run(
                        () => barcodeReader.Decode(pixels, (int)decoder.PixelWidth, (int)decoder.PixelHeight, format),
                        cancelToken);

            return result;
        }
Beispiel #9
0
        private async void wvMain_SendMessage(object sender, System.EventArgs e)
        {
            //try {

                var ea = (ContentViewEventArgs)e;

                if (ea.Type == "ContentLoading")
                {
                    if (wvMain.Uri.Contains("about:blank")) return;
                    //prLoading.IsActive = true;
                    //ShowHideUriArea(0);
                    //sbShowLoading.Begin();
                }
                else if (ea.Type == "NavigationFailed")
                {
                    X.Services.Extensions.ExtensionsService.Instance.SendMessage(ea, ExtensionType.WVNavigationFailed);
                }
                else if (ea.Type == "DOMContentLoaded")
                {
                    X.Services.Extensions.ExtensionsService.Instance.SendMessage(ea.Uri, ExtensionType.WVDOMContentLoaded);
                }
                else if (ea.Type == "NavigationCompleted")
                {
                    X.Services.Extensions.ExtensionsService.Instance.SendMessage(ea.Uri, ExtensionType.WVNavigationCompleted);
                }
                else if (ea.Type == "NavigationStarting")
                {
                    try
                    {
                        BrowserVM vm = this.DataContext as BrowserVM;
                        if (vm.SelectedTab != null) vm.SelectedTab.Uri = ea.Uri.OriginalString;
                        X.Services.Extensions.ExtensionsService.Instance.SendMessage(ea.Uri, ExtensionType.WVNavigationStarting);
                    }
                    catch
                    {
                        X.Services.Extensions.ExtensionsService.Instance.SendMessage(ea.Uri, ExtensionType.WVNavigationFailed);
                    }
                }
                else if (ea.Type == "NewWindowRequested")
                {
                    X.Services.Extensions.ExtensionsService.Instance.SendMessage(ea.Uri, ExtensionType.WVNewWindowRequest);
                    //args.Handled = true;

                }
                else if (ea.Type == "LongRunningScriptDetected")
                {
                    X.Services.Extensions.ExtensionsService.Instance.SendMessage(null, ExtensionType.WVLongRunningScriptDetected);
                }
                else if (ea.Type == "ScriptNotify")
                {
                    X.Services.Extensions.ExtensionsService.Instance.SendMessage(ea.CallingUri, ExtensionType.WVScriptNotify);
                }
                else if (ea.Type == "FoundFavicon")
                {
                    BrowserVM vm = this.DataContext as BrowserVM;

                    vm.SelectedTab.FaviconUri = ea.Favicon.Replace(".svg", ".ico");
                    vm.SelectedTab.ExternalRaisePropertyChanged("FaviconUri");
                    //vm.ExposedRaisePropertyChanged("SelectedTab");


                    ////and update local storage
                    //try
                    //{
                    //    //App.DataService.Storage.UpdateFieldByUid(vm.SelectedTab.Uid.ToString(), "WebPageModel", "FaviconUri", ea.Favicon);
                    //    var found = App.DataService.Storage.RetrieveByUid(vm.SelectedTab.Uid.ToString());
                    //    var foundItem = found[0];
                    //    foundItem.FaviconUri = ea.Favicon;
                    //    App.DataService.Storage.Update(foundItem);
                    //}
                    //catch { }



                }
                else if (ea.Type == "LoadTimedout")
                {
                    //sbHideLoading.Begin();
                }
                else if (ea.Type == "LoadCompleted")
                {

                    X.Services.Extensions.ExtensionsService.Instance.SendMessage(ea.Uri, ExtensionType.WVLoadCompleted);

                    BrowserVM vm = this.DataContext as BrowserVM;


                    //todo: work out if this is necessary as this is causing a double postback
                    //if (vm.SelectedTab != null &&  vm.SelectedTab.Uri != e.Uri.AbsoluteUri) vm.UpdateSelectedTabManually(e.Uri);

                    if (vm.SelectedTab == null) return;

                    var uriHash = FlickrNet.UtilityMethods.MD5Hash(vm.SelectedTab.OriginalUri); //   e.Uri);

                    if (!isCapturingImage) {
                        isCapturingImage = true;

                        await Task.Delay(1000);

                        if (vm.SelectedTab != null) {

                            //capture screenshot
                            using (InMemoryRandomAccessStream ms = new InMemoryRandomAccessStream())
                            {
                                //todo :drive this from the x.webview
                                await wvMain.Renderer?.CaptureThumbnail(ms);
                                //await wvMain.CapturePreviewToStreamAsync(ms);

                                //img: Banner 400 width
                                //ms.Seek(0);
                                await X.Services.Image.Service.Instance.GenerateResizedImageAsync(400, wvMain.ActualWidth, wvMain.ActualHeight, ms, uriHash + ".png", X.Services.Image.Service.location.MediumFolder);

                                //img: Thumbnail
                                ms.Seek(0);
                                await X.Services.Image.Service.Instance.GenerateResizedImageAsync(180, wvMain.ActualWidth, wvMain.ActualHeight, ms, uriHash + ".png", X.Services.Image.Service.location.ThumbFolder);

                                //img: Tile
                                ms.Seek(0);
                                await X.Services.Image.Service.Instance.GenerateResizedImageAsync(71, wvMain.ActualWidth, wvMain.ActualHeight, ms, uriHash + ".png", X.Services.Image.Service.location.TileFolder, 71);

                                ms.Seek(0);
                                await X.Services.Image.Service.Instance.GenerateResizedImageAsync(150, wvMain.ActualWidth, wvMain.ActualHeight, ms, uriHash + "-150x150.png", X.Services.Image.Service.location.TileFolder, 150);

                                ms.Seek(0);
                                await X.Services.Image.Service.Instance.GenerateResizedImageAsync(310, wvMain.ActualWidth, wvMain.ActualHeight, ms, uriHash + "-310x150.png", X.Services.Image.Service.location.TileFolder, 150);

                                ms.Seek(0);
                                await X.Services.Image.Service.Instance.GenerateResizedImageAsync(310, wvMain.ActualWidth, wvMain.ActualHeight, ms, uriHash + "-310x310.png", X.Services.Image.Service.location.TileFolder, 310);


                                //update tile
                                //var sxxxxx = Windows.Storage.ApplicationData.Current.LocalFolder;
                                X.Services.Tile.Service.UpdatePrimaryTile("X.Browser",
                                    "ms-appdata:///local/tile/" + uriHash + "-150x150.png",
                                    "ms-appdata:///local/tile/" + uriHash + "-310x150.png",
                                    "ms-appdata:///local/tile/" + uriHash + "-310x310.png",
                                    "ms-appdata:///local/tile/" + uriHash + ".png"
                                    );

                                ms.Dispose();

                            }


                            //update thumb in VM
                            var fullUriHash = string.Concat(X.Services.Image.Service.Instance.MediumLocation, "\\", uriHash, ".png");
                            //if (!vm.SelectedTab.ThumbUri.Equals(fullUriHash)) {
                            vm.SelectedTab.ThumbUri = fullUriHash + "?v=" + Guid.NewGuid().ToString();
                            vm.SelectedTab.ExternalRaisePropertyChanged("ThumbUri");
                            //}

                            vm.SelectedTab.LastRefreshedDate = DateTime.UtcNow;

                        }



                        isCapturingImage = false;
                    }
                    
                }
                else if (ea.Type == "SnapViewer")
                {
                    if (!isCapturingImage) {
                        isCapturingImage = true;

                        var uriHash = FlickrNet.UtilityMethods.MD5Hash(vm.SelectedTab.OriginalUri); //   e.Uri);
                        using (InMemoryRandomAccessStream ms = new InMemoryRandomAccessStream())
                        {
                            await wvMain.Renderer?.CaptureThumbnail(ms);

                            //img: Banner 400 width
                            //ms.Seek(0);
                            await X.Services.Image.Service.Instance.GenerateResizedImageAsync(400, wvMain.ActualWidth, wvMain.ActualHeight, ms, uriHash + ".png", X.Services.Image.Service.location.MediumFolder);

                            //img: Thumbnail
                            ms.Seek(0);
                            await X.Services.Image.Service.Instance.GenerateResizedImageAsync(180, wvMain.ActualWidth, wvMain.ActualHeight, ms, uriHash + ".png", X.Services.Image.Service.location.ThumbFolder);

                            //img: Tile
                            ms.Seek(0);
                            await X.Services.Image.Service.Instance.GenerateResizedImageAsync(71, wvMain.ActualWidth, wvMain.ActualHeight, ms, uriHash + ".png", X.Services.Image.Service.location.TileFolder, 71);

                            ms.Seek(0);
                            await X.Services.Image.Service.Instance.GenerateResizedImageAsync(150, wvMain.ActualWidth, wvMain.ActualHeight, ms, uriHash + "-150x150.png", X.Services.Image.Service.location.TileFolder, 150);

                            ms.Seek(0);
                            await X.Services.Image.Service.Instance.GenerateResizedImageAsync(310, wvMain.ActualWidth, wvMain.ActualHeight, ms, uriHash + "-310x150.png", X.Services.Image.Service.location.TileFolder, 150);

                            ms.Seek(0);
                            await X.Services.Image.Service.Instance.GenerateResizedImageAsync(310, wvMain.ActualWidth, wvMain.ActualHeight, ms, uriHash + "-310x310.png", X.Services.Image.Service.location.TileFolder, 310);


                            //update tile
                            //var sxxxxx = Windows.Storage.ApplicationData.Current.LocalFolder;
                            X.Services.Tile.Service.UpdatePrimaryTile("X.Browser",
                                "ms-appdata:///local/tile/" + uriHash + "-150x150.png",
                                "ms-appdata:///local/tile/" + uriHash + "-310x150.png",
                                "ms-appdata:///local/tile/" + uriHash + "-310x310.png",
                                "ms-appdata:///local/tile/" + uriHash + ".png"
                                );

                            ms.Dispose();
                        }

                        isCapturingImage = false;
                    }
                }
            //}
            //catch (Exception ex){

            //    //todo : handle this BUT need to work out why this happens

            //}


        }
        private async void Run()
        {
            await _HubConnection.Start();

            var cam = new MediaCapture();

            await cam.InitializeAsync(new MediaCaptureInitializationSettings()
            {
                MediaCategory = MediaCategory.Media,
                StreamingCaptureMode = StreamingCaptureMode.Video
            });

            _Sensor.MotionDetected += async (int pinNum) =>
            {
                var stream = new InMemoryRandomAccessStream();
                Stream imageStream = null;
                try
                {
                    await Task.Factory.StartNew(async () =>
                    {
                        _Sensor.IsActive = false;
                        await cam.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), stream);
                        stream.Seek(0);
                        imageStream = stream.AsStream();
                        imageStream.Seek(0, SeekOrigin.Begin);
                        string imageUrl = await NotificationHelper.UploadImageAsync(imageStream);

                        switch (await OxfordHelper.IdentifyAsync(imageUrl))
                        {
                            case AuthenticationResult.IsOwner:
                                // open the door
                                MotorController.PWM(26);
                                break;

                            case AuthenticationResult.Unkown:
                                // send notification to the owner
                                NotificationHelper.NotifyOwnerAsync(imageUrl);
                                break;

                            case AuthenticationResult.None:
                            default:
                                break;
                        }
                        _Sensor.IsActive = true;
                    });
                }
                finally
                {
                    if (stream != null)
                        stream.Dispose();
                    if (imageStream != null)
                        imageStream.Dispose();
                }
            };
        }
        private async Task LoadImageFromHttpResponse(HttpResponseMessage response, BitmapImage bitmap, string cacheKey)
        {
            if (response.IsSuccessStatusCode)
            {
                var stream = new InMemoryRandomAccessStream();

                using (var content = response.Content)
                {
                    await content.WriteToStreamAsync(stream);
                }

                await stream.FlushAsync();
                stream.Seek(0);

                await bitmap.Dispatcher.RunAsync(CoreDispatcherPriority.Low, async () =>
                {
                    try
                    {
                        await bitmap.SetSourceAsync(stream);

                        // cache image asynchronously, after successful decoding
                        var task = Task.Run(async () =>
                        {
                            var buffer = new Windows.Storage.Streams.Buffer((uint)stream.Size);

                            stream.Seek(0);
                            await stream.ReadAsync(buffer, buffer.Capacity, InputStreamOptions.None);
                            stream.Dispose();

                            await Cache.SetAsync(cacheKey, buffer);
                        });
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine("{0}: {1}", response.RequestMessage.RequestUri, ex.Message);
                        stream.Dispose();
                    }
                });
            }
            else
            {
                Debug.WriteLine("{0}: {1}", response.RequestMessage.RequestUri, response.StatusCode);
            }
        }
        /// <summary>
        /// 문자열 이미지 uri를 받아서 이미지를 로컬에 저장하고 BitmapImage로 반환한다.
        /// </summary>
        /// <param name="imageUri"></param>
        /// <returns></returns>
        public async Task<BitmapImage> UriImageSaveLocalAsync(string imageUri, bool retry = true)
        {
            if (string.IsNullOrEmpty(imageUri) == true) return null;

            //폴더 초기화 될때까지 대기
            while (files == null)
            {
                await TaskEx.Delay(500);
            }

            //Stream
            var iuri = new Uri(imageUri, UriKind.Absolute);
            string filename = System.IO.Path.GetFileName(iuri.LocalPath);
            //메모리 내용확인
            var mbi = GetImage(filename);
            if (mbi != null)
            {
                return mbi;
            }

            Stream imageStream = null;      //기본 스트림
            //IRandomAccessStream
            InMemoryRandomAccessStream ras = new InMemoryRandomAccessStream();
            //create bitmap
            BitmapImage bi = new BitmapImage();

            //폴더에 파일 존재 확인
            if (files.Any(p => p.Name == filename))
            {
                var localFile = files.First(p => p.Name == filename);
                bi.UriSource = new Uri(Path.Combine(ApplicationData.Current.TemporaryFolder.Path, localFile.Name));
                AddImage(filename, bi);
                //try
                //{
                //    imageStream = await localFile.OpenStreamForReadAsync();
                //}
                //catch (Exception)
                //{
                //    //파일 열때 에러가 발생하면, 파일이 존재하지 않기 때문일 수 있는..
                //    UpdateFolder();
                //    bi.UriSource = new Uri(imageUri);
                //    if (imageStream != null) imageStream.Dispose();
                //    if (ras != null) ras.Dispose();
                //    return bi;
                //}

                //await imageStream.CopyToAsync(ras.AsStreamForWrite());
                //if (ras.Size > 0)
                //{
                //    ras.Seek(0);
                //    await bi.SetSourceAsync(ras);
                //    //메모리에 저장
                //    AddImage(filename, bi);
                //}
                //else
                //{
                //    //파일 이상인듯
                //    await localFile.DeleteAsync();
                //    UpdateFolder();
                //    //재귀호출
                //    if (retry == false)
                //    {
                //        if (imageStream != null) imageStream.Dispose();
                //        if (ras != null) ras.Dispose();
                //        return await UriImageSaveLocalAsync(imageUri, true);
                //    }
                //    else
                //    {
                //        bi.UriSource = new Uri(imageUri);
                //        if (imageStream != null) imageStream.Dispose();
                //        if (ras != null) ras.Dispose();
                //        return bi;
                //    }
                //}
            }
            else
            {
                using (HttpClient hc = new HttpClient())
                {
                    try
                    {
                        imageStream = await hc.GetStreamAsync(imageUri);
                    }
                    catch (Exception)
                    {
                        //네트워크 상태가 끊어졌을 때
                        bi.UriSource = new Uri(imageUri);
                        if (imageStream != null) imageStream.Dispose();
                        if (ras != null) ras.Dispose();
                        return bi;
                    }
                    //Stream -> IRandomAccessStream
                    await imageStream.CopyToAsync(ras.AsStreamForWrite());
                    if (ras.Size > 0)
                    {
                        try
                        {
                            BitmapDecoder decoder = await BitmapDecoder.CreateAsync(ras);
                            BitmapFrame frame = await decoder.GetFrameAsync(0);
                            //파일로 저장
                            var bitmap = new WriteableBitmap((int)frame.PixelWidth, (int)frame.PixelHeight);
                            ras.Seek(0);
                            await bitmap.SetSourceAsync(ras);
                            var saveImage = await bitmap.SaveToFile(ApplicationData.Current.TemporaryFolder, filename, CreationCollisionOption.OpenIfExists);
                            UpdateFolder();
                            //UriSource로 이미지 넣어주고
                            bi.UriSource = new Uri(Path.Combine(ApplicationData.Current.TemporaryFolder.Path, saveImage.Name));

                            //이미지로 변환
                            //ras.Seek(0);
                            //await bi.SetSourceAsync(ras);
                            //메모리에 저장
                            AddImage(filename, bi);
                        }
                        catch (Exception)
                        {
                            //이미지가 너무 커서 저장할 수 없을 경우 그냥 이미지 uri를 넣어서 던짐
                            bi.UriSource = new Uri(imageUri);
                            if (imageStream != null) imageStream.Dispose();
                            if (ras != null) ras.Dispose();
                            return bi;
                        }
                    }
                    else
                    {
                        //재귀호출
                        if (retry == false)
                        {
                            if (imageStream != null) imageStream.Dispose();
                            if (ras != null) ras.Dispose();
                            return await UriImageSaveLocalAsync(imageUri, true);
                        }
                        else
                        {
                            bi.UriSource = new Uri(imageUri);
                            if (imageStream != null) imageStream.Dispose();
                            if (ras != null) ras.Dispose();
                            return bi;
                        }
                    }
                }
            }
            if(imageStream != null) imageStream.Dispose();
            if(ras != null) ras.Dispose();
            return bi;
        }
Beispiel #13
0
        private async Task ShowVehicleLocations()
        {
            var vehicleLocations = await searchVm.GetBusLocations();

            while (vehicleCounter > 0)
            {
                SearchMap.MapElements.RemoveAt(SearchMap.MapElements.Count - 1);
                vehicleCounter--;
            }

            var inboundBM = new WriteableBitmap(40, 40);
            await inboundBM.SetSourceAsync(await RandomAccessStreamReference.CreateFromUri(new Uri("ms-appx:///Assets/Inbound.png")).OpenReadAsync());

            var outboundBM = new WriteableBitmap(40, 40);
            await outboundBM.SetSourceAsync(await RandomAccessStreamReference.CreateFromUri(new Uri("ms-appx:///Assets/Outbound.png")).OpenReadAsync());

            foreach (Bus bus in vehicleLocations)
            {
                if (bus.direction.Equals("inbound"))
                {
                    var rotatedImage = inboundBM.RotateFree(bus.busHeading, false);
                    var stream = new InMemoryRandomAccessStream();
                    await rotatedImage.ToStream(stream, BitmapEncoder.PngEncoderId);

                    var busMarker = new MapIcon
                    {
                        Image = RandomAccessStreamReference.CreateFromStream(stream),
                        CollisionBehaviorDesired = MapElementCollisionBehavior.RemainVisible,
                        Location = new Geopoint(new BasicGeoposition { Latitude = bus.latitude, Longitude = bus.longitude }),
                        NormalizedAnchorPoint = new Point(0.5, 0.5),
                        ZIndex = 99
                    };

                    SearchMap.MapElements.Add(busMarker);

                    await stream.FlushAsync();
                    stream.Dispose();
                    rotatedImage = null;
                }
                else if (bus.direction.Equals("outbound"))
                {
                    var rotatedImage = outboundBM.RotateFree(bus.busHeading, false);
                    var stream = new InMemoryRandomAccessStream();
                    await rotatedImage.ToStream(stream, BitmapEncoder.PngEncoderId);

                    var busMarker = new MapIcon
                    {
                        Image = RandomAccessStreamReference.CreateFromStream(stream),
                        CollisionBehaviorDesired = MapElementCollisionBehavior.RemainVisible,
                        Location = new Geopoint(new BasicGeoposition { Latitude = bus.latitude, Longitude = bus.longitude }),
                        NormalizedAnchorPoint = new Point(0.5, 0.5),
                        ZIndex = 99
                    };

                    SearchMap.MapElements.Add(busMarker);

                    await stream.FlushAsync();
                    stream.Dispose();
                    rotatedImage = null;
                }
                vehicleCounter++;
            }

            inboundBM = null;
            outboundBM = null;
        }
        private async void ScanButton(object sender, object e)
        {
            string result = null;

            try
            {
                Waiter(true);
                var tcs = new TaskCompletionSource<object>();

                StackPanel sp = new StackPanel() { Margin = new Thickness(20) };

#if WINDOWS_PHONE

                if (Device == null)
                {
                    Windows.Foundation.Size initialResolution = new Windows.Foundation.Size(640, 480);
                    wbm = new WriteableBitmap(640, 480);
                    Device = await PhotoCaptureDevice.OpenAsync(CameraSensorLocation.Back, initialResolution);
                    Device.SetProperty(KnownCameraGeneralProperties.EncodeWithOrientation,
                                  Device.SensorLocation == CameraSensorLocation.Back ?
                                  Device.SensorRotationInDegrees : -Device.SensorRotationInDegrees);
                    Device.SetProperty(KnownCameraGeneralProperties.AutoFocusRange, AutoFocusRange.Macro);
                    Device.SetProperty(KnownCameraPhotoProperties.SceneMode, CameraSceneMode.Macro);
                    Device.SetProperty(KnownCameraPhotoProperties.FocusIlluminationMode, FocusIlluminationMode.Off);
                }

                Rectangle previewRect = new Rectangle() { Height = 480, Width = 360 };
                VideoBrush previewVideo = new VideoBrush();
                previewVideo.RelativeTransform = new CompositeTransform()
                {
                    CenterX = 0.5,
                    CenterY = 0.5,
                    Rotation = (Device.SensorLocation == CameraSensorLocation.Back ?
                        Device.SensorRotationInDegrees : -Device.SensorRotationInDegrees)
                };
                previewVideo.SetSource(Device);
                previewRect.Fill = previewVideo;

                Grid combiner = new Grid() { Height = previewRect.Height, Width = previewRect.Width };
                combiner.Children.Add(previewRect);
                Grid.SetColumnSpan(previewRect, 3);
                Grid.SetRowSpan(previewRect, 3);

                int windowSize = 100;
                combiner.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(previewRect.Height / 2 - windowSize) });
                combiner.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(windowSize) });
                combiner.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(previewRect.Height / 2 - windowSize) });
                combiner.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(previewRect.Width / 2 - windowSize) });
                combiner.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(windowSize) });
                combiner.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(previewRect.Width / 2 - windowSize) });
                var maskBrush = new SolidColorBrush(Color.FromArgb(80, 0, 0, 0));
                Canvas v1 = new Canvas() { Background = maskBrush };
                Canvas v2 = new Canvas() { Background = maskBrush };
                Canvas v3 = new Canvas() { Background = maskBrush };
                Canvas v4 = new Canvas() { Background = maskBrush };
                combiner.Children.Add(v1); Grid.SetRow(v1, 0); Grid.SetColumnSpan(v1, 3);
                combiner.Children.Add(v2); Grid.SetRow(v2, 2); Grid.SetColumnSpan(v2, 3);
                combiner.Children.Add(v3); Grid.SetRow(v3, 1); Grid.SetColumn(v3, 0);
                combiner.Children.Add(v4); Grid.SetRow(v4, 1); Grid.SetColumn(v4, 2);
                sp.Children.Add(combiner);

                BackgroundWorker bw = new BackgroundWorker();
                DateTime last = DateTime.Now;

                bw.WorkerSupportsCancellation = true;
                bw.DoWork += async (s2, e2) =>
                {
                    var reader = new BarcodeReader();
                    while (!bw.CancellationPending)
                    {
                        if (DateTime.Now.Subtract(last).TotalSeconds > 2)
                        {
                            await Device.FocusAsync();
                            last = DateTime.Now;
                        }

                        try
                        {
                            Device.GetPreviewBufferArgb(wbm.Pixels);
                            Debug.WriteLine(DateTime.Now.Millisecond);
                            var codeVal = reader.Decode(wbm);
                            if (codeVal != null)
                            {
                                result = codeVal.Text;
                                e2.Cancel = true;
                                tcs.TrySetResult(null);
                            }
                        }
                        catch (Exception ex)
                        {
                            Debug.WriteLine(ex.ToString());
                        }
                    }
                };

                bw.RunWorkerAsync();

#else
                var cameras = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);
                if (cameras.Count < 1)
                {
                    return;
                }

                var settings = new MediaCaptureInitializationSettings { VideoDeviceId = cameras.Last().Id };
                var imageSource = new MediaCapture();
                await imageSource.InitializeAsync(settings);
                CaptureElement previewRect = new CaptureElement() { Width = 640, Height = 360 };
                previewRect.Source = imageSource;
                sp.Children.Add(previewRect);
                await imageSource.StartPreviewAsync();

                bool keepGoing = true;
                Action a = null;
                a = async () =>
                {
                    if (!keepGoing) return;
                    var stream = new InMemoryRandomAccessStream();
                    await imageSource.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), stream);

                    stream.Seek(0);

                    var tmpBmp = new WriteableBitmap(1, 1);
                    await tmpBmp.SetSourceAsync(stream);
                    var writeableBmp = new WriteableBitmap(tmpBmp.PixelWidth, tmpBmp.PixelHeight);
                    stream.Seek(0);
                    await writeableBmp.SetSourceAsync(stream);

                    Result _result = null;

                    var barcodeReader = new BarcodeReader
                    {
                        // TryHarder = true,
                        AutoRotate = true
                    };

                    try
                    {
                        _result = barcodeReader.Decode(writeableBmp);
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine(ex.ToString());
                    }

                    stream.Dispose();

                    if (_result != null)
                    {
                        result = _result.Text;
                        Debug.WriteLine(_result.Text);
                        keepGoing = false;
                        tcs.TrySetResult(null);
                    }
                    else
                    {
                        var x = RunOnUIThread(a);
                    }
                };

                await RunOnUIThread(a);
#endif

                CustomMessageBox messageBox = new CustomMessageBox()
                {
                    Title = "Scan Tag",
                    Message = "",
                    Content = sp,
                    LeftButtonContent = "OK",
                    RightButtonContent = "Cancel",
                    IsFullScreen = false,
                };

                messageBox.Unloaded += (s2, e2) =>
                {
                    tcs.TrySetResult(null);
                };
                messageBox.Show();

                await tcs.Task;

                messageBox.Dismiss();
#if WINDOWS_PHONE
                bw.CancelAsync();
#else
                keepGoing = false;
                await imageSource.StopPreviewAsync();
#endif

                Debug.WriteLine("result: '" + result + "'");
                string loc = null;
                string building = null;
                string floor = null;
                string room = null;

                if (!string.IsNullOrEmpty(result))
                {
                    var s = result.Split(new char[] { '?' }, 2);
                    if (s.Length == 2)
                    {
                        var paramList = s[1].Split('&')
                            .Select(p => p.Split(new char[] { '=' }, 2))
                            .Where(p => p.Length == 2);
                        loc = pick(paramList, "cp");
                        building = pick(paramList, "bld");
                        floor = pick(paramList, "flr");
                        room = pick(paramList, "rm");
                    }
                }

                GeoCoord? locVal = GeoCoord.Parse(loc);
                if (!string.IsNullOrEmpty(building) && !string.IsNullOrEmpty(floor))
                {
                    await ShowMap(RoomInfo.Parse(building + "/" + (room == null ? floor : room)), locVal);
                }
            }
            finally
            {
                Waiter(false);
            }
        }
        private async void Stream_Click1(object sender, RoutedEventArgs e)
        {
            byte[] startSequence = { 0, 0, 0, 1, 0x27, 0x4d };
            var    options       = new PropertySet();

            //options.Add("framerate", "25");
            //options.Add("vcodec", "copy");

            _ws = new StreamWebSocket();
            await _ws.ConnectAsync(new Uri(wsuri.Text, UriKind.Absolute));

            bool isStarted = false;
            bool isCreated = false;

            var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream();
            var output = stream.GetOutputStreamAt(0);
            var writer = new DataWriter(output);

            int        maxdelay = 10;
            int        delay    = maxdelay;
            int        index    = 0;
            DataReader reader   = new DataReader(_ws.InputStream);

            do
            {
                var loaded = await reader.LoadAsync(10 * 1024);

                var buf = reader.ReadBuffer(loaded);
                if (!isStarted)
                {
                    isStarted = true;
                    var signature = buf.ToArray();
                    index = Helpers.FindSequence(signature, 0, startSequence);
                    if (index == -1)
                    {
                        Debug.WriteLine("signature not found, continuing");
                        continue;
                    }

                    buf = signature.AsBuffer(index, signature.Length - index);
                    Debug.WriteLine("buffer created");
                    //await output.WriteAsync(buf);
                    writer.WriteBuffer(buf);
                }
                else
                {
                    //await output.WriteAsync(buf);
                    //await output.FlushAsync();
                    writer.WriteBuffer(buf);
                }

                await writer.StoreAsync();

                if (delay > 0)
                {
                    delay--;
                    Debug.Write("B");
                    //Debug.WriteLine(stream.Position);
                    continue;
                }
                //delay = maxdelay;

                //Debug.Write(".");
                try
                {
                    //await output.WriteAsync(buf);
                    if (!isCreated)
                    {
                        isCreated = true;
                        //stream.Seek((ulong)0);
                        var decoder = FFmpegInterop.FFmpegInteropMSS.CreateFFmpegInteropMSSFromStream(
                            stream, false, false, options);
                        if (decoder == null)
                        {
                            Debug.WriteLine("decoder was null, will retry");
                            continue;
                        }

                        var source = decoder.GetMediaStreamSource();
                        source.Closed          += Source_Closed;
                        source.Starting        += Source_Starting;
                        source.SampleRequested += Source_SampleRequested;
                        source.SampleRendered  += Source_SampleRendered;
                        //source.BufferTime = TimeSpan.FromSeconds(0.2);

                        media.SetMediaStreamSource(source);
                        media.Play();
                    }
                }
                catch (Exception err)
                {
                    Debug.WriteLine(err.ToString());
                    stream.Dispose();
                    reader.Dispose();
                    return;
                }
            }while (true);
        }