示例#1
1
        public static Uri Create(string filename, string text, SolidColorBrush backgroundColor, double textSize, Size size)
        {
            var background = new Rectangle();
            background.Width = size.Width;
            background.Height = size.Height;
            background.Fill = backgroundColor;

            var textBlock = new TextBlock();
            textBlock.Width = 500;
            textBlock.Height = 500;
            textBlock.TextWrapping = TextWrapping.Wrap;
            textBlock.Text = text;
            textBlock.FontSize = textSize;
            textBlock.Foreground = new SolidColorBrush(Colors.White);
            textBlock.FontFamily = new FontFamily("Segoe WP");

            var tileImage = "/Shared/ShellContent/" + filename;
            using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
            {
                var bitmap = new WriteableBitmap((int)size.Width, (int)size.Height);
                bitmap.Render(background, new TranslateTransform());
                bitmap.Render(textBlock, new TranslateTransform() { X = 39, Y = 88 });
                var stream = store.CreateFile(tileImage);
                bitmap.Invalidate();
                bitmap.SaveJpeg(stream, (int)size.Width, (int)size.Height, 0, 99);
                stream.Close();
            }
            return new Uri("ms-appdata:///local" + tileImage, UriKind.Absolute);
        }
示例#2
1
        private static void SaveTileBackgroundImage(TileViewModel model)
        {
            string xamlCode;

            using (var tileStream = Application.GetResourceStream(new Uri("/WP7LiveTileDemo;component/Controls/CustomTile.xaml", UriKind.Relative)).Stream)
            {
                using (var reader = new StreamReader(tileStream))
                {
                    xamlCode = reader.ReadToEnd();
                }
            }

            var control = (Control)XamlReader.Load(xamlCode);
            control.DataContext = model;

            var bitmap = new WriteableBitmap(173, 173);

            bitmap.Render(control, new TranslateTransform());

            using (var store = IsolatedStorageFile.GetUserStoreForApplication())
            {
                using (var stream = store.CreateFile(TileBackgroundPath))
                {
                    bitmap.Invalidate();
                    bitmap.SaveJpeg(stream, 173, 173, 0, 100);
                    stream.Close();
                }
            }
        }
示例#3
1
文件: SkiaView.cs 项目: Core2D/Core2D
        private void Render(DrawingContext drawingContext)
        {
            if (_width > 0 && _height > 0)
            {
                if (_bitmap == null || _bitmap.Width != _width || _bitmap.Height != _height)
                {
                    _bitmap = new WriteableBitmap(_width, _height, 96, 96, PixelFormats.Pbgra32, null);
                }

                _bitmap.Lock();
                using (var surface = SKSurface.Create(_width, _height, SKImageInfo.PlatformColorType, SKAlphaType.Premul, _bitmap.BackBuffer, _bitmap.BackBufferStride))
                {
                    var canvas = surface.Canvas;
                    canvas.Scale((float)_dpiX, (float)_dpiY);
                    canvas.Clear();
                    using (new SKAutoCanvasRestore(canvas, true))
                    {
                        Presenter.Render(canvas, Renderer, Container, _offsetX, _offsetY);
                    }
                }
                _bitmap.AddDirtyRect(new Int32Rect(0, 0, _width, _height));
                _bitmap.Unlock();

                drawingContext.DrawImage(_bitmap, new Rect(0, 0, _actualWidth, _actualHeight));
            }
        }
示例#4
0
文件: BandStrapp.cs 项目: jehy/unBand
        internal void SetIcon(string fileName)
        {
            var bitmapSource = new BitmapImage();

            bitmapSource.BeginInit();
            bitmapSource.UriSource = new Uri(fileName);

            // ensure that we resize to the correct dimensions
            bitmapSource.DecodePixelHeight = 46;
            bitmapSource.DecodePixelWidth  = 46;

            bitmapSource.EndInit();

            var pbgra32Image = new FormatConvertedBitmap(bitmapSource, System.Windows.Media.PixelFormats.Pbgra32, null, 0);

            var bmp = new System.Windows.Media.Imaging.WriteableBitmap(pbgra32Image);

            var images = new List <BandIcon>()
            {
                bmp.ToBandIcon(), bmp.ToBandIcon()
            };

            Strapp.SetImageList(Strapp.TileId, images, 0);

            _tiles.UpdateStrapp(Strapp);

            // this should refresh all bindings into the Strapp (in particular, the image)
            NotifyPropertyChanged("Strapp");
        }
示例#5
0
        void myChooser_KinectChanged(object sender, KinectChangedEventArgs e)
        {
            if (null != e.OldSensor)
            {
                //Alten Kinect deaktivieren
                if (mySensor != null)
                {
                    mySensor.Dispose();
                }
            }

            if (null != e.NewSensor)
            {
                mySensor = e.NewSensor;
                mySensor.AudioSource.Start();
                mySensor.AudioSource.BeamAngleChanged += new EventHandler<BeamAngleChangedEventArgs>(AudioSource_BeamAngleChanged);
                mySensor.AudioSource.SoundSourceAngleChanged += new EventHandler<SoundSourceAngleChangedEventArgs>(AudioSource_SoundSourceAngleChanged);
                myBitmap = new WriteableBitmap(640,480, 96.0, 96.0, PixelFormats.Pbgra32, null);
                image1.Source = myBitmap;
                try
                {
                    this.mySensor.Start();
                    SensorChooserUI.Visibility = Visibility.Hidden;
                }
                catch (IOException)
                {
                    this.mySensor = null;
                }
            }
        }
示例#6
0
 private void Init(int width, int height)
 {
   
     _bitmap = BitmapFactory.New(width, height);
     _bytes = new byte[width * height * 4];
     _dirtyRect = new Int32Rect(0, 0, width, height);
 }
示例#7
0
        void t_Completed(object sender, Microsoft.Phone.Tasks.PhotoResult e)
        {
            if (e.TaskResult == Microsoft.Phone.Tasks.TaskResult.OK)
            {
                System.Windows.Media.Imaging.WriteableBitmap wb = new System.Windows.Media.Imaging.WriteableBitmap(480, 800);
                BitmapImage bimg = new BitmapImage();
                bimg.SetSource(e.ChosenPhoto);
                Image img = new Image();
                img.Width   = 480;
                img.Height  = 800;
                img.Source  = bimg;
                img.Stretch = Stretch.UniformToFill;

                wb.Render(img, null);

                wb.Invalidate();
                using (var store = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    using (var st = new IsolatedStorageFileStream("slideshow_" + (DateTime.Now.Day.ToString() + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString() + DateTime.Now.Hour.ToString()) + ".jpg", FileMode.Create, FileAccess.Write, store))
                    {
                        System.Windows.Media.Imaging.Extensions.SaveJpeg(wb, st, 480, 800, 0, 100);
                    }
                }
                updateList();
            }
            else
            {
                MessageBox.Show("It looks like your phone is syncing; couldn't open the chooser.");
            }
        }
示例#8
0
        public static ImageTools.Image ToImage(WriteableBitmap bitmap)
        {
            bitmap.Invalidate();

            ImageTools.Image image = new ImageTools.Image(bitmap.PixelWidth, bitmap.PixelHeight);
            try
            {
                for (int y = 0; y < bitmap.PixelHeight; ++y)
                {
                    for (int x = 0; x < bitmap.PixelWidth; ++x)
                    {
                        int pixel = bitmap.Pixels[bitmap.PixelWidth * y + x];

                        byte a = (byte)((pixel >> 24) & 0xFF);

                        float aFactor = a / 255f;

                        byte r = (byte)(((pixel >> 16) & 0xFF) / aFactor);
                        byte g = (byte)(((pixel >> 8) & 0xFF) / aFactor);
                        byte b = (byte)((pixel & 0xFF) / aFactor);

                        image.SetPixel(x, y, r, g, b, a);
                    }
                }
            }
            catch (System.Security.SecurityException e)
            {
                throw new ArgumentException("Bitmap cannot accessed", e);
            }

            return image;
        }
示例#9
0
        public WriteableBitmap bmpFromColorFrame(ColorImageFrame NewFrame, bool SkeletonWanted, SkeletonFrame SkelFrame)
        {
            if (bmpColor == null)
            {
                bmpColor = new WriteableBitmap(frameWidth, frameHeight, 96, 96, PixelFormats.Bgr32, null);
            }

            if (NewFrame == null)
            {
                throw new InvalidOperationException("Null Image");
            }

            NewFrame.CopyPixelDataTo(colorPixels);
            // Write the pixel data into our bitmap
            bmpColor.WritePixels(
            new Int32Rect(0, 0, bmpColor.PixelWidth, bmpColor.PixelHeight),
                colorPixels,
                bmpColor.PixelWidth * sizeof(int),
                0);
            //Skeleton
            if (SkeletonWanted != false && SkelFrame != null)
            {
                return bmpWithSkelFromColor(bmpColor, SkelFrame);
            }
            return bmpColor;
        }
        private void btnSalvar_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                string _tmpImage = "tmpImage";
                string _msgMensagem = "Imagem grava com sucesso!";

                var store = IsolatedStorageFile.GetUserStoreForApplication();
                if (store.FileExists(_tmpImage)) store.DeleteFile(_tmpImage);

                IsolatedStorageFileStream _stream = store.CreateFile(_tmpImage);
                WriteableBitmap _writeImage = new WriteableBitmap(_imagetmp);

                Extensions.SaveJpeg(_writeImage, _stream, _writeImage.PixelWidth,
                    _writeImage.PixelHeight, 0, 100);
                _stream.Close();
                _stream = store.OpenFile(_tmpImage, System.IO.FileMode.Open,
                    System.IO.FileAccess.Read);

                MediaLibrary _mlibrary = new MediaLibrary();
                _mlibrary.SavePicture(_stream.Name, _stream);
                _stream.Close();

                btnSalvar.IsEnabled = false;
                lblStatus.Text = _msgMensagem;
            }
            catch (Exception error)
            {
                lblStatus.Text = error.Message;
            }
        }
        private string SaveBitmap()
        {
            System.Windows.Media.Matrix m = PresentationSource.FromVisual(this).CompositionTarget.TransformToDevice;
            Double dpiX = m.M11 * 96;
            Double dpiY = m.M22 * 96;
            //200*12
            //7*60
            int width  = GetFitBMPWidth();
            int height = GetFitBMPHeight();
            var wb     = new System.Windows.Media.Imaging.WriteableBitmap(width, height, dpiX, dpiY,
                                                                          PixelFormats.Pbgra32, null);

            wb.Lock();
            var bmp = new System.Drawing.Bitmap(wb.PixelWidth, wb.PixelHeight,
                                                wb.BackBufferStride,
                                                System.Drawing.Imaging.PixelFormat.Format32bppPArgb,
                                                wb.BackBuffer);

            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bmp); // Good old Graphics
            DrawEverything(g);
            //g.DrawLine( ... ); // etc...

            // ...and finally:
            g.Dispose();
            string temp  = System.Environment.GetEnvironmentVariable("TEMP");
            string sFile = temp + "\\snapshot.png";

            bmp.Save(sFile);
            bmp.Dispose();

            //wb.AddDirtyRect( ... );
            wb.Unlock();
            return(sFile);
        }
示例#12
0
        public void Create(int width, int height, PixelFormat pixelFormat)
        {
            swm.PixelFormat format;
            switch (pixelFormat)
            {
            /*case PixelFormat.Format16bppRgb555:
             *      format = swm.PixelFormats.Bgr555;
             *      break;*/
            case PixelFormat.Format24bppRgb:
                format = swm.PixelFormats.Bgr24;
                break;

            case PixelFormat.Format32bppRgb:
                format = swm.PixelFormats.Bgr32;
                break;

            case PixelFormat.Format32bppRgba:
                format = swm.PixelFormats.Bgra32;
                break;

            default:
                throw new NotSupportedException();
            }
            var bf = new swmi.WriteableBitmap(width, height, 96, 96, format, null);

            Control = bf;
        }
示例#13
0
 /// <summary>
 /// Получить тестовое незаполненное изображение
 /// </summary>
 /// <returns>Изображение, состоящее из 25 пикселей, 16 из которых белые и 9 черных (сетка, между ячейками черные полосы в 1 пиксель)</returns>
 private WriteableBitmap GetTestPatternImage()
 {
     WriteableBitmap result = new WriteableBitmap(5,5,96,96,PixelFormats.Bgra32, new BitmapPalette(this.testColors));
     int stride = 20;
     byte[] firstLine =
     {
         255, 255, 255, 255,
         255, 255, 255, 255,
         0, 0, 0, 255,
         255, 255, 255, 255,
         255, 255, 255, 255,
     };
     byte[] middleLine =
     {
         0,0,0, 255,
         0,0,0, 255,
         0, 0, 0, 255,
         0,0,0, 255,
         0,0,0, 255,
     };
     byte[] imageBytes = new byte[25 * 4];
     Array.Copy(firstLine, 0, imageBytes, 0, stride);
     Array.Copy(firstLine, 0, imageBytes, stride, stride);
     Array.Copy(middleLine, 0, imageBytes, stride * 2, stride);
     Array.Copy(firstLine, 0, imageBytes, stride * 3, stride);
     Array.Copy(firstLine, 0, imageBytes, stride * 4, stride);
     result.WritePixels(new Int32Rect(0,0,5,5), imageBytes,stride,0);
     return result;
 }
        /// <summary>
        /// Converts a color frame to a System.Media.Imaging.BitmapSource.
        /// </summary>
        /// <param name="frame">The specified color frame.</param>
        /// <returns>The specified frame in a System.Media.Imaging.BitmapSource representation of the color frame.</returns>
        public static BitmapSource ToBitmap(this ColorFrame frame)
        {
            if (_bitmap == null)
            {
                _width = frame.FrameDescription.Width;
                _height = frame.FrameDescription.Height;
                _pixels = new byte[_width * _height * Constants.BYTES_PER_PIXEL];
                _bitmap = new WriteableBitmap(_width, _height, Constants.DPI, Constants.DPI, Constants.FORMAT, null);
            }

            if (frame.RawColorImageFormat == ColorImageFormat.Bgra)
            {
                frame.CopyRawFrameDataToArray(_pixels);
            }
            else
            {
                frame.CopyConvertedFrameDataToArray(_pixels, ColorImageFormat.Bgra);
            }

            _bitmap.Lock();

            Marshal.Copy(_pixels, 0, _bitmap.BackBuffer, _pixels.Length);
            _bitmap.AddDirtyRect(new Int32Rect(0, 0, _width, _height));

            _bitmap.Unlock();

            return _bitmap;
        }
示例#15
0
        // Make a grey image
        public WriteableBitmap GreyEffect(WriteableBitmap image)
        {
            WriteableBitmap result = new WriteableBitmap(image.PixelWidth, image.PixelHeight);
            int[] ARGBPx = image.Pixels;

            for (int pixelIndex = 0; pixelIndex < ARGBPx.Length; pixelIndex++)
            {
                int color = ARGBPx[pixelIndex];
                int gray = 0;
                // Retrieve A, R, G, B colors
                int a = color >> 24;
                int r = (color & 0x00ff0000) >> 16;
                int g = (color & 0x0000ff00) >> 8;
                int b = (color & 0x000000ff);

                if ((r == g) && (g == b))
                {
                    gray = color;
                }
                else
                {
                    // Calculate for the illumination.
                    int i = (7 * r + 38 * g + 19 * b + 32) >> 6;
                    gray = ((a & 0xFF) << 24) | ((i & 0xFF) << 16) | ((i & 0xFF) << 8) | (i & 0xFF);
                }

                // Set result color
                ARGBPx[pixelIndex] = gray;
            }
            // Return resulted image
            ARGBPx.CopyTo(result.Pixels, 0);
            return result;
        }
示例#16
0
		public CaptureImageCompletedEventArgs (WriteableBitmap image)
			: base (null, false, null)
		{
			// Note: When this is implemented a native peer will have to be created.
			Console.WriteLine ("NIEX: System.Windows.Media.CaptureImageCompletedEventArgs:.ctor");
			throw new NotImplementedException ();
		}
        public void Update(ImageFrameReadyEventArgs e)
        {
            if (depthFrame32 == null)
            {
                depthFrame32 = new byte[e.ImageFrame.Image.Width * e.ImageFrame.Image.Height * 4];
            }

            ConvertDepthFrame(e.ImageFrame.Image.Bits);

            if (DepthBitmap == null)
            {
                DepthBitmap = new WriteableBitmap(e.ImageFrame.Image.Width, e.ImageFrame.Image.Height, 96, 96, PixelFormats.Bgra32, null);
            }

            DepthBitmap.Lock();

            int stride = DepthBitmap.PixelWidth * DepthBitmap.Format.BitsPerPixel / 8;
            Int32Rect dirtyRect = new Int32Rect(0, 0, DepthBitmap.PixelWidth, DepthBitmap.PixelHeight);
            DepthBitmap.WritePixels(dirtyRect, depthFrame32, stride, 0);

            DepthBitmap.AddDirtyRect(dirtyRect);
            DepthBitmap.Unlock();

            RaisePropertyChanged(()=>DepthBitmap);
        }
示例#18
0
        private void plotButton_click(object sender, RoutedEventArgs e)
        {
            if (graphBitmap == null)
            {
                graphBitmap = new WriteableBitmap(pixelWidth, pixelHeight, dpiX, dpiY, PixelFormats.Gray8, null);
            }
            Action doPlotButtonWorkAction = new Action(doPlotButtonWork);
            doPlotButtonWorkAction.BeginInvoke(null, null);
            #region 注释掉的内容
            //int byetePerPixel = (graphBitmap.Format.BitsPerPixel + 7) / 8;
            //int stride = byetePerPixel * graphBitmap.PixelWidth;
            //int dataSize = stride * graphBitmap.PixelHeight;
            //byte[] data = new byte[dataSize];

            //Stopwatch watch = new Stopwatch();

            ////generateGraphData(data);
            ////新建线程
            //Task first = Task.Factory.StartNew(()=>generateGraphData(data,0,pixelWidth/8));
            //Task second = Task.Factory.StartNew(() => generateGraphData(data, pixelWidth / 8, pixelWidth / 4));
            //Task first1 = Task.Factory.StartNew(() => generateGraphData(data, pixelWidth / 4, pixelWidth / 2));
            //Task second1 = Task.Factory.StartNew(() => generateGraphData(data, pixelWidth / 2, pixelWidth));
            //Task.WaitAll(first, second,first1,second1);
            //duration.Content = string.Format("Duration (ms):{0}", watch.ElapsedMilliseconds);
            //graphBitmap.WritePixels(new Int32Rect(0, 0, graphBitmap.PixelWidth, graphBitmap.PixelHeight), data, stride, 0);
            //graphImage.Source = graphBitmap;
            #endregion
        }
示例#19
0
        public void Create(int width, int height, PixelFormat pixelFormat)
        {
            swm.PixelFormat format;
            switch (pixelFormat)
            {
            /*case PixelFormat.Format16bppRgb555:
             *      format = swm.PixelFormats.Bgr555;
             *      break;*/
            case PixelFormat.Format24bppRgb:
                format = swm.PixelFormats.Bgr24;
                break;

            case PixelFormat.Format32bppRgb:
                format = swm.PixelFormats.Bgr32;
                break;

            case PixelFormat.Format32bppRgba:
                format = swm.PixelFormats.Pbgra32;
                break;

            default:
                throw new NotSupportedException();
            }
            ApplicationHandler.InvokeIfNecessary(() =>
            {
                var bf  = new swm.Imaging.WriteableBitmap(width, height, 96, 96, format, null);
                Control = bf;
            });
        }
示例#20
0
    protected override async void OnNavigatedTo(NavigationEventArgs e) {

      StreamResourceInfo sri = Application.GetResourceStream(new Uri("DemoImage.jpg", UriKind.Relative));
      var myBitmap = new WriteableBitmap(800, 480);
      img.ImageSource = myBitmap;

      using (var editsession = await EditingSessionFactory.CreateEditingSessionAsync(sri.Stream)) {
        // First add an antique effect 
       editsession.AddFilter(FilterFactory.CreateCartoonFilter(true));


       editsession.AddFilter(FilterFactory.CreateAntiqueFilter());
       // Then rotate the image
       editsession.AddFilter(FilterFactory.CreateFreeRotationFilter(35.0f, RotationResizeMode.FitInside));


        await editsession.RenderToBitmapAsync(myBitmap.AsBitmap());

   
      }
     
      myBitmap.Invalidate();

      base.OnNavigatedTo(e);
    }
        public WriteableBitmap Render(int[] values)
        {
            if (values.Length != this.pixels.Length)
            {
                throw new ArgumentException("Number of raw values must equal width*height");
            }

            // Convert raw values to ARGB format pixels.
            this.ConvertToPixels(values);

            // Copy pixels to frame buffer.
            var bitmap = new WriteableBitmap(   this.width,
                                                this.height,
                                                0,
                                                0,
                                                PixelFormats.Pbgra32,
                                                null);
            int widthInBytes = 4 * this.width;
            var sourceRect = new Int32Rect(0, 0, this.width, this.height);
            bitmap.WritePixels( sourceRect,
                                pixels,
                                widthInBytes,
                                0);

            return bitmap;
        }
示例#22
0
        unsafe bool Close()
        {
            CloseGroup();
            if (image != null)
            {
                Control.Close();
                var handler = (BitmapHandler)image.Handler;
                var bmp     = image.ToWpf();
                var newbmp  = new swmi.RenderTargetBitmap(bmp.PixelWidth, bmp.PixelHeight, bmp.DpiX, bmp.DpiY, swm.PixelFormats.Pbgra32);
                newbmp.RenderWithCollect(visual);
                if (!bmp.Format.HasAlpha())
                {
                    // convert to non-alpha, as RenderTargetBitmap does not support anything other than Pbgra32
                    var wb     = new swmi.WriteableBitmap(bmp.PixelWidth, bmp.PixelHeight, bmp.DpiX, bmp.DpiY, swm.PixelFormats.Bgr32, null);
                    var rect   = new sw.Int32Rect(0, 0, bmp.PixelWidth, bmp.PixelHeight);
                    var pixels = new byte[bmp.PixelHeight * wb.BackBufferStride];
                    newbmp.CopyPixels(rect, pixels, wb.BackBufferStride, 0);
                    fixed(byte *ptr = pixels)
                    {
                        wb.WritePixels(rect, (IntPtr)ptr, pixels.Length, wb.BackBufferStride, 0, 0);
                    }

                    handler.SetBitmap(wb);
                }
                else
                {
                    handler.SetBitmap(newbmp);
                }
                return(true);
            }
            return(false);
        }
        public unsafe void CreateImage(WriteableBitmap target, IntPtr pointer)
        {
            Int32Rect rectangle = default(Int32Rect);
            target.Dispatcher.Invoke(new Action(() => 
                {
                    rectangle = new Int32Rect(0, 0, target.PixelWidth, target.PixelHeight);
                }));

            byte* pImage = (byte*)pointer.ToPointer();

            var pixelCount = rectangle.Width * rectangle.Height;
            var buffer = new byte[pixelCount * 3];

            for (int index = 0; index < pixelCount; index++)
            {
                buffer[index * 3] = pImage[2];
                buffer[index * 3 + 1] = pImage[1];
                buffer[index * 3 + 2] = pImage[0];
                pImage += 3;
            }

            target.Dispatcher.Invoke(new Action(() =>
            {
                target.Lock();
                target.WritePixels(rectangle, buffer, rectangle.Width * 3, 0);
                target.Unlock();
            }));
        }
 /// <summary>
 /// Creates a new RenderTargetImageSource.
 /// </summary>
 /// <param name="graphics">The GraphicsDevice to use.</param>
 /// <param name="width">The width of the image source.</param>
 /// <param name="height">The height of the image source.</param>
 public RenderTargetImageSource(GraphicsDevice graphics, int width, int height)
 {
     // create the render target and buffer to hold the data
     renderTarget = new RenderTarget2D(graphics, width, height, false, SurfaceFormat.Color, DepthFormat.Depth24Stencil8);
     buffer = new byte[width * height * 4];
     writeableBitmap = new WriteableBitmap(width, height, 96, 96, PixelFormats.Bgra32, null);
 }
示例#25
0
 private void NewCommand(object sender, ExecutedRoutedEventArgs e)
 {
     var dlog = new NewDocument
     {
         Owner = this
     };
     var result = dlog.ShowDialog();
     if (!result.HasValue || !result.Value)
     {
         return;
     }
     var bmp = new WriteableBitmap(
         dlog.ViewModel.Width,
         dlog.ViewModel.Height,
         96,
         96,
         PixelFormats.Bgr32,
         null);
     _picture = new Picture(dlog.ViewModel.Name, bmp);
     Title = _picture.Name;
     ViewModel.Document = new ReversibleDocument<IPicture>(_picture);
     ViewModel.AccessPolicy = new PictureAccessPolicy(_picture);
     _image.Source = bmp;
     _image.Stretch = Stretch.None;
     RenderOptions.SetBitmapScalingMode(_image, BitmapScalingMode.NearestNeighbor);
     RenderOptions.SetEdgeMode(_image, EdgeMode.Aliased);
 }
示例#26
0
 void updateMyBg()
 {
     try
     {
         using (var store = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication())
         {
             using (var str = store.OpenFile("bing.jpg", FileMode.Open))
             {
                 System.Windows.Media.Imaging.WriteableBitmap wb = new System.Windows.Media.Imaging.WriteableBitmap(480, 800);
                 BitmapImage bimg = new BitmapImage();
                 bimg.SetSource(str);
                 image1.Source = bimg;
             }
         }
     }
     catch
     {
         System.Windows.Threading.DispatcherTimer tim = new System.Windows.Threading.DispatcherTimer();
         tim.Interval = TimeSpan.FromSeconds(2);
         tim.Tick    += new EventHandler((o, e) =>
         {
             updateMyBg();
             tim.Stop();
         });
         tim.Start();
     }
 }
示例#27
0
文件: Util.cs 项目: Marksys/markdice
        public static byte[] toByte(Image img)
        {
            BitmapImage bmpToArray = img.Source as BitmapImage;
            WriteableBitmap wb = new WriteableBitmap(bmpToArray);
            
            

            MemoryStream msWrite = new MemoryStream();
            wb.SaveJpeg(msWrite, 100, 100, 0, 90);
            msWrite.Seek(0, SeekOrigin.Begin);

            if (msWrite != null)
            {
                msWrite.Position = 0;
                MemoryStream ms = new MemoryStream();
                byte[] buffer = new byte[msWrite.Length];
                int read;
                while ((read = msWrite.Read(buffer, 0, buffer.Length)) > 0)
                {
                    ms.Write(buffer, 0, read);
                }

                return buffer;
            }
            return null;
        }
示例#28
0
        /// <summary>
        /// WriteableBitmap -> IplImage
        /// </summary>
        private void TestWriteableBitmap()
        {
            // Load 16-bit image to WriteableBitmap
            PngBitmapDecoder decoder = new PngBitmapDecoder(
                new Uri(FilePath.Image.Depth16Bit, UriKind.Relative),
                BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default
            );
            BitmapSource bs = decoder.Frames[0];
            WriteableBitmap wb = new WriteableBitmap(bs);

            // Convert wb into IplImage
            IplImage ipl = wb.ToIplImage();
            //IplImage ipl32 = new IplImage(wb.PixelWidth, wb.PixelHeight, BitDepth.U16, 1);
            //WriteableBitmapConverter.ToIplImage(wb, ipl32);

            // Print pixel values
            for (int i = 0; i < ipl.Height; i++)
            {
                Console.WriteLine("x:{0} y:{1} v:{2}", i, i, ipl[i, 128]);
            }

            // Show 16-bit IplImage
            using (new CvWindow("from WriteableBitmap to IplImage", ipl))
            {
                Cv.WaitKey();
            }
        }
        void GetRequestStreamCallback(IAsyncResult callbackResult)
        {
            HttpWebRequest myRequest = (HttpWebRequest)callbackResult.AsyncState;
            // End the stream request operation
            Stream postStream = myRequest.EndGetRequestStream(callbackResult);
            var settings = IsolatedStorageSettings.ApplicationSettings;
            String token ="";
            if (settings.Contains("tokken"))
            {
                token = settings["tokken"].ToString();
            }
            // Create the post data
            string postData = "tokken=" + token + "&attrId=30";

               MemoryStream ms = new MemoryStream();
            WriteableBitmap btmMap = new WriteableBitmap(photo.PixelWidth,photo.PixelHeight);

            // write an image into the stream
            Extensions.SaveJpeg(btmMap, ms,
            photo.PixelWidth, photo.PixelHeight, 0, 100);

            //this.WriteEntry(postStream, "image",ms.ToArray());
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);

            // Add the post data to the web request
            postStream.Write(byteArray, 0, byteArray.Length);
            postStream.Close();

            // Start the web request
            myRequest.BeginGetResponse(new AsyncCallback(GetResponsetStreamCallback), myRequest);
        }
示例#30
0
        public static WriteableBitmap DecodeJpeg(Stream srcStream)
        {
            // Decode JPEG
            var decoder = new FluxJpeg.Core.Decoder.JpegDecoder(srcStream);
            var jpegDecoded = decoder.Decode();
            var img = jpegDecoded.Image;
            img.ChangeColorSpace(ColorSpace.RGB);

            // Init Buffer
            int w = img.Width;
            int h = img.Height;
            var result = new WriteableBitmap(w, h);
            int[] p = result.Pixels;
            byte[][,] pixelsFromJpeg = img.Raster;

            // Copy FluxJpeg buffer into WriteableBitmap
            int i = 0;
            for (int x = 0; x < w; x++)
            {
                for (int y = 0; y < h; y++)
                {
                    p[i++] = (0xFF << 24) // A
                                | (pixelsFromJpeg[0][x, y] << 16) // R
                                | (pixelsFromJpeg[1][x, y] << 8)  // G
                                | pixelsFromJpeg[2][x, y];       // B
                }
            }

            return result;
        }
示例#31
0
 public FrameData( WriteableBitmap depth, WriteableBitmap color, double lat, double lng )
 {
     depthBitmap = depth;
     colorBitmap = color;
     latitude = lat;
     longitude = lng;
 }
        public byte[] DoCapture()
        {
            FrameworkElement toSnap = null;
            
            if (!AutomationIdIsEmpty)
                toSnap = GetFrameworkElement(false);

            if (toSnap == null)
                toSnap = AutomationElementFinder.GetRootVisual();

            if (toSnap == null)
                return null;

            // Save to bitmap
            var bmp = new WriteableBitmap((int)toSnap.ActualWidth, (int)toSnap.ActualHeight);
            bmp.Render(toSnap, null);
            bmp.Invalidate();

            // Get memoryStream from bitmap
            using (var memoryStream = new MemoryStream())
            {
                bmp.SaveJpeg(memoryStream, bmp.PixelWidth, bmp.PixelHeight, 0, 95);
                memoryStream.Seek(0, SeekOrigin.Begin);
                return memoryStream.GetBuffer();
            }
        }
示例#33
0
        void WebClientOpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            const string tempJpeg = "TempJPEG";
            var streamResourceInfo = new StreamResourceInfo(e.Result, null);

            var userStoreForApplication = IsolatedStorageFile.GetUserStoreForApplication();
            if (userStoreForApplication.FileExists(tempJpeg))
            {
                userStoreForApplication.DeleteFile(tempJpeg);
            }

            var isolatedStorageFileStream = userStoreForApplication.CreateFile(tempJpeg);

            var bitmapImage = new BitmapImage { CreateOptions = BitmapCreateOptions.None };
            bitmapImage.SetSource(streamResourceInfo.Stream);

            var writeableBitmap = new WriteableBitmap(bitmapImage);
            writeableBitmap.SaveJpeg(isolatedStorageFileStream, writeableBitmap.PixelWidth, writeableBitmap.PixelHeight, 0, 85);

            isolatedStorageFileStream.Close();
            isolatedStorageFileStream = userStoreForApplication.OpenFile(tempJpeg, FileMode.Open, FileAccess.Read);

            // Save the image to the camera roll or saved pictures album.
            var mediaLibrary = new MediaLibrary();

            // Save the image to the saved pictures album.
            mediaLibrary.SavePicture(string.Format("SavedPicture{0}.jpg", DateTime.Now), isolatedStorageFileStream);

            isolatedStorageFileStream.Close();
        }
        async void GeneratePicture()
        {
            if (rendering) return;


            ProgressIndicator prog = new ProgressIndicator();
            prog.IsIndeterminate = true;
            prog.Text = "Rendering";
            prog.IsVisible = true;
            SystemTray.SetProgressIndicator(this, prog);



            var bmp = new WriteableBitmap(480, 800);
            try
            {
                rendering = true;

             
              
                using (var renderer = new WriteableBitmapRenderer(manager, bmp, OutputOption.PreserveAspectRatio))
                {
                    display.Source = await renderer.RenderAsync();
                }

                SystemTray.SetProgressIndicator(this, null);
                rendering = false;
            }
            finally
            {
               
            }


        }
        void UpdateTiledImage() {
            if(sourceBitmap == null)
                return;

            var width = (int)Math.Ceiling(ActualWidth);
            var height = (int)Math.Ceiling(ActualHeight);

            // only regenerate the image if the width/height has grown
            if(width < lastWidth && height < lastHeight)
                return;
            lastWidth = width;
            lastHeight = height;

            var final = new WriteableBitmap(width, height);

            for(var x = 0; x < final.PixelWidth; x++) {
                for(var y = 0; y < final.PixelHeight; y++) {
                    var tiledX = (x % sourceBitmap.PixelWidth);
                    var tiledY = (y % sourceBitmap.PixelHeight);
                    final.Pixels[y * final.PixelWidth + x] = sourceBitmap.Pixels[tiledY * sourceBitmap.PixelWidth + tiledX];
                }
            }

            tiledImage.Source = final;
        }
示例#36
0
        public RecordedVideoFrame(ColorImageFrame colorFrame)
        {
            if (colorFrame != null)
            {
                byte[] bits = new byte[colorFrame.PixelDataLength];
                colorFrame.CopyPixelDataTo(bits);

                int BytesPerPixel = colorFrame.BytesPerPixel;
                int Width = colorFrame.Width;
                int Height = colorFrame.Height;

                var bmp = new WriteableBitmap(Width, Height, 96, 96, PixelFormats.Bgr32, null);
                bmp.WritePixels(new System.Windows.Int32Rect(0, 0, Width, Height), bits, Width * BytesPerPixel, 0);
                JpegBitmapEncoder jpeg = new JpegBitmapEncoder();
                jpeg.Frames.Add(BitmapFrame.Create(bmp));
                var SaveStream = new MemoryStream();
                jpeg.Save(SaveStream);
                SaveStream.Flush();
                JpegData = SaveStream.ToArray();
            }
            else
            {
                return;
            }
        }
        Stream GetPngStream(WriteableBitmap bmp)
        {
            // Use Joe Stegman's PNG Encoder
            // http://bit.ly/77mDsv
            EditableImage imageData = new EditableImage(bmp.PixelWidth, bmp.PixelHeight);

            for (int y = 0; y < bmp.PixelHeight; ++y)
            {
                for (int x = 0; x < bmp.PixelWidth; ++x)
                {

                    int pixel = bmp.Pixels[bmp.PixelWidth * y + x];

                    imageData.SetPixel(x, y,
                                (byte)((pixel >> 16) & 0xFF),
                                (byte)((pixel >> 8) & 0xFF),
                                (byte)(pixel & 0xFF),
                                (byte)((pixel >> 24) & 0xFF)
                                );

                }
            }

            return imageData.GetStream();
        }
示例#38
0
        private void PreparePopups()
        {
            if (theHelpPopup == null)
            {
                theHelpPopup                  = new Popup();
                theHelpPopup.Child            = new HelpPopup();
                theHelpPopup.VerticalOffset   = 200;
                theHelpPopup.HorizontalOffset = 0;
                theHelpPopup.Closed          += (sender1, e1) =>
                {
                    this.ApplicationBar.IsVisible = true;
                };
            }
            if (theSavePopup == null)
            {
                theSavePopup                  = new Popup();
                theSavePopup.Child            = new HelpSavePopup();
                theSavePopup.VerticalOffset   = 70;
                theSavePopup.HorizontalOffset = 0;
                theSavePopup.Closed          += (sender1, e1) =>
                {
                    try
                    {
                        if (!backButtonPressedFlag)
                        {
                            var bitmap = new System.Windows.Media.Imaging.WriteableBitmap(this.LayoutRoot, null);
                            using (var stream = new System.IO.MemoryStream())
                            {
                                System.Windows.Media.Imaging.Extensions.SaveJpeg(bitmap, stream,
                                                                                 bitmap.PixelWidth, bitmap.PixelHeight, 0, 100);
                                stream.Position = 0;
                                var mediaLib = new Microsoft.Xna.Framework.Media.MediaLibrary();
                                var datetime = System.DateTime.Now;
                                var filename =
                                    System.String.Format("LockScreen-{0}-{1}-{2}-{3}-{4}",
                                                         datetime.Year % 100, datetime.Month, datetime.Day,
                                                         datetime.Hour, datetime.Minute);
                                mediaLib.SavePicture(filename, stream);

                                var toast = new ToastPrompt
                                {
                                    Title   = "Saved",
                                    Message = @"Your wallpaper is in ""Saved Pictures"""
                                };
                                toast.Show();
                            }
                        }
                        backButtonPressedFlag = false;
                    }
                    finally
                    {
                        UpdateMockup(false);
                    }
                };
            }
        }
示例#39
0
        private WriteableBitmap WriteableBitmapBitmapFromBitmap(Bitmap writeBmp)
        {
            BitmapSource bitmapSource =
                System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(writeBmp.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty,
                                                                             System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());

            WriteableBitmap writeableBitmap = new System.Windows.Media.Imaging.WriteableBitmap(bitmapSource);

            return(writeableBitmap);
        }
示例#40
0
        public BitmapData Lock()
        {
            var wb = Control as swmi.WriteableBitmap;

            if (wb == null || RequiresFrozen)
            {
                wb = new swmi.WriteableBitmap(FrozenControl);
                SetBitmap(wb);
            }
            wb.Lock();
            return(new BitmapDataHandler(Widget, wb.BackBuffer, wb.BackBufferStride, wb.Format.BitsPerPixel, wb, wb.Format.IsPremultiplied()));
        }
示例#41
0
        public static BitmapSource ToBitmapSource(this System.Drawing.Bitmap bmp)
        {
            var rect       = new System.Drawing.Rectangle(0, 0, bmp.Width, bmp.Height);
            var bmpData    = bmp.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite, System.Drawing.Imaging.PixelFormat.Format32bppRgb);
            int bufferSize = bmpData.Stride * bmp.Height;
            var bms        = new System.Windows.Media.Imaging.WriteableBitmap(bmp.Width, bmp.Height, bmp.HorizontalResolution, bmp.VerticalResolution, PixelFormats.Bgr32, null);

            bms.WritePixels(new Int32Rect(0, 0, bmp.Width, bmp.Height), bmpData.Scan0, bufferSize, bmpData.Stride);
            bmp.UnlockBits(bmpData);

            return(bms);
        }
示例#42
0
        public static void setPixel(this System.Windows.Media.Imaging.WriteableBitmap wbm, int x, int y, System.Windows.Media.Color c)
        {
            if (y > wbm.PixelHeight - 1 || x > wbm.PixelWidth - 1)
            {
                return;
            }

            if (y < 0 || x < 0)
            {
                return;
            }

            wbm.Pixels[y * wbm.PixelWidth + x] = c.A << 24 | c.R << 16 | c.G << 8 | c.B;
        }
示例#43
0
        public void LoadImageWPF(string filePath)
        {
            filePath = System.IO.Path.Combine(TestContext.CurrentContext.TestDirectory, filePath);

            var uri = new Uri(filePath, UriKind.Absolute);

            var image = new System.Windows.Media.Imaging.BitmapImage(uri);

            var memory = image.ToMemoryBitmap();

            memory.Save(AttachmentInfo.From("Result.png"));

            var writable = new System.Windows.Media.Imaging.WriteableBitmap(image);
        }
示例#44
0
        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            var photoBase64 = string.Empty;

            var wbmp = new System.Windows.Media.Imaging.WriteableBitmap((System.Windows.Media.Imaging.BitmapSource)value);

            //this.photo.Source
            using (var ms = new System.IO.MemoryStream())
            {
                wbmp.SaveJpeg(ms, 640, 480, 0, 60);

                return(System.Convert.ToBase64String(ms.ToArray()));
            }
        }
示例#45
0
 public BitmapData Lock()
 {
     return(ApplicationHandler.InvokeIfNecessary(() =>
     {
         var wb = Control as swmi.WriteableBitmap;
         if (wb == null)
         {
             wb = new swmi.WriteableBitmap(Control);
             SetBitmap(wb);
         }
         wb.Lock();
         return new BitmapDataHandler(Widget, wb.BackBuffer, Stride, Control.Format.BitsPerPixel, wb);
     }));
 }
示例#46
0
        public override WriteableBitmap ApplyFunctionFilter(System.Windows.Media.Imaging.BitmapImage originalBitmapImage)
        {
            WriteableBitmap writableImage = new System.Windows.Media.Imaging.WriteableBitmap(originalBitmapImage);

            byte[] byteArr = writableImage.WriteableBitMapImageToArray();

            for (int i = 0; i < byteArr.Length; i++)
            {
                byteArr[i] = (byte)(255 - byteArr[i]);
            }

            WriteableBitmap result = originalBitmapImage.ByteArrayToWritableBitmap(byteArr);

            return(result);
        }
示例#47
0
        public static System.Windows.Media.Color getPixel(this System.Windows.Media.Imaging.WriteableBitmap wbm, int x, int y)
        {
            if (y > wbm.PixelHeight - 1 || x > wbm.PixelWidth - 1)
            {
                return(System.Windows.Media.Color.FromArgb(0, 0, 0, 0));
            }

            if (y < 0 || x < 0)
            {
                return(System.Windows.Media.Color.FromArgb(0, 0, 0, 0));
            }

            byte[] ARGB = BitConverter.GetBytes(wbm.Pixels[y * wbm.PixelWidth + x]);

            return(System.Windows.Media.Color.FromArgb(ARGB[3], ARGB[2], ARGB[1], ARGB[0]));
        }
示例#48
0
 public Bitmap Clone(Rectangle?rectangle = null)
 {
     if (rectangle != null)
     {
         var rect = rectangle.Value;
         var data = new byte[Stride * Control.PixelHeight];
         FrozenControl.CopyPixels(data, Stride, 0);
         var target = new swmi.WriteableBitmap(rect.Width, rect.Height, Control.DpiX, Control.DpiY, Control.Format, Control.Palette);
         target.WritePixels(rect.ToWpfInt32(), data, Stride, destinationX: 0, destinationY: 0);
         return(new Bitmap(new BitmapHandler(target)));
     }
     else
     {
         return(new Bitmap(new BitmapHandler(FrozenControl.Clone())));
     }
 }
示例#49
0
        /// <summary>
        /// Draw outline on image
        /// </summary>
        /// <param name="strategy">is text strategy</param>
        /// <param name="image">is the image to be draw upon</param>
        /// <param name="offset">offsets the text (typically used for shadows)</param>
        /// <param name="textContext">is text context</param>
        /// <returns>true if successful</returns>
        public static bool DrawTextImage(
            ITextStrategy strategy,
            ref System.Windows.Media.Imaging.WriteableBitmap image,
            System.Windows.Point offset,
            TextContext textContext,
            System.Windows.Media.Matrix mat)
        {
            if (strategy == null || image == null || textContext == null)
            {
                return(false);
            }

            RenderTargetBitmap bmp = new RenderTargetBitmap((int)(image.Width), (int)(image.Height), 96, 96, PixelFormats.Pbgra32);

            DrawingVisual drawingVisual = new DrawingVisual();

            DrawingContext drawingContext = drawingVisual.RenderOpen();

            MatrixTransform mat_trans = new MatrixTransform();

            mat_trans.Matrix = mat;

            drawingContext.PushTransform(mat_trans);

            drawingContext.DrawImage(image, new Rect(0.0, 0.0, image.Width, image.Height));

            bool bRet = strategy.DrawString(drawingContext,
                                            textContext.fontFamily,
                                            textContext.fontStyle,
                                            textContext.fontWeight,
                                            textContext.nfontSize,
                                            textContext.pszText,
                                            new System.Windows.Point(textContext.ptDraw.X + offset.X, textContext.ptDraw.Y + offset.Y),
                                            textContext.ci);

            drawingContext.Pop();

            drawingContext.Close();

            bmp.Render(drawingVisual);

            image = new System.Windows.Media.Imaging.WriteableBitmap(bmp);

            return(bRet);
        }
        /*
         * private void btn_DoubleTap(object sender, System.Windows.Input.GestureEventArgs e)
         * {
         *      Button btn;
         *      btn = ((Button) sender);
         *      RscMediaLibItemDesc it;
         *      it = (RscMediaLibItemDesc) btn.Tag;
         *
         *      if( it.bFolder )
         *      {
         *              //m_path.Push( it.sFn );
         *
         *              //ListFiles();
         *      }
         *      else
         *      {
         *              //m_txtTitle.Text = "medlib:\\" + it.sFolderPath + "\\" + it.sName;
         *
         *              m_btnImage.Visibility = Rsc.Visible;
         *              m_btnImage.Tag = it.sIndiciesToItem;
         *              m_btnImage.Image.Source = LoadImage( it, false, 96, 160 );
         *      }
         * }
         */

        private ImageSource LoadImage(RscMediaLibItemDesc it, bool bThumbnail, int iCX, int iCY)
        {
            if (it.bFolder)
            {
                return(m_AppFrame.Theme.GetImage("Images/Ico001_Ressive.jpg"));
            }

            // //
            //

            PictureAlbum pa  = m_media.RootPictureAlbum;
            Picture      pic = null;

            string [] asInd = it.sIndiciesToItem.Split('|');
            int       iCnt  = asInd.Length;

            for (int i = 0; i < iCnt; i++)
            {
                if (i == iCnt - 1)
                {
                    pic = pa.Pictures[Int32.Parse(asInd[i])];
                }
                else
                {
                    pa = pa.Albums[Int32.Parse(asInd[i])];
                }
            }

            //
            // //

            if (bThumbnail)
            {
                System.Windows.Media.Imaging.WriteableBitmap wbmp =
                    Microsoft.Phone.PictureDecoder.DecodeJpeg(pic.GetThumbnail(), iCX, iCY);

                return(wbmp);
            }
            else
            {
                BitmapImage bmp = new BitmapImage();
                bmp.SetSource(pic.GetImage());
                return(bmp);
            }
        }
 public bool IfNewSizeResizeAndDraw(int width, int height)
 {
     if (m_wpfBitmap == null ||
         m_wpfBitmap.PixelHeight != height ||
         m_wpfBitmap.PixelWidth != width)
     {
         Reset();
         // Can't dispose wpf
         const double Dpi = 96;
         m_wpfBitmap = new SWMI.WriteableBitmap(width, height, Dpi, Dpi,
                                                SWM.PixelFormats.Bgr24, null);
         var ptr = m_wpfBitmap.BackBuffer;
         m_gdiBitmap = new Bitmap(width, height, m_wpfBitmap.BackBufferStride,
                                  System.Drawing.Imaging.PixelFormat.Format24bppRgb, ptr);
         Draw();
         return(true);
     }
     return(false);
 }
示例#52
0
        public BitmapData Lock()
        {
            BitmapDataHandler handler = null;

            ApplicationHandler.InvokeIfNecessary(() => {
                var wb = Control as swm.Imaging.WriteableBitmap;
                if (wb != null)
                {
                    wb.Lock();
                    handler = new BitmapDataHandler(Widget, wb.BackBuffer, (int)stride, Control.Format.BitsPerPixel, Control);
                }
                else
                {
                    wb = new swm.Imaging.WriteableBitmap(Control);
                    wb.Lock();
                    Control = wb;
                    handler = new BitmapDataHandler(Widget, wb.BackBuffer, (int)stride, Control.Format.BitsPerPixel, wb);
                }
            });
            return(handler);
        }
示例#53
0
        public override WriteableBitmap ApplyFunctionFilter(System.Windows.Media.Imaging.BitmapImage originalBitmapImage)
        {
            WriteableBitmap writableImage = new System.Windows.Media.Imaging.WriteableBitmap(originalBitmapImage);

            byte[] byteArr = writableImage.WriteableBitMapImageToArray();

            int num = 0;

            for (int i = 0; i < byteArr.Length; i++)
            {
                num = (int)(byteArr[i]);
                int val = (int)_customFunction[num] + (int)this.Offset;
                val        = (val < 0 ? 0 : val);
                val        = (val > 255 ? 255 : val);
                byteArr[i] = (byte)(val);
            }

            WriteableBitmap result = originalBitmapImage.ByteArrayToWritableBitmap(byteArr);

            return(result);
        }
示例#54
0
        public Bitmap Clone(Rectangle?rectangle = null)
        {
            swmi.BitmapSource clone = null;
            ApplicationHandler.InvokeIfNecessary(() =>
            {
                if (rectangle != null)
                {
                    var rect = rectangle.Value;
                    var data = new byte[Stride * Control.PixelHeight];
                    Control.CopyPixels(data, Stride, 0);
                    var target = new swmi.WriteableBitmap(rect.Width, rect.Height, Control.DpiX, Control.DpiY, Control.Format, null);
                    target.WritePixels(rect.ToWpfInt32(), data, Stride, destinationX: 0, destinationY: 0);
                    clone = target;
                }
                else
                {
                    clone = Control.Clone();
                }
            });

            return(new Bitmap(Generator, new BitmapHandler(clone)));
        }
示例#55
0
        /*
         * public override byte[] Function {
         *  get {
         *      byte[] function = new byte[256];
         *
         *      int num = 0;
         *
         *      int subvalues = 4;
         *      int length = 256 / subvalues;
         *      for (int i = 0; i * subvalues < length; i += subvalues) {
         *
         *          int grayScalePx = (int)((i * .299) + ((i + 1) * .587) + ((i + 2) * .114));
         *
         *          if (grayScalePx < this.Offset)
         *              num = 0;
         *          else
         *              num = 255;
         *
         *          for (int j = i; j < (i + subvalues); j++) {
         *              function[j] = (byte)num;
         *          }
         *      }
         *
         *      _function = function;
         *      return _function;
         *  }
         *  set {
         *      base.Function = value;
         *  }
         * }
         */

        public override WriteableBitmap ApplyFunctionFilter(System.Windows.Media.Imaging.BitmapImage originalBitmapImage)
        {
            WriteableBitmap writableImage = new System.Windows.Media.Imaging.WriteableBitmap(originalBitmapImage);

            byte[] byteArr = writableImage.WriteableBitMapImageToArray();

            for (int i = 0; i < byteArr.Length; i += 4)
            {
                byte a = byteArr[i + 3];

                if (a > 0)
                {
                    double ad = (double)a / 255.0;
                    double rd = (double)byteArr[i + 2] / ad;
                    double gd = (double)byteArr[i + 1] / ad;
                    double bd = (double)byteArr[i + 0] / ad;

                    double luminance = 0.2126 * rd + 0.7152 * gd + 0.0722 * bd;
                    double newR      = luminance * ad;

                    if (newR < this.Offset)
                    {
                        newR = 0;
                    }
                    else
                    {
                        newR = 255;
                    }

                    byteArr[i + 0] = (byte)newR;
                    byteArr[i + 1] = (byte)newR;
                    byteArr[i + 2] = (byte)newR;
                }
            }

            WriteableBitmap result = originalBitmapImage.ByteArrayToWritableBitmap(byteArr);

            return(result);
        }
 internal void CreateCameraViewWpfBitmapSource()
 {
     try
     {
         var capture = Device.CameraViewImageSourceBitmapCapture;
         var width   = capture.CameraViewImageSourceBitmapSize.Width;
         var height  = capture.CameraViewImageSourceBitmapSize.Height;
         Debug.Assert(width > 0 && height > 0);
         CameraViewWpfBitmapSource       = new System.Windows.Media.Imaging.WriteableBitmap(width, height, 96, 96, System.Windows.Media.PixelFormats.Bgr24, null);
         CameraViewWpfBitmapSourceWidth  = width;
         CameraViewWpfBitmapSourceHeight = height;
         CameraViewWpfBitmapSourceWritePixelsSourceRect = new System.Windows.Int32Rect(0, 0, width, height);
     }
     catch (Exception ex)
     {
         if (ApplicationCommonSettings.IsDebugging)
         {
             Debugger.Break();
         }
         Debug.WriteLine(ex.Message);
     }
 }
示例#57
0
        private async void addPhoto(bool takeNew)
        {
            //Capture photo file from view
            var picker  = new Xamarin.Media.MediaPicker();
            var options = new Xamarin.Media.StoreCameraMediaOptions();

            var       mediaFileSource = this.GetService <Core.Interfaces.IMediaFileSource>();
            MediaFile mediaFile       = null;

            try { mediaFile = await mediaFileSource.GetPhoto(takeNew); }
            catch { }

            if (mediaFile != null && !string.IsNullOrEmpty(mediaFile.Path))
            {
                this.Dispatcher.BeginInvoke(() =>
                {
                    this.Photo = new System.Windows.Media.Imaging.BitmapImage();
                    this.Photo.SetSource(mediaFile.GetStream());


                    var photoBase64 = string.Empty;
                    var wbmp        = new System.Windows.Media.Imaging.WriteableBitmap(this.Photo);

                    using (var ms = new System.IO.MemoryStream())
                    {
                        wbmp.SaveJpeg(ms, 640, 480, 0, 60);
                        photoBase64 = Convert.ToBase64String(ms.ToArray());
                    }

                    this.ViewModel.AddPhoto(photoBase64);

                    //Clean up!
                    mediaFile.Dispose();
                });
            }
        }
示例#58
0
        private void PrintDepthOnCanvas(short[] imageArray, Image canvas, int width, int height, int max)
        {
            try
            {
                System.Windows.Media.Imaging.WriteableBitmap colorBitmap = new System.Windows.Media.Imaging.WriteableBitmap(width, height, 96.0, 96.0, System.Windows.Media.PixelFormats.Bgr32, null);

                byte[] pixels      = new byte[imageArray.Length * 4];
                int    pixelsIndex = 0;
                for (int i = 0; i < imageArray.Length; i++)
                {
                    float relativeDepth    = Convert.ToInt16(imageArray[i]) / (float)max;
                    System.Drawing.Color c = RelativeDepthToColor(relativeDepth);

                    pixels[pixelsIndex++] = c.B;
                    pixels[pixelsIndex++] = c.G;
                    pixels[pixelsIndex++] = c.R;
                    pixels[pixelsIndex++] = c.A;
                }

                colorBitmap.WritePixels(
                    new System.Windows.Int32Rect(0, 0, width, height),
                    pixels,
                    width * sizeof(int),
                    0);
                colorBitmap.Freeze();

                canvas.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, (ThreadStart) delegate()
                {
                    canvas.Source = colorBitmap;
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
示例#59
0
        /// <summary>
        /// Apply shadow to mask onto the canvas
        /// </summary>
        /// <param name="clrShadow">is the color to be used</param>
        /// <param name="mask">is the mask image to be read</param>
        /// <param name="canvas">is the destination image to be draw upon</param>
        /// <param name="maskColor">is mask color used in mask image</param>
        /// <param name="offset">determine how much to offset the mask</param>
        /// <returns>true if successful</returns>
        public static bool ApplyShadowToMask(
            System.Windows.Media.Color clrShadow,
            System.Windows.Media.Imaging.WriteableBitmap mask,
            System.Windows.Media.Imaging.WriteableBitmap canvas,
            System.Windows.Media.Color maskColor,
            System.Windows.Point offset)
        {
            if (mask == null || canvas == null)
            {
                return(false);
            }


            mask.Lock();

            canvas.Lock();

            unsafe
            {
                uint *pixelsMask   = (uint *)mask.BackBuffer;
                uint *pixelsCanvas = (uint *)canvas.BackBuffer;

                if (pixelsMask == null || pixelsCanvas == null)
                {
                    return(false);
                }

                uint col    = 0;
                int  stride = canvas.BackBufferStride >> 2;
                for (int row = 0; row < canvas.Height; ++row)
                {
                    uint total_row_len      = (uint)(row * stride);
                    uint total_row_mask_len = (uint)((row - (int)offset.Y) * (mask.BackBufferStride >> 2));
                    for (col = 0; col < canvas.Width; ++col)
                    {
                        if (row - (int)offset.Y >= mask.Height || col - (int)offset.X >= mask.Width ||
                            row - (int)offset.Y < 0 || col - (int)offset.X < 0)
                        {
                            continue;
                        }

                        uint index     = total_row_len + col;
                        uint indexMask = (uint)(total_row_mask_len + (col - (int)offset.X));

                        byte maskByte = 0;

                        if (MaskColor.IsEqual(maskColor, MaskColor.Red))
                        {
                            maskByte = (Byte)((pixelsMask[indexMask] & 0xff0000) >> 16);
                        }
                        else if (MaskColor.IsEqual(maskColor, MaskColor.Green))
                        {
                            maskByte = (Byte)((pixelsMask[indexMask] & 0xff00) >> 8);
                        }
                        else if (MaskColor.IsEqual(maskColor, MaskColor.Blue))
                        {
                            maskByte = (Byte)(pixelsMask[indexMask] & 0xff);
                        }

                        uint color = (uint)(0xff << 24 | clrShadow.R << 16 | clrShadow.G << 8 | clrShadow.B);

                        if (maskByte > 0)
                        {
                            uint maskAlpha = (pixelsMask[indexMask] >> 24);
                            pixelsCanvas[index] = Alphablend(pixelsCanvas[index], color, (Byte)(maskAlpha), (Byte)(maskAlpha * clrShadow.A / 255));
                        }
                    }
                }
            }
            canvas.Unlock();
            mask.Unlock();

            return(true);
        }
示例#60
0
        /// <summary>
        /// Apply image to mask onto the canvas
        /// </summary>
        /// <param name="image">is the image to be used</param>
        /// <param name="mask">is the mask image to be read</param>
        /// <param name="canvas">is the destination image to be draw upon</param>
        /// <param name="maskColor">is mask color used in mask image</param>
        /// <returns>true if successful</returns>
        public static bool ApplyImageToMask(
            System.Windows.Media.Imaging.WriteableBitmap image,
            System.Windows.Media.Imaging.WriteableBitmap mask,
            System.Windows.Media.Imaging.WriteableBitmap canvas,
            System.Windows.Media.Color maskColor,
            bool NoAlphaAtBoundary)
        {
            if (image == null || mask == null || canvas == null)
            {
                return(false);
            }

            image.Lock();

            mask.Lock();

            canvas.Lock();

            unsafe
            {
                uint *pixelsImage  = (uint *)image.BackBuffer;
                uint *pixelsMask   = (uint *)mask.BackBuffer;
                uint *pixelsCanvas = (uint *)canvas.BackBuffer;

                if (pixelsImage == null || pixelsMask == null || pixelsCanvas == null)
                {
                    return(false);
                }

                uint col    = 0;
                int  stride = canvas.BackBufferStride >> 2;
                for (uint row = 0; row < canvas.Height; ++row)
                {
                    uint total_row_len       = (uint)(row * stride);
                    uint total_row_mask_len  = (uint)(row * (mask.BackBufferStride >> 2));
                    uint total_row_image_len = (uint)(row * (image.BackBufferStride >> 2));
                    for (col = 0; col < canvas.Width; ++col)
                    {
                        if (row >= image.Height || col >= image.Width)
                        {
                            continue;
                        }
                        if (row >= mask.Height || col >= mask.Width)
                        {
                            continue;
                        }

                        uint index      = total_row_len + col;
                        uint indexMask  = total_row_mask_len + col;
                        uint indexImage = total_row_image_len + col;

                        byte maskByte = 0;

                        if (MaskColor.IsEqual(maskColor, MaskColor.Red))
                        {
                            maskByte = (Byte)((pixelsMask[indexMask] & 0xff0000) >> 16);
                        }
                        else if (MaskColor.IsEqual(maskColor, MaskColor.Green))
                        {
                            maskByte = (Byte)((pixelsMask[indexMask] & 0xff00) >> 8);
                        }
                        else if (MaskColor.IsEqual(maskColor, MaskColor.Blue))
                        {
                            maskByte = (Byte)(pixelsMask[indexMask] & 0xff);
                        }

                        if (maskByte > 0)
                        {
                            if (NoAlphaAtBoundary)
                            {
                                pixelsCanvas[index] = AlphablendNoAlphaAtBoundary(pixelsCanvas[index], pixelsImage[indexImage], (Byte)(pixelsMask[indexMask] >> 24), (Byte)(pixelsMask[indexMask] >> 24));
                            }
                            else
                            {
                                pixelsCanvas[index] = Alphablend(pixelsCanvas[index], pixelsImage[indexImage], (Byte)(pixelsMask[indexMask] >> 24), (Byte)(pixelsMask[indexMask] >> 24));
                            }
                        }
                    }
                }
            }
            canvas.Unlock();
            mask.Unlock();
            image.Unlock();

            return(true);
        }