Example #1
0
        private static Stream LimitImageSize(Stream imageStream, double imageMaxDiagonalSize)
        {
            // In order to determine the size of the image we will transfer it to a writable bitmap.
            WriteableBitmap wb = new WriteableBitmap(1, 1);
            wb.SetSource(imageStream);

            // Check if we need to scale it down.
            double imageDiagonalSize = Math.Sqrt(wb.PixelWidth * wb.PixelWidth + wb.PixelHeight * wb.PixelHeight);
            if (imageDiagonalSize > imageMaxDiagonalSize)
            {
                // Calculate the new image size that corresponds to imageMaxDiagonalSize for the
                // diagonal size and that preserves the aspect ratio.
                int newWidth = (int)(wb.PixelWidth * imageMaxDiagonalSize / imageDiagonalSize);
                int newHeight = (int)(wb.PixelHeight * imageMaxDiagonalSize / imageDiagonalSize);

                Stream resizedStream = new MemoryStream();
                Extensions.SaveJpeg(wb, resizedStream, newWidth, newHeight, 0, 100);

                return resizedStream;
            }
            else
            {
                // No need to scale down. The image diagonal is less than or equal to imageMaxSizeDiagonal.
                return imageStream;
            }
        }
        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            try
            {
                PhotoChooserTask photoChooserTask           = new PhotoChooserTask();
                photoChooserTask.Completed += (ee,s)=>
                {
                    //DirectX context should be recreate before cereate the texture
                    Dispatcher.BeginInvoke(() =>
                   {
                       WriteableBitmap bmp = new WriteableBitmap(1,1);
                       bmp.SetSource(s.ChosenPhoto);
  
                       m_d3dInterop.CreateTexture(bmp.Pixels, bmp.PixelWidth, bmp.PixelHeight);
                       MessageBox.Show("Picture loaded with c#");
                   });


                };

                photoChooserTask.Show();

            }
            catch(Exception exp)
                {
                }
        }
Example #3
0
 // call by reference
 public static void resizeImage(ref WriteableBitmap bmp)
 {
     // TODO: memory management
     // we have 2 options
     // i) use "using" statement
     // ii) dispose of object "ms" before the method finishes (**check bmp1 as ms is set as it's source )
     MemoryStream ms = new MemoryStream();
     int h, w;
     if (bmp.PixelWidth > bmp.PixelHeight)
     {
         double aspRatio = bmp.PixelWidth / (double)bmp.PixelHeight;
         double hh, ww;
         hh = (640.0 / aspRatio);
         ww = hh * aspRatio;
         h = (int)hh;
         w = (int)ww;
     }
     else
     {
         double aspRatio = bmp.PixelHeight / (double)bmp.PixelWidth;
         double hh, ww;
         hh = (480.0 / aspRatio);
         ww = hh * aspRatio;
         h = (int)hh;
         w = (int)ww;
     }
     bmp.SaveJpeg(ms, w, h, 0, 100);
     bmp.SetSource(ms);
 }
        void task_Completed(object sender, PhotoResult e)
        {
            if(e.TaskResult == TaskResult.OK)
            {

                var bmp = new WriteableBitmap(0,0);
                bmp.SetSource(e.ChosenPhoto);

                var bmpres = new WriteableBitmap(bmp.PixelWidth,bmp.PixelHeight);

                var txt = new WindowsPhoneControl1();
                txt.Text = txtInput.Text;
                txt.FontSize = 36 * bmpres.PixelHeight / 480;
                txt.Width = bmpres.PixelWidth;
                txt.Height = bmpres.PixelHeight;

                //should call Measure and  when uicomponent is not in visual tree
                txt.Measure(new Size(bmpres.PixelWidth, bmpres.PixelHeight));
                txt.Arrange(new Rect(0, 0, bmpres.PixelWidth, bmpres.PixelHeight));

                bmpres.Render(new Image() { Source = bmp }, null);
                bmpres.Render(txt, null);

                bmpres.Invalidate();
                display.Source = bmpres;

            }
        }
      private static void assertCorrectImage2result(String path, ExpandedProductParsedResult expected)
      {
         RSSExpandedReader rssExpandedReader = new RSSExpandedReader();

         if (!File.Exists(path))
         {
            // Support running from project root too
            path = Path.Combine("..\\..\\..\\Source", path);
         }

#if !SILVERLIGHT
         var image = new Bitmap(Image.FromFile(path));
#else
         var image = new WriteableBitmap(0, 0);
         image.SetSource(File.OpenRead(path));
#endif
         BinaryBitmap binaryMap = new BinaryBitmap(new GlobalHistogramBinarizer(new BitmapLuminanceSource(image)));
         int rowNumber = binaryMap.Height / 2;
         BitArray row = binaryMap.getBlackRow(rowNumber, null);

         Result theResult = rssExpandedReader.decodeRow(rowNumber, row, null);
         Assert.IsNotNull(theResult);

         Assert.AreEqual(BarcodeFormat.RSS_EXPANDED, theResult.BarcodeFormat);

         ParsedResult result = ResultParser.parseResult(theResult);

         Assert.AreEqual(expected, result);
      }
Example #6
0
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            ApplicationBar.Opacity = 0.5;
            if (this.NavigationContext.QueryString.ContainsKey("nid"))
            {
                var nid = Int32.Parse(this.NavigationContext.QueryString["nid"]);
                Capitulo c;

                if (AU.Instance.Capitulos.TryGetValue(nid, out c))
                {
                    PageTitle.Text = c.Nombre;
                    sinopsis.Text = c.TextoNoti;
                    textAutor.Text = c.NotiAutor;
                    textFecha.Text = c.ReleaseDate.ToString();
                    var i = 0;

                    serieId = c.Serie;
                    foreach (String file in c.Imagenes)
                    {
                        using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
                        {

                            if (myIsolatedStorage.FileExists(file))
                            {
                                using (var imageStream = myIsolatedStorage.OpenFile(file, FileMode.Open, FileAccess.Read))
                                {
                                    WriteableBitmap temp = new WriteableBitmap(0, 0);
                                    try
                                    {
                                        Image image1 = new Image();
                                        WriteableBitmap aux = new WriteableBitmap(0, 0);
                                        aux.SetSource(imageStream);
                                        image1.Source = (ImageSource)aux;
                                        image1.HorizontalAlignment = HorizontalAlignment.Left;
                                        image1.VerticalAlignment = VerticalAlignment.Top;
                                        image1.Stretch = Stretch.Uniform;
                                        ColumnDefinition colDef3 = new ColumnDefinition();
                                        imagenes.ColumnDefinitions.Add(colDef3);
                                        Grid.SetColumn(image1, i);
                                        i++;
                                        imagenes.Children.Add(image1);


                                    }
                                    catch (ArgumentException ae)
                                    {

                                    }

                                }
                            }
                        }
                    }
                }
            }
            else
            {
                // I use this condition to handle creating new items.
            }
        }
Example #7
0
        public static WriteableBitmap toWriteableBitmap(Stream stream, int pixelWidth, int pixelHeight) {
            BitmapImage bitmapImage = new BitmapImage();
            bitmapImage.SetSource(stream);

            WriteableBitmap bitmap = new WriteableBitmap(pixelWidth, pixelWidth);
            bitmap.SetSource(stream);
            return bitmap;
        }
Example #8
0
 public BitmapImage BytesToImage(byte[] array, int width, int height)
 {
     WriteableBitmap result = new WriteableBitmap(width, height);
     MemoryStream ms = new MemoryStream();
     ms.Write(array, 0, array.Length);
     result.SetSource(ms);
     BitmapImage bitmapImage = new BitmapImage();
     bitmapImage.SetSource(ms);
     return bitmapImage;
 }
Example #9
0
 public static WriteableBitmap ReadImageFromIsolatedStorage(string imageName, int width, int height)
 {
     using (var isoStore = IsolatedStorageFile.GetUserStoreForApplication())
     {
         using (var fileStream = isoStore.OpenFile(imageName, FileMode.Open, FileAccess.Read))
         {
             var bitmap = new WriteableBitmap(width, height);
             bitmap.SetSource(fileStream);
             return bitmap;
         }
     }
 }
        public async static Task<WriteableBitmap> ToBitmapImageAsync(this Stream imageStream, Tuple<int, int> downscale, bool useDipUnits, InterpolationMode mode, ImageInformation imageInformation = null)
        {
            if (imageStream == null)
                return null;

            using (IRandomAccessStream image = new RandomStream(imageStream))
            {
                if (downscale != null && (downscale.Item1 > 0 || downscale.Item2 > 0))
                {
                    using (var downscaledImage = await image.ResizeImage(downscale.Item1, downscale.Item2, mode, useDipUnits, imageInformation).ConfigureAwait(false))
                    {
                        BitmapDecoder decoder = await BitmapDecoder.CreateAsync(downscaledImage);
                        downscaledImage.Seek(0);
                        WriteableBitmap resizedBitmap = null;

                        await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Low, () =>
                        {
                            resizedBitmap = new WriteableBitmap((int)decoder.PixelWidth, (int)decoder.PixelHeight);
                            using (var s = downscaledImage.AsStream())
                            {
                                resizedBitmap.SetSource(s);
                            }
                        });

                        return resizedBitmap;
                    }
                }
                else
                {
                    BitmapDecoder decoder = await BitmapDecoder.CreateAsync(image);
                    image.Seek(0);
                    WriteableBitmap bitmap = null;

                    if (imageInformation != null)
                    {
                        imageInformation.SetCurrentSize((int)decoder.PixelWidth, (int)decoder.PixelHeight);
                        imageInformation.SetOriginalSize((int)decoder.PixelWidth, (int)decoder.PixelHeight);
                    }

                    await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Low, () =>
                    {
                        bitmap = new WriteableBitmap((int)decoder.PixelWidth, (int)decoder.PixelHeight);
                        bitmap.SetSource(imageStream);
                    });

                    return bitmap;
                }
            }
        }
Example #11
0
        public void CreateDeadTileBitmap()
        {
            // load your image
            StreamResourceInfo info = Application.GetResourceStream(new Uri(DEAD_TILE, UriKind.Relative));
            // create source bitmap for Image control (image is assumed to be alread 173x173)
            WriteableBitmap wbmp = new WriteableBitmap(173, 173);
            wbmp.SetSource(info.Stream);

            // save image to isolated storage
            using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
            {
                // use of "/Shared/ShellContent/" folder is mandatory!
                using (IsolatedStorageFileStream imageStream = new IsolatedStorageFileStream("/Shared/ShellContent/Tile.jpg", System.IO.FileMode.Create, isf))
                {
                    wbmp.SaveJpeg(imageStream, wbmp.PixelWidth, wbmp.PixelHeight, 0, 100);
                }
            }
        }
Example #12
0
      private static WriteableBitmap loadImage(String fileName)
#endif
      {
         String file = BASE_IMAGE_PATH + fileName;
         if (!File.Exists(file))
         {
            // try starting with 'core' since the test base is often given as the project root
            file = "..\\..\\..\\Source\\" + BASE_IMAGE_PATH + fileName;
         }
         Assert.IsTrue(File.Exists(file), "Please run from the 'core' directory");
#if !SILVERLIGHT
         return (Bitmap)Bitmap.FromFile(file);
#else
         var wb = new WriteableBitmap(0, 0);
         wb.SetSource(File.OpenRead(file));
         return wb;
#endif
      }
Example #13
0
        public async static Task<WriteableBitmap> ToBitmapImageAsync(this byte[] imageBytes, Tuple<int, int> downscale, InterpolationMode mode)
        {
            if (imageBytes == null)
                return null;

            using (var imageStream = imageBytes.AsBuffer().AsStream())
            using (IRandomAccessStream image = new RandomStream(imageStream))
            {
                if (downscale != null && (downscale.Item1 > 0 || downscale.Item2 > 0))
                {
                    using (var downscaledImage = await image.ResizeImage((uint)downscale.Item1, (uint)downscale.Item2, mode).ConfigureAwait(false))
                    {
                        BitmapDecoder decoder = await BitmapDecoder.CreateAsync(downscaledImage);
                        downscaledImage.Seek(0);
                        WriteableBitmap resizedBitmap = null;

                        await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Low, () =>
                        {
                            resizedBitmap = new WriteableBitmap((int)decoder.PixelWidth, (int)decoder.PixelHeight);
                            using (var s = downscaledImage.AsStream())
                            {
                                resizedBitmap.SetSource(s);
                            }
                        });

                        return resizedBitmap;
                    }
                }
                else
                {
                    BitmapDecoder decoder = await BitmapDecoder.CreateAsync(image);
                    image.Seek(0);
                    WriteableBitmap bitmap = null;

                    await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Low, () =>
                    {
                        bitmap = new WriteableBitmap((int)decoder.PixelWidth, (int)decoder.PixelHeight);
                        bitmap.SetSource(imageStream);
                    });

                    return bitmap;
                }
            }
        }
      public void testFindFinderPatterns()
      {
         RSSExpandedReader rssExpandedReader = new RSSExpandedReader();

         String path = "test/data/blackbox/rssexpanded-1/2.png";

         if (!File.Exists(path))
         {
            // Support running from project root too
            path = Path.Combine("..\\..\\..\\Source", path);
         }

#if !SILVERLIGHT
         var image = new Bitmap(Image.FromFile(path));
#else
         var image = new WriteableBitmap(0, 0);
         image.SetSource(File.OpenRead(path));
#endif
         BinaryBitmap binaryMap = new BinaryBitmap(new GlobalHistogramBinarizer(new BitmapLuminanceSource(image)));
         int rowNumber = binaryMap.Height / 2;
         BitArray row = binaryMap.getBlackRow(rowNumber, null);
         List<ExpandedPair> previousPairs = new List<ExpandedPair>();

         ExpandedPair pair1 = rssExpandedReader.retrieveNextPair(row, previousPairs, rowNumber);
         previousPairs.Add(pair1);
         FinderPattern finderPattern = pair1.FinderPattern;
         Assert.IsNotNull(finderPattern);
         Assert.AreEqual(0, finderPattern.Value);

         ExpandedPair pair2 = rssExpandedReader.retrieveNextPair(row, previousPairs, rowNumber);
         previousPairs.Add(pair2);
         finderPattern = pair2.FinderPattern;
         Assert.IsNotNull(finderPattern);
         Assert.AreEqual(1, finderPattern.Value);

         ExpandedPair pair3 = rssExpandedReader.retrieveNextPair(row, previousPairs, rowNumber);
         previousPairs.Add(pair3);
         finderPattern = pair3.FinderPattern;
         Assert.IsNotNull(finderPattern);
         Assert.AreEqual(1, finderPattern.Value);

         //   the previous was the last pair
         Assert.IsNull(rssExpandedReader.retrieveNextPair(row, previousPairs, rowNumber));
      }
Example #15
0
 private void btnDecoderOpen_Click(object sender, RoutedEventArgs e)
 {
    var dlg = new OpenFileDialog();
    dlg.Filter = "PNG (*.png)|*.png";
    if (dlg.ShowDialog().GetValueOrDefault(false))
    {
       try
       {
          currentBarcode = new WriteableBitmap(0, 0);
          using (var stream = dlg.File.OpenRead())
          {
             currentBarcode.SetSource(stream);
          }
          imgDecoderBarcode.Source = currentBarcode;
       }
       catch (Exception exc)
       {
          txtDecoderContent.Text = exc.Message;
       }
    }
 }
        /// <summary>
        /// It will ensure that the photo does not exceed a maximum size. 
        /// If needed the photo is scaled down by preserving its aspect ratio.
        /// </summary>
        /// <param name="photoStream">
        /// The stream that represents the photo as returned by CameraCaptureTask or PhotoChooserTask.
        /// </param>
        /// <param name="photoMaxSizeDiagonal">
        /// The diagonal of the scaled down photo.
        /// </param>
        /// <returns>
        /// Returns a stream that has the scaled-down photo in JPEG format.
        /// If the original stream represents a photo that is smaller or the same size as the scale-down size
        /// then it returns the original stream.
        /// </returns>
        public static Stream LimitPhotoSize(Stream photoStream, double photoMaxSizeDiagonal)
        {
            WriteableBitmap wb = new WriteableBitmap(1, 1);
            wb.SetSource(photoStream);

            // Only scale down if needed.
            double photoSizeDiagonal = Math.Sqrt(wb.PixelWidth * wb.PixelWidth + wb.PixelHeight * wb.PixelHeight);
            if (photoSizeDiagonal > photoMaxSizeDiagonal)
            {
                int newWidth = (int)(wb.PixelWidth * photoMaxSizeDiagonal / photoSizeDiagonal);
                int newHeight = (int)(wb.PixelHeight * photoMaxSizeDiagonal / photoSizeDiagonal);

                Stream resizedStream = new MemoryStream();
                Extensions.SaveJpeg(wb, resizedStream, newWidth, newHeight, 0, 100);

                return resizedStream;
            }

            // No need to scale down. The photo is smaller or the same size as the scale-down size
            return photoStream;
        }
        /// <summary>
        /// Hawaii limits the size of the image you can submit, so this checks to see if the given stream is valid.
        /// </summary>
        /// <param name="imageStream"></param>
        /// <param name="maxPictureSizeDiag"></param>
        /// <returns>Either a resized stream, or the original stream if it's the correct size.</returns>
        private static Stream ScaleImage(Stream imageStream, double maxPictureSizeDiag)
        {
            // Place image in a writeable bmp to determine its size
            var wb = new WriteableBitmap(1, 1);
            wb.SetSource(imageStream);

            // Is a scale down needed
            var imgDiag = Math.Sqrt(wb.PixelHeight*wb.PixelHeight + wb.PixelWidth*wb.PixelWidth);
            if (imgDiag > maxPictureSizeDiag)
            {
                var newWidth = (int) (wb.PixelWidth*maxPictureSizeDiag/imgDiag);
                var newHeight = (int) (wb.PixelHeight*maxPictureSizeDiag/imgDiag);

                Stream resizedStream = null;
                Stream tempStream = null;

                try
                {
                    tempStream = new MemoryStream();
                    wb.SaveJpeg(tempStream, newWidth, newHeight, 0, 100);
                    resizedStream = tempStream;
                    tempStream = null;
                }
                finally
                {
                    if (tempStream != null)
                    {
                        tempStream.Close();
                        tempStream = null;
                    }
                }

                return resizedStream;
            }
            else
            {
                // Returns the original stream if you don't need to scale down
                return imageStream;
            }
        }
Example #18
0
        /// <summary>
        /// It will ensure that the photo does not exceed a maximum size. 
        /// If needed the photo is scaled down by preserving its aspect ratio.
        /// </summary>
        /// <param name="photoStream">
        /// The stream that represents the photo as returned by CameraCaptureTask or PhotoChooserTask.
        /// </param>
        /// <param name="photoMaxSizeDiagonal">
        /// The diagonal of the scaled down photo.
        /// </param>
        /// <returns>
        /// Returns a stream that has the scaled-down photo in JPEG format.
        /// If the original stream represents a photo that is smaller or the same size as the scale-down size
        /// then it returns the original stream.
        /// </returns>
        public static Stream LimitPhotoSize(Stream photoStream, double photoMaxSizeDiagonal)
        {
            WriteableBitmap wb = new WriteableBitmap(1, 1);
            wb.SetSource(photoStream);

            // Only scale down if needed.
            double photoSizeDiagonal = Math.Sqrt(wb.PixelWidth * wb.PixelWidth + wb.PixelHeight * wb.PixelHeight);
            if (photoSizeDiagonal > photoMaxSizeDiagonal)
            {
                int newWidth = (int)(wb.PixelWidth * photoMaxSizeDiagonal / photoSizeDiagonal);
                int newHeight = (int)(wb.PixelHeight * photoMaxSizeDiagonal / photoSizeDiagonal);

                Stream resizedStream = null;
                Stream tempStream = null;

                // This try/finally block is needed to avoid CA2000: Dispose objects before losing scope
                // See http://msdn.microsoft.com/en-us/library/ms182289.aspx for more details.
                try
                {
                    tempStream = new MemoryStream();
                    Extensions.SaveJpeg(wb, tempStream, newWidth, newHeight, 0, 100);
                    resizedStream = tempStream;
                    tempStream = null;
                }
                finally
                {
                    if (tempStream != null)
                    {
                        tempStream.Close();
                        tempStream = null;
                    }
                }

                return resizedStream;
            }

            // No need to scale down. The photo is smaller or the same size as the scale-down size
            return photoStream;
        }
Example #19
0
        private void photoChooserTask_Completed(object sender, PhotoResult e)
        {
            if (e.TaskResult == TaskResult.OK)
            {
                updateUndoList();

                bm = new WriteableBitmap(canvas1, null);

                double width = bm.PixelWidth;
                double height = bm.PixelHeight;

                bm.SetSource(e.ChosenPhoto);

                double scaleX = bm.PixelWidth / width;
                double scaleY = bm.PixelHeight / height;

                //For debugging
                //System.Diagnostics.Debug.WriteLine(width + " - " + height);
                //System.Diagnostics.Debug.WriteLine(bm.PixelWidth + " :: " + bm.PixelHeight);
                //System.Diagnostics.Debug.WriteLine(scaleX + " = " + scaleY);

                bm = bm.Resize((int)(bm.PixelWidth / scaleX),
                               (int)(bm.PixelHeight / scaleY),
                               WriteableBitmapExtensions.Interpolation.Bilinear);

                updateCanvasFromWBM(bm);
                makeToast("", "Load Successful");

                //Frank: Look into cleaning up this Imagesource mess later with the following trick
                //Code to display the photo on the page in an image control named myImage.
                //System.Windows.Media.Imaging.BitmapImage bmp = new System.Windows.Media.Imaging.BitmapImage();
                //bmp.SetSource(e.ChosenPhoto);
                //myImage.Source = bmp;
            }
            else
            {
                makeToast("Uh oh!", "Load Failed");
            }
        }
Example #20
0
		public override Codec.DecodeResult Decode( Stream input )
		{
			return ThreadUI.Invoke(
				delegate
				{
					var wbs = new WriteableBitmap( 0, 0 );
					wbs.SetSource( input );
					wbs.Invalidate();
					input.Close();
					return Decode( wbs );
				} );
		}
      private static void assertCorrectImage2binary(String path, String expected)
      {
         RSSExpandedReader rssExpandedReader = new RSSExpandedReader();

         if (!File.Exists(path))
         {
            // Support running from project root too
            path = Path.Combine("..\\..\\..\\Source", path);
         }

#if !SILVERLIGHT
         var image = new Bitmap(Image.FromFile(path));
#else
         var image = new WriteableBitmap(0, 0);
         image.SetSource(File.OpenRead(path));
#endif
         BinaryBitmap binaryMap = new BinaryBitmap(new GlobalHistogramBinarizer(new BitmapLuminanceSource(image)));
         int rowNumber = binaryMap.Height / 2;
         BitArray row = binaryMap.getBlackRow(rowNumber, null);

         Assert.IsTrue(rssExpandedReader.decodeRow2pairs(rowNumber, row));

         BitArray binary = BitArrayBuilder.buildBitArray(rssExpandedReader.Pairs);
         Assert.AreEqual(expected, binary.ToString());
      }
Example #22
0
        public static void updateTile(string backgroundPath, string frontText)
        {
            Uri backgroundUri = new Uri(backgroundPath, UriKind.Relative);
            MemoryStream ms = new MemoryStream();
            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                Grid grid = new Grid();
                StreamResourceInfo info = Application.GetResourceStream(backgroundUri);
                info.Stream.CopyTo(ms);
                /*BitmapImage imageSource = new BitmapImage(backgroundUri);
                grid.Background = new ImageBrush {
                    ImageSource = imageSource,
                    Opacity = 1,
                };*/
                WriteableBitmap imgSrc = new WriteableBitmap(1, 1);
                imgSrc.SetSource(info.Stream);
                Image img = new Image();
                img.Source = imgSrc;
                grid.Children.Add(img);
                /*TextBlock text = new TextBlock() { FontSize = 20, Foreground = new SolidColorBrush(Colors.White) };
                text.Text = frontText;
                text.HorizontalAlignment = System.Windows.HorizontalAlignment.Right;
                text.VerticalAlignment = System.Windows.VerticalAlignment.Bottom;
                Thickness th = new Thickness();
                th.Top = 143;
                th.Left = 133;
                text.Margin = th;
                grid.Children.Add(text);
                 */
                grid.Arrange(new Rect(0, 0, 173, 173)); // force render

                WriteableBitmap wbmp = new WriteableBitmap(173, 173);
                Canvas can = new Canvas();
                can.Background = (SolidColorBrush)Application.Current.Resources["PhoneAccentBrush"];
                can.Width = 173;
                can.Height = 173;
                wbmp.Render(can, null);
                wbmp.Render(grid, null);
                wbmp.Invalidate();
                //wbmp.SaveJpeg(ms, 173, 173, 0, 100);
            });
            using (var stream = isolatedStorage.CreateFile("/Shared/ShellContent/tile.png"))
            {
                ms.CopyTo(stream);
            }

            TranslationHelper.Pair<string, int> title_info = TranslationHelper.getTitle();
            string tile_title = title_info.First;
            int tile_width = title_info.Second;

            string title = tile_title + spaces(tile_width - tile_title.Length - frontText.Length) + frontText;
            Uri iconUri = new Uri("isostore:/Shared/ShellContent/tile.png", UriKind.Absolute);
            ShellTile TileToFind = ShellTile.ActiveTiles.First();
            if (TileToFind != null)
            {
                StandardTileData NewTileData = new StandardTileData
                {
                    Title = title,
                    Count = 0,
                    BackgroundImage = backgroundUri,
                };
                TileToFind.Update(NewTileData);
            }
        }
        void uploadButton_Click(object sender, RoutedEventArgs e)
        {
            if (!NetworkInterface.GetIsNetworkAvailable())
            {
                displayPopup(popupTitle2, popupContent1);
                return;
            }
            var uploadButton = DynamicPanel.Children.OfType<Button>().First() as Button;
            uploadButton.IsEnabled = false;
           
           SubmissionProgressBar.IsIndeterminate = true;
            String filename = App.toBeSubmit[App.currentSubmissionIndex].ImageName + ".jpg";
            WriteableBitmap image = new WriteableBitmap(2560, 1920);
            using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                using (IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile("MyScience/Images/" + filename, FileMode.Open, FileAccess.Read))
                {
                    image.SetSource(fileStream);
                }
            }
            MemoryStream ms = new MemoryStream();
            image.SaveJpeg(ms, image.PixelWidth, image.PixelHeight, 0, 100);
            byte[] imageData = ms.ToArray();
            App.toBeSubmit[App.currentSubmissionIndex].ImageData = imageData;

            //Low Res Pic submission 
            MemoryStream lowresms = new MemoryStream();
            image.SaveJpeg(lowresms, 80, 60, 0, 80);
            byte[] lowResImageData = lowresms.ToArray();
            App.toBeSubmit[App.currentSubmissionIndex].LowResImageData = lowResImageData;

            Service1Client client = new Service1Client();
            client.SubmitDataCompleted += new EventHandler<SubmitDataCompletedEventArgs>(client_SubmitDataCompleted);
            client.SubmitDataAsync(App.toBeSubmit[App.currentSubmissionIndex]);
        }
        private WriteableBitmap CreateTemporaryBitmap()
        {
            WriteableBitmap b = new WriteableBitmap(100, 100);
            b.SetSource(_model.Picture.GetThumbnail());

            return b;
        }
Example #25
0
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            if (this.NavigationContext.QueryString.ContainsKey("eid"))
            {
                var nid = Int32.Parse(this.NavigationContext.QueryString["eid"]);
                Ente c;

                if (AU.Instance.Entes.TryGetValue(nid, out c))
                {
                    PageTitle.Text = c.Nombre;
                    textSexo.Text = c.Sexo;
                    if (c.Sexo == null || c.Sexo=="")
                    {
                        textSexo.Text = "Sin definir";
                    }
                    textBio.Text = c.Bio;
                    if (c.Bio == null || c.Bio == "")
                    {
                        textBio.Text = "Sin definir";
                    }

                    textEdad.Text = c.Edad.ToString();
                    if (textEdad.Text == "0")
                    {
                        textEdad.Text = "Sin definir";
                    }
                    textCiudad.Text = c.Ciudad;
                    if (c.Ciudad == null || c.Ciudad == "")
                    {
                        textCiudad.Text = "Sin definir";
                    }

                    textTitulo.Text = c.Titulo;
                    if (c.Titulo == null || c.Titulo == "")
                    {
                        textTitulo.Visibility = Visibility.Collapsed;
                    }

                    seriescapis.Text = " " + c.SeriesHechas + " series y " + c.CapitulosHechos + " capítulos";
                    var i = 0;
                    var file = c.Avatar;
                    using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
                        {

                            if (myIsolatedStorage.FileExists(file))
                            {
                                using (var imageStream = myIsolatedStorage.OpenFile(file, FileMode.Open, FileAccess.Read))
                                {
                                    try
                                    {
                                        WriteableBitmap aux = new WriteableBitmap(0, 0);
                                        aux.SetSource(imageStream);
                                        image1.Source = (ImageSource)aux;
                                    }
                                    catch (ArgumentException ae)
                                    {

                                    }

                                }
                            }
                        }
                    foreach (Ocupacion o in c.Ocupaciones)
                    {
                        Serie s;
                        if (AU.Instance.Series.TryGetValue(o.Serie, out s))
                        {
                            TextBlock t = new TextBlock();
                            t.TextWrapping = TextWrapping.Wrap;
                            t.Width = listBox1.Width-10;
                            t.LineHeight = 50;
                            t.FontSize = 25;
                            t.Text = s.Nombre + " " + o.Capis + " capítulos.";
                            listBox1.Items.Add(t);

                        }
                    }
                }
            }
            else
            {
                // I use this condition to handle creating new items.
            }
        }
Example #26
0
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            if (this.NavigationContext.QueryString.ContainsKey("id"))
            {
                var id = Int32.Parse(this.NavigationContext.QueryString["id"]);
                  if (AU.Instance.Series.TryGetValue(id, out s))
                {
                    PageTitle.Text = s.Nombre;
                    sinopsis.Text = s.Sinopsis;
                    formato.Text = s.Formato;
                    generos.Text = une(s.Generos);
                    estudio.Text = une(s.Estudios);


                    ApplicationBar.Buttons.Clear();
                    if (s.Precuela != 0)
                    {
                        ApplicationBarIconButton a = new ApplicationBarIconButton(new Uri("/icons/appbar.back.rest.png", UriKind.Relative)) { Text = "Precuela" };
                        a.Click += new EventHandler(ApplicationBarIconButton_Click_Precuela);
                        ApplicationBar.Buttons.Add(a);
                    }

                    if (s.Secuela != 0)
                    {
                        ApplicationBarIconButton a = new ApplicationBarIconButton(new Uri("/icons/appbar.next.rest.png", UriKind.Relative)) { Text = "Secuela" };
                        a.Click += new EventHandler(ApplicationBarIconButton_Click_Secuela);
                        ApplicationBar.Buttons.Add(a);
                    }
                    else
                    {
                        Serie sAux;
                        if (AU.Instance.Precuelas.TryGetValue(s.Id, out sAux))
                        {
                            s.Secuela = sAux.Id;
                            ApplicationBarIconButton a = new ApplicationBarIconButton(new Uri("/icons/appbar.next.rest.png", UriKind.Relative)) { Text = "Secuela" };
                            a.Click += new EventHandler(ApplicationBarIconButton_Click_Secuela);
                            ApplicationBar.Buttons.Add(a);
                        }
                    }

                    if (ApplicationBar.Buttons.Count == 0)
                    {
                        ApplicationBar.IsVisible = false;
                    }

                    var file = s.Imagen;
                    using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
                    {

                        if (myIsolatedStorage.FileExists(file))
                        {
                            using (var imageStream = myIsolatedStorage.OpenFile(file, FileMode.Open, FileAccess.Read))
                            {
                                WriteableBitmap temp = new WriteableBitmap(0, 0);
                                try
                                {
                                    WriteableBitmap aux = new WriteableBitmap(0, 0);
                                    aux.SetSource(imageStream);
                                    image1.Source = (ImageSource)aux;
                                }
                                catch (ArgumentException ae)
                                {

                                }

                            }
                        }
                    }
                }
            }
            else
            {
                // I use this condition to handle creating new items.
            }
        }
      public void testDecodeDataCharacter()
      {
         RSSExpandedReader rssExpandedReader = new RSSExpandedReader();

         String path = "test/data/blackbox/rssexpanded-1/3.png";
         if (!File.Exists(path))
         {
            // Support running from project root too
            path = Path.Combine("..\\..\\..\\Source", path);
         }

#if !SILVERLIGHT
         var image = new Bitmap(Image.FromFile(path));
#else
         var image = new WriteableBitmap(0, 0);
         image.SetSource(File.OpenRead(path));
#endif
         BinaryBitmap binaryMap = new BinaryBitmap(new GlobalHistogramBinarizer(new BitmapLuminanceSource(image)));
         BitArray row = binaryMap.getBlackRow(binaryMap.Height / 2, null);

         int[] startEnd = { 145, 243 };//image pixels where the A1 pattern starts (at 124) and ends (at 214)
         int value = 0; // A
#if !SILVERLIGHT
         FinderPattern finderPatternA1 = new FinderPattern(value, startEnd, startEnd[0], startEnd[1], image.Height / 2);
#else
         FinderPattern finderPatternA1 = new FinderPattern(value, startEnd, startEnd[0], startEnd[1], image.PixelHeight / 2);
#endif
         //{1, 8, 4, 1, 1};
         DataCharacter dataCharacter = rssExpandedReader.decodeDataCharacter(row, finderPatternA1, true, false);

         Assert.AreEqual(19, dataCharacter.Value);
         Assert.AreEqual(1007, dataCharacter.ChecksumPortion);
      }
Example #28
0
        void camera_CaptureImageAvailable(object sender, ContentReadyEventArgs e)
        {
            // camera.

            Deployment.Current.Dispatcher.BeginInvoke(delegate()
               {
                   if (e.ImageStream != null)
                   {
                       bordercap.Visibility = System.Windows.Visibility.Visible;
                       WriteableBitmap bmp = new WriteableBitmap(Convert.ToInt32(camera.Resolution.Width), Convert.ToInt32(camera.Resolution.Height));
                       if (myVar.Effect is EchoEffect)
                       {
                           bmp.SetSource(e.ImageStream);

                       }
                       else
                       {
                           int[] pixelData = new int[Convert.ToInt32(camera.Resolution.Width) * Convert.ToInt32(camera.Resolution.Height)];
                           camera.GetPreviewBufferArgb32(pixelData);
                           int[] imageData = myVar.Effect.ProcessImage(pixelData);
                           imageData.CopyTo(bmp.Pixels, 0);
                           bmp.Invalidate();

                       }
                       imagecap.Source = bmp;

                       var vm = this.DataContext as MainViewModel;
                       vm.SaveImage(bmp);
                       ////Copy to WriteableBitmap

                   }

               });
            //throw new NotImplementedException();
        }
        Image LoadImage()
        {
            // The image will be read from isolated storage into the following byte array
            byte[] data;

            // Read the entire image in one go into a byte array
            using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
            {
                // Open the file - error handling omitted for brevity
                // Note: If the image does not exist in isolated storage the following exception will be generated:
                // System.IO.IsolatedStorage.IsolatedStorageException was unhandled
                // Message=Operation not permitted on IsolatedStorageFileStream
                using (IsolatedStorageFileStream isfs = isf.OpenFile("izvorna.slika", FileMode.Open, FileAccess.Read))
                {
                    // Allocate an array large enough for the entire file
                    data = new byte[isfs.Length];
                    // Read the entire file and then close it
                    isfs.Read(data, 0, data.Length);
                    isfs.Close();
                }
            }
            // Create memory stream and bitmap
            MemoryStream ms = new MemoryStream(data);
            WriteableBitmap bi = new WriteableBitmap(1000,1000);
            // Set bitmap source to memory stream
            bi.SetSource(ms);
            // Create an image UI element – Note: this could be declared in the XAML instead
            Image image = new Image();
            // Set size of image to bitmap size for this demonstration
            image.Height = bi.PixelHeight;
            image.Width = bi.PixelWidth;
            // Assign the bitmap image to the image’s source
            image.Source = bi;
            return image;
        }
Example #30
0
        void camera_Completed(object sender, PhotoResult e)
        {
            if (e.TaskResult == TaskResult.OK)
            {
                BitmapImage tmp = new BitmapImage();
                tmp.SetSource(e.ChosenPhoto);
                WriteableBitmap bmp = new WriteableBitmap(tmp);
                int[] dimension = ParseContract.SOSRequestTable.GetImageWidthHeight(bmp.PixelWidth, bmp.PixelHeight);

                Debug.WriteLine(dimension[0] + " " + dimension[1]);
                imageStream = new MemoryStream();
                bmp.SaveJpeg(imageStream, dimension[0], dimension[1], 0, 100);//Resize and save the image to the stream

                bmp.SetSource(imageStream);

                AddPhotoImage.Source = bmp;
                //AddPhotoImage.Source = new BitmapImage(new Uri("/Assets/car.png", UriKind.Relative));
                DeletePhotoImage.Visibility = System.Windows.Visibility.Visible;
            }
        }