private static void CopyFromBitmap(byte[] buffer, WriteableBitmap bitmap, int offset, int length)
        {
#if WPF
            Marshal.Copy(bitmap.BackBuffer + offset, buffer, 0, length);
#elif WINRT

            bitmap.PixelBuffer.CopyTo((uint)offset, buffer, 0, length);
#else
            #error Not implemented
#endif
        }
Example #2
0
File: Class1.cs Project: Pokat/Life
            static void Main(string[] args)
            {
                i = new Image();
                RenderOptions.SetBitmapScalingMode(i, BitmapScalingMode.NearestNeighbor);
                RenderOptions.SetEdgeMode(i, EdgeMode.Aliased);

                w = new Window();
                w.Content = i;
                w.Show();

                writeableBitmap = new WriteableBitmap(
                    (int)w.ActualWidth,
                    (int)w.ActualHeight,
                    96,
                    96,
                    PixelFormats.Bgr32,
                    null);

                i.Source = writeableBitmap;

                i.Stretch = Stretch.None;
                i.HorizontalAlignment = HorizontalAlignment.Left;
                i.VerticalAlignment = VerticalAlignment.Top;

                i.MouseMove += new MouseEventHandler(i_MouseMove);
                i.MouseLeftButtonDown +=
                    new MouseButtonEventHandler(i_MouseLeftButtonDown);
                i.MouseRightButtonDown +=
                    new MouseButtonEventHandler(i_MouseRightButtonDown);

                w.MouseWheel += new MouseWheelEventHandler(w_MouseWheel);

                Application app = new Application();
                app.Run();
            }
        public static void BlitBlt(this WriteableBitmap dst, Point pt, WriteableBitmap src, Rect rc)
        {
            // crop rectangle
            if (rc.X + rc.Width > src.PixelWidth)
                rc.Width = src.PixelWidth - rc.X;
            if (rc.Y + rc.Height > src.PixelHeight)
                rc.Height = src.PixelHeight - rc.Y;
            if (pt.X + rc.Width > dst.PixelWidth)
                rc.Width = dst.PixelWidth - pt.X;
            if (pt.Y + rc.Height > dst.PixelHeight)
                rc.Height = dst.PixelHeight - pt.Y;

            // copy rectangle
            int[] srcPixels = src.Pixels;
            int[] dstPixels = dst.Pixels;
            int srcOffset = (int)(src.PixelWidth * rc.Y + rc.X) * 4;
            int dstOffset = (int)(dst.PixelWidth * pt.Y + pt.X) * 4;
            int max = (int)rc.Height;
            int len = (int)rc.Width * 4;

            for (int y = 0; y < max; y++)
            {
                Buffer.BlockCopy(srcPixels, srcOffset, dstPixels, dstOffset, len);
                srcOffset += src.PixelWidth * 4;
                dstOffset += dst.PixelWidth * 4;
            }
        }
        public void Add(string key, ImageInformation imageInformation, WriteableBitmap bitmap)
        {
            if (string.IsNullOrWhiteSpace(key) || bitmap == null)
                return;

            var weakRef = new WeakReference<WriteableBitmap>(bitmap);
            _reusableBitmaps.TryAdd(key, new Tuple<WeakReference<WriteableBitmap>, ImageInformation>(weakRef, imageInformation));
        }
        /// <summary>
        /// パラメータ無しの画像処理をおこなう
        /// </summary>
        /// <param name="bmp">元になるWriteableBitmapオブジェクト</param>
        /// <param name="effector">処理させるIEffectオブジェクト</param>
        /// <returns>処理後のWriteableBitmapオブジェクト</returns>
        private static WriteableBitmap ProcessEffect(WriteableBitmap bmp, IEffect effector)
        {
            // WriteableBitmapのピクセルデータをバイト配列に変換する
            var srcPixels = bmp.GetPixels();

            // パラメータ無しの画像処理をおこなう
            var dstPixels = effector.Effect(bmp.PixelWidth, bmp.PixelHeight, srcPixels);

            // バイト配列からピクセルを作成する
            return WriteableBitmapLoadExtensions.FromArray(bmp.PixelWidth, bmp.PixelHeight, dstPixels);
        }
Example #6
0
        private void Init(int width, int height)
        {
            _bitmap = BitmapFactory.New(width, height);
            _data = new ushort[width * height];
            _bytes = new byte[width * height * 4];
            _stride = width * 4;
#if NETFX_CORE
            _stream = _bitmap.PixelBuffer.AsStream();
#else
            _dirtyRect = new Int32Rect(0, 0, width, height);
#endif
        }
        /// <summary>
        /// バイト配列からWriteableBitmapを生成する
        /// </summary>
        /// <param name="width">幅</param>
        /// <param name="height">高さ</param>
        /// <param name="array">ピクセルデータ</param>
        /// <returns>WriteableBitmapオブジェクト</returns>
        public static WriteableBitmap FromArray(int width, int height, byte[] array, ImageFileTypes type = ImageFileTypes.Normal)
        {
            // 出力用のWriteableBitmapオブジェクトを生成する
            var bitmap = new WriteableBitmap(width, height);
#if WINDOWS_STORE_APPS
            if (type == ImageFileTypes.GifWithStrokes)
            {
                // WriteableBitmapへバイト配列のピクセルデータをコピーする
                using (var pixelStream = bitmap.PixelBuffer.AsStream())
                {
                    pixelStream.Seek(0, SeekOrigin.Begin);

                    var pixelCount = array.Length / 4;
                    for (var i = 0; i < pixelCount; i++)
                    {
                        var index = i * 4;
                        var r = array[index + 0];
                        var g = array[index + 1];
                        var b = array[index + 2];
                        var a = array[index + 3];

                        pixelStream.WriteByte(b);
                        pixelStream.WriteByte(g);
                        pixelStream.WriteByte(r);
                        pixelStream.WriteByte(a);
                    }
                }
            }
            else
            {
                // WriteableBitmapへバイト配列のピクセルデータをコピーする
                using (var pixelStream = bitmap.PixelBuffer.AsStream())
                {
                    pixelStream.Seek(0, SeekOrigin.Begin);
                    pixelStream.Write(array, 0, array.Length);
                }

            }
#elif WINDOWS_PHONE
            int max = width * height;
            for (int i = 0; i < max; i++)
            {
                int index = i * 4;
                int a = array[index + 3];
                int r = array[index + 2];
                int g = array[index + 1];
                int b = array[index + 0];

                bitmap.Pixels[i] = (a << 24 | r << 16 | g << 8 | b);
            }
#endif
            return bitmap;
        }
 /// <summary>
 /// Creates a new cropped WriteableBitmap.
 /// </summary>
 /// <param name="bmp">The WriteableBitmap.</param>
 /// <param name="x">The x coordinate of the rectangle that defines the crop region.</param>
 /// <param name="y">The y coordinate of the rectangle that defines the crop region.</param>
 /// <param name="width">The width of the rectangle that defines the crop region.</param>
 /// <param name="height">The height of the rectangle that defines the crop region.</param>
 /// <returns>A new WriteableBitmap that is a cropped version of the input.</returns>
 public static WriteableBitmap Crop(this WriteableBitmap bmp, int x, int y, int width, int height)
 {
     WriteableBitmap result = new WriteableBitmap(width, height);
     int srcWidth = bmp.PixelWidth;
     for (int line = 0; line < height; line++)
     {
         var srcOff = ((y + line) * srcWidth + x) * SizeOfARGB;
         var dstOff = line * width * SizeOfARGB;
         Buffer.BlockCopy(bmp.Pixels, srcOff, result.Pixels, dstOff, width * SizeOfARGB);
     }
     return result;
 }
Example #9
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ColorFrameBitmap"/> class.
        /// </summary>
        public ColorFrameBitmap()
        {
            var sensor = KinectSensor.GetDefault();
            int width = sensor.ColorFrameSource.FrameDescription.Width;
            int height = sensor.ColorFrameSource.FrameDescription.Height;
            _bitmap = BitmapFactory.New(width, height);
            _bytes = new byte[width * height * 4];
#if NETFX_CORE
            _stream = _bitmap.PixelBuffer.AsStream();
#else
            _dirtyRect = new Int32Rect(0, 0, width, height);
#endif
        }
        /// <summary>
        /// パラメータ無しの画像処理をおこなう
        /// </summary>
        /// <param name="bmp">元になるWriteableBitmapオブジェクト</param>
        /// <param name="effectors">処理させるIEffectオブジェクト配列</param>
        /// <returns>処理後のWriteableBitmapオブジェクト</returns>
        private static WriteableBitmap ProcessEffect(WriteableBitmap bmp, IEnumerable<IEffect> effectors)
        {
            var pixels = bmp.GetPixels();
            var width = bmp.PixelWidth;
            var height = bmp.PixelHeight;

            foreach (var effector in effectors)
            {
                pixels = effector.Effect(width, height, pixels);
            }

            return WriteableBitmapLoadExtensions.FromArray(width, height, pixels);
        }
Example #11
0
 private Animator(Stream sourceStream, Uri sourceUri, GifDataStream metadata, RepeatBehavior repeatBehavior, Image image)
 {
     _sourceStream = sourceStream;
     _sourceUri = sourceUri;
     _metadata = metadata;
     _image = image;
     _palettes = CreatePalettes(metadata);
     _bitmap = CreateBitmap(metadata);
     var desc = metadata.Header.LogicalScreenDescriptor;
     _stride = 4 * ((desc.Width * 32 + 31) / 32);
     _previousBackBuffer = new byte[desc.Height * _stride];
     _indexStreamBuffer = CreateIndexStreamBuffer(metadata, _sourceStream);
     _timingManager = CreateTimingManager(metadata, repeatBehavior);
 }
Example #12
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ColorFrameBitmap" /> class
        /// suitable for displaying the supplied <see cref="ReplayColorFrame" />.
        /// </summary>
        /// <param name="frame">The frame.</param>
        public ColorFrameBitmap(ReplayColorFrame frame)
        {
#if NETFX_CORE
            _bitmap = BitmapFactory.New(frame.Width, frame.Height);
            _bytes = new byte[_bitmap.PixelWidth * _bitmap.PixelHeight * 4];
            _stream = _bitmap.PixelBuffer.AsStream();
#else
            // force population of PixelFormat
            var data = frame.GetFrameDataAsync().Result;
            _bitmap = new WriteableBitmap(frame.Width, frame.Height, 96, 96, frame.Codec.PixelFormat, null);
            _bytes = new byte[_bitmap.PixelWidth * _bitmap.PixelHeight * (_bitmap.Format.BitsPerPixel / 8)];
            _dirtyRect = new Int32Rect(0, 0, frame.Width, frame.Height);
#endif
        }
Example #13
0
        /// <summary>
        /// Renders a UI control into an image.
        /// </summary>
        /// <param name="control"></param>
        /// <param name="isWideTile"></param>
        /// <returns></returns>
        public static void CreateImage(UIElement control, string imagePath, int width, int height, SolidColorBrush tileBackgroundColor)
        {
            // 1. Setup dimensions for wide tile.
            var bmp = new WriteableBitmap(width, height);

            // 2. Get the name of the background image based on theme            
            var canvas = new System.Windows.Controls.Canvas();
            canvas.Width = width;
            canvas.Height = height;
            canvas.Background = tileBackgroundColor;

            canvas.Children.Add(control);
            canvas.Measure(new Size(width, height));
            canvas.Arrange(new Rect(0, 0, width, height));
            canvas.UpdateLayout();

            // 4. Now output the control as text.
            bmp.Render(canvas, null);
            bmp.Invalidate();

            // 8. Now save the image to local folder.
            using (var store = IsolatedStorageFile.GetUserStoreForApplication())
            {
                // FileMode.Open, FileAccess.Read, FileShare.Read,
                using (var st = new IsolatedStorageFileStream(imagePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite, store))
                {
                    bmp.SaveJpeg(st, width, height, 0, 100);
                    st.Close();
                }
            }

            try
            {

                bmp = null;
                canvas.Children.Clear();
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
            catch (Exception ex)
            {
                Slate.Core.Logging.Logger.Error("Create image", "Warning, attempt to clear up memory for tile image failed", ex);
            }
        }
      public BitmapLuminanceSource(WriteableBitmap writeableBitmap)
         : base(writeableBitmap.PixelWidth, writeableBitmap.PixelHeight)
      {
         var height = writeableBitmap.PixelHeight;
         var width = writeableBitmap.PixelWidth;
         var stride = width * 4;
         // In order to measure pure decoding speed, we convert the entire image to a greyscale array
         luminances = new byte[width * height];
         Color c;

#if NETFX_CORE
         var data = System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeBufferExtensions.ToArray(writeableBitmap.PixelBuffer, 0, (int)writeableBitmap.PixelBuffer.Length);
         for (int y = 0; y < height; y++)
         {
            int offset = y * stride;
            for (int x = 0, xl = 0; x < stride; x += 4, xl++)
            {
               c = Color.FromArgb(
                  data[x + offset], 
                  data[x + offset + 1], 
                  data[x + offset + 2], 
                  data[x + offset + 3]);
               luminances[y * width + xl] = (byte)(0.3 * c.R + 0.59 * c.G + 0.11 * c.B + 0.01);
            }
         }
#else
         var pixels = writeableBitmap.Pixels;
         for (int y = 0; y < height; y++)
         {
            int offset = y * width;
            for (int x = 0; x < width; x++)
            {
               int srcPixel = pixels[x + offset];
               c = Color.FromArgb((byte)((srcPixel >> 0x18) & 0xff),
                     (byte)((srcPixel >> 0x10) & 0xff),
                     (byte)((srcPixel >> 8) & 0xff),
                     (byte)(srcPixel & 0xff));
               luminances[offset + x] = (byte)(0.3 * c.R + 0.59 * c.G + 0.11 * c.B + 0.01);
            }
         }
#endif
      }
      public BitmapLuminanceSource(WriteableBitmap writeableBitmap)
         : base(writeableBitmap.PixelWidth, writeableBitmap.PixelHeight)
      {
         var height = writeableBitmap.PixelHeight;
         var width = writeableBitmap.PixelWidth;

         // In order to measure pure decoding speed, we convert the entire image to a greyscale array
         // luminance array is initialized with new byte[width * height]; in base class
#if NETFX_CORE
         var data = System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeBufferExtensions.ToArray(writeableBitmap.PixelBuffer, 0, (int)writeableBitmap.PixelBuffer.Length);
         var luminanceIndex = 0;
         var maxSourceIndex = width*height*4;
         for (var sourceIndex = 0; sourceIndex < maxSourceIndex; sourceIndex+=4)
         {
            var c = Color.FromArgb(
               data[sourceIndex], 
               data[sourceIndex + 1], 
               data[sourceIndex + 2], 
               data[sourceIndex + 3]);
            luminances[luminanceIndex] = (byte)((RChannelWeight * c.R + GChannelWeight * c.G + BChannelWeight * c.B) >> ChannelWeight);
            luminanceIndex++;
         }
#else
         var pixels = writeableBitmap.Pixels;
         var luminanceIndex = 0;
         var maxSourceIndex = width*height;
         for (var sourceIndex = 0; sourceIndex < maxSourceIndex; sourceIndex++)
         {
            int srcPixel = pixels[sourceIndex];
            var c = Color.FromArgb(
               (byte) ((srcPixel >> 24) & 0xff),
               (byte) ((srcPixel >> 16) & 0xff),
               (byte) ((srcPixel >> 8) & 0xff),
               (byte) (srcPixel & 0xff));
            luminances[luminanceIndex] = (byte)((RChannelWeight * c.R + GChannelWeight * c.G + BChannelWeight * c.B) >> ChannelWeight);
            luminanceIndex++;
         }
#endif
      }
        /// <summary>
        /// Renders a bitmap using any affine transformation and transparency into this bitmap
        /// Unlike Silverlight's Render() method, this one uses 2-3 times less memory, and is the same or better quality
        /// The algorithm is simple dx/dy (bresenham-like) step by step painting, optimized with fixed point and fast bilinear filtering
        /// It's used in Fantasia Painter for drawing stickers and 3D objects on screen
        /// </summary>
        /// <param name="bmp">Destination bitmap.</param>
        /// <param name="source">The source WriteableBitmap.</param>
        /// <param name="shouldClear">If true, the the destination bitmap will be set to all clear (0) before rendering.</param>
        /// <param name="opacity">opacity of the source bitmap to render, between 0 and 1 inclusive</param>
        /// <param name="transform">Transformation to apply</param>
        public static void BlitRender(this WriteableBitmap bmp, WriteableBitmap source, bool shouldClear = true, float opacity = 1f, GeneralTransform transform = null)
        {
            const int PRECISION_SHIFT = 10;
            const int PRECISION_VALUE = (1 << PRECISION_SHIFT);
            const int PRECISION_MASK = PRECISION_VALUE - 1;

            using (BitmapContext destContext = bmp.GetBitmapContext())
            {
                if (transform == null) transform = new MatrixTransform();

                var destPixels = destContext.Pixels;
                int destWidth = destContext.Width;
                int destHeight = destContext.Height;
                var inverse = transform.Inverse;
                if(shouldClear) destContext.Clear();

                using (BitmapContext sourceContext = source.GetBitmapContext())
                {
                    var sourcePixels = sourceContext.Pixels;
                    int sourceWidth = sourceContext.Width;
                    int sourceHeight = sourceContext.Height;

                    Rect sourceRect = new Rect(0, 0, sourceWidth, sourceHeight);
                    Rect destRect = new Rect(0, 0, destWidth, destHeight);
                    Rect bounds = transform.TransformBounds(sourceRect);
                    bounds.Intersect(destRect);

                    int startX = (int)bounds.Left;
                    int startY = (int)bounds.Top;
                    int endX = (int)bounds.Right;
                    int endY = (int)bounds.Bottom;

#if NETFX_CORE
                    Point zeroZero = inverse.TransformPoint(new Point(startX, startY));
                    Point oneZero = inverse.TransformPoint(new Point(startX + 1, startY));
                    Point zeroOne = inverse.TransformPoint(new Point(startX, startY + 1));
#else
                    Point zeroZero = inverse.Transform(new Point(startX, startY));
                    Point oneZero = inverse.Transform(new Point(startX + 1, startY));
                    Point zeroOne = inverse.Transform(new Point(startX, startY + 1));
#endif
                    float sourceXf = ((float)zeroZero.X);
                    float sourceYf = ((float)zeroZero.Y);
                    int dxDx = (int)((((float)oneZero.X) - sourceXf) * PRECISION_VALUE); // for 1 unit in X coord, how much does X change in source texture?
                    int dxDy = (int)((((float)oneZero.Y) - sourceYf) * PRECISION_VALUE); // for 1 unit in X coord, how much does Y change in source texture?
                    int dyDx = (int)((((float)zeroOne.X) - sourceXf) * PRECISION_VALUE); // for 1 unit in Y coord, how much does X change in source texture?
                    int dyDy = (int)((((float)zeroOne.Y) - sourceYf) * PRECISION_VALUE); // for 1 unit in Y coord, how much does Y change in source texture?

                    int sourceX = (int)(((float)zeroZero.X) * PRECISION_VALUE);
                    int sourceY = (int)(((float)zeroZero.Y) * PRECISION_VALUE);
                    int sourceWidthFixed = sourceWidth << PRECISION_SHIFT;
                    int sourceHeightFixed = sourceHeight << PRECISION_SHIFT;

                    int opacityInt = (int)(opacity * 255);

                    int index = 0;
                    for (int destY = startY; destY < endY; destY++)
                    {
                        index = destY * destWidth + startX;
                        int savedSourceX = sourceX;
                        int savedSourceY = sourceY;

                        for (int destX = startX; destX < endX; destX++)
                        {
                            if ((sourceX >= 0) && (sourceX < sourceWidthFixed) && (sourceY >= 0) && (sourceY < sourceHeightFixed))
                            {
                                // bilinear filtering
                                int xFloor = sourceX >> PRECISION_SHIFT;
                                int yFloor = sourceY >> PRECISION_SHIFT;

                                if (xFloor < 0) xFloor = 0;
                                if (yFloor < 0) yFloor = 0;

                                int xCeil = xFloor + 1;
                                int yCeil = yFloor + 1;

                                if (xCeil >= sourceWidth)
                                {
                                    xFloor = sourceWidth - 1;
                                    xCeil = 0;
                                }
                                else
                                {
                                    xCeil = 1;
                                }

                                if (yCeil >= sourceHeight)
                                {
                                    yFloor = sourceHeight - 1;
                                    yCeil = 0;
                                }
                                else
                                {
                                    yCeil = sourceWidth;
                                }

                                int i1 = yFloor * sourceWidth + xFloor;
                                int p1 = sourcePixels[i1];
                                int p2 = sourcePixels[i1 + xCeil];
                                int p3 = sourcePixels[i1 + yCeil];
                                int p4 = sourcePixels[i1 + yCeil + xCeil];

                                int xFrac = sourceX & PRECISION_MASK;
                                int yFrac = sourceY & PRECISION_MASK;

                                // alpha
                                byte a1 = (byte)(p1 >> 24);
                                byte a2 = (byte)(p2 >> 24);
                                byte a3 = (byte)(p3 >> 24);
                                byte a4 = (byte)(p4 >> 24);

                                int comp1, comp2;
                                byte a;

                                if ((a1 == a2) && (a1 == a3) && (a1 == a4))
                                {
                                    if (a1 == 0)
                                    {
                                        destPixels[index] = 0;

                                        sourceX += dxDx;
                                        sourceY += dxDy;
                                        index++;
                                        continue;
                                    }

                                    a = a1;
                                }
                                else
                                {
                                    comp1 = a1 + ((xFrac * (a2 - a1)) >> PRECISION_SHIFT);
                                    comp2 = a3 + ((xFrac * (a4 - a3)) >> PRECISION_SHIFT);
                                    a = (byte)(comp1 + ((yFrac * (comp2 - comp1)) >> PRECISION_SHIFT));
                                }

                                // red
                                comp1 = ((byte)(p1 >> 16)) + ((xFrac * (((byte)(p2 >> 16)) - ((byte)(p1 >> 16)))) >> PRECISION_SHIFT);
                                comp2 = ((byte)(p3 >> 16)) + ((xFrac * (((byte)(p4 >> 16)) - ((byte)(p3 >> 16)))) >> PRECISION_SHIFT);
                                byte r = (byte)(comp1 + ((yFrac * (comp2 - comp1)) >> PRECISION_SHIFT));

                                // green
                                comp1 = ((byte)(p1 >> 8)) + ((xFrac * (((byte)(p2 >> 8)) - ((byte)(p1 >> 8)))) >> PRECISION_SHIFT);
                                comp2 = ((byte)(p3 >> 8)) + ((xFrac * (((byte)(p4 >> 8)) - ((byte)(p3 >> 8)))) >> PRECISION_SHIFT);
                                byte g = (byte)(comp1 + ((yFrac * (comp2 - comp1)) >> PRECISION_SHIFT));

                                // blue
                                comp1 = ((byte)p1) + ((xFrac * (((byte)p2) - ((byte)p1))) >> PRECISION_SHIFT);
                                comp2 = ((byte)p3) + ((xFrac * (((byte)p4) - ((byte)p3))) >> PRECISION_SHIFT);
                                byte b = (byte)(comp1 + ((yFrac * (comp2 - comp1)) >> PRECISION_SHIFT));

                                // save updated pixel
                                if (opacityInt != 255)
                                {
                                    a = (byte)((a * opacityInt) >> 8);
                                    r = (byte)((r * opacityInt) >> 8);
                                    g = (byte)((g * opacityInt) >> 8);
                                    b = (byte)((b * opacityInt) >> 8);
                                }
                                destPixels[index] = (a << 24) | (r << 16) | (g << 8) | b;
                            }

                            sourceX += dxDx;
                            sourceY += dxDy;
                            index++;
                        }

                        sourceX = savedSourceX + dyDx;
                        sourceY = savedSourceY + dyDy;
                    }
                }
            }
        }
        /// <summary>
        /// Draws a quad.
        /// </summary>
        /// <param name="bmp">The WriteableBitmap.</param>
        /// <param name="x1">The x-coordinate of the 1st point.</param>
        /// <param name="y1">The y-coordinate of the 1st point.</param>
        /// <param name="x2">The x-coordinate of the 2nd point.</param>
        /// <param name="y2">The y-coordinate of the 2nd point.</param>
        /// <param name="x3">The x-coordinate of the 3rd point.</param>
        /// <param name="y3">The y-coordinate of the 3rd point.</param>
        /// <param name="x4">The x-coordinate of the 4th point.</param>
        /// <param name="y4">The y-coordinate of the 4th point.</param>
        /// <param name="color">The color.</param>
        public static void DrawQuad(this WriteableBitmap bmp, int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4, Color color)
        {
            var col = ConvertColor(color);

            bmp.DrawQuad(x1, y1, x2, y2, x3, y3, x4, y4, col);
        }
Example #18
0
 void BitmapImageOpened(object sender, RoutedEventArgs e)
 {
     _sourceBitmap = new WriteableBitmap(_bitmap);
     UpdateTiledImage();
 }
Example #19
0
        /// <summary>
        /// 解析二维码图片
        /// </summary>
        /// <param name="writeableBmp">图片</param>
        /// <returns></returns>
        private async Task ScanBitmap(WriteableBitmap writeableBmp)
        {
            try
            {
                var barcodeReader = new BarcodeReader
                {
                    AutoRotate = true,
                    Options    = new ZXing.Common.DecodingOptions {
                        TryHarder = true
                    }
                };
                await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    _result = barcodeReader.Decode(writeableBmp);
                });



                if (_result != null)
                {
                    Debug.WriteLine(@"[INFO]扫描到二维码:{result}   ->" + _result.Text);
                    await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() =>
                    {
                        if (await MessageCenter.HandelUrl(_result.Text))
                        {
                            return;
                        }

                        //string ban = Regex.Match(_result.Text, @"^http://bangumi.bilibili.com/anime/(.*?)$").Groups[1].Value;
                        //if (ban.Length != 0)
                        //{
                        //    //args.Handled = true;
                        //    MessageCenter.SendNavigateTo(NavigateMode.Info, typeof(BanInfoPage), ban.Replace("/", ""));
                        //    this.Frame.GoBack();
                        //    return;
                        //}
                        //string ban2 = Regex.Match(_result.Text, @"^http://www.bilibili.com/bangumi/i/(.*?)$").Groups[1].Value;
                        //if (ban2.Length != 0)
                        //{
                        //    //args.Handled = true;
                        //    MessageCenter.SendNavigateTo(NavigateMode.Info, typeof(BanInfoPage), ban2.Replace("/", ""));
                        //    this.Frame.GoBack();
                        //    // this.Frame.Navigate(typeof(BanInfoPage), ban2.Replace("/", ""));
                        //    return;
                        //}
                        ////bilibili://?av=4284663
                        //string ban3 = Regex.Match(_result.Text, @"^bilibili://?av=(.*?)$").Groups[1].Value;
                        //if (ban3.Length != 0)
                        //{
                        //    //args.Handled = true;
                        //    MessageCenter.SendNavigateTo(NavigateMode.Info, typeof(VideoViewPage), ban3.Replace("/", ""));
                        //    this.Frame.GoBack();
                        //    //this.Frame.Navigate(typeof(VideoViewPage), ban3.Replace("/", ""));
                        //    return;
                        //}


                        //string ban4 = Regex.Match(_result.Text + "/", @"space.bilibili.com/(.*?)/").Groups[1].Value;
                        //if (ban4.Length != 0)
                        //{
                        //    //args.Handled = true;
                        //    MessageCenter.SendNavigateTo(NavigateMode.Info, typeof(UserCenterPage), ban4.Replace("/", ""));
                        //    this.Frame.GoBack();
                        //    //this.Frame.Navigate(typeof(VideoViewPage), ban3.Replace("/", ""));
                        //    return;
                        //}

                        string ban5 = Regex.Match(_result.Text + "/", @"oauthKey=(.*?)/").Groups[1].Value;
                        if (ban5.Length != 0)
                        {
                            MessageCenter.SendNavigateTo(NavigateMode.Info, typeof(WebPage), "https://passport.bilibili.com/qrcode/h5/login?oauthKey=" + ban5.Replace("/", ""));
                            this.Frame.GoBack();
                            //if (!ApiHelper.IsLogin())
                            //{
                            //    await new MessageDialog("手机需先登录!").ShowAsync();
                            //    return;
                            //}
                            ////args.Handled = true;
                            //pr_Laod.Visibility = Visibility.Visible;
                            //LoginStatus dts = await ApiHelper.QRLogin(ban5.Replace("/", ""));
                            //if (dts==LoginStatus.Succeed)
                            //{
                            //    this.Frame.GoBack();
                            //}
                            //else
                            //{
                            //    await new MessageDialog("登录失败").ShowAsync();
                            //}
                            //pr_Laod.Visibility = Visibility.Collapsed;
                            //MessageCenter.SendNavigateTo(NavigateMode.Play, typeof(UserInfoPage), ban5.Replace("/", ""));
                            //this.Frame.Navigate(typeof(VideoViewPage), ban3.Replace("/", ""));
                            return;
                        }
                        //text .Text= args.Uri.AbsoluteUri;

                        //string live = Regex.Match(_result.Text, @"^bilibili://live/(.*?)$").Groups[1].Value;
                        //if (live.Length != 0)
                        //{
                        //    MessageCenter.SendNavigateTo(NavigateMode.Play, typeof(LiveRoomPage), live);

                        //    return;
                        //}

                        //string live2 = Regex.Match(_result.Text + "a", @"live.bilibili.com/(.*?)a").Groups[1].Value;
                        //if (live2.Length != 0)
                        //{
                        //    MessageCenter.SendNavigateTo(NavigateMode.Play, typeof(LiveRoomPage), live2.Replace("a", ""));

                        //    return;
                        //}

                        //if (Regex.IsMatch(_result.Text, "/video/av(.*)?[/|+](.*)?"))
                        //{

                        //    string a = Regex.Match(_result.Text, "/video/av(.*)?[/|+](.*)?").Groups[1].Value;
                        //    //this.Frame.Navigate(typeof(VideoViewPage), a);
                        //    MessageCenter.SendNavigateTo(NavigateMode.Info, typeof(VideoViewPage), a);
                        //    this.Frame.GoBack();
                        //    return;
                        //}


                        tbkResult.Text = "无法识别的类型";
                    });
                }
            }
            catch (Exception)
            {
            }
        }
 /// <summary>
 /// Copies (blits) the pixels from the WriteableBitmap source to the destination WriteableBitmap (this).
 /// </summary>
 /// <param name="bmp">The destination WriteableBitmap.</param>
 /// <param name="destRect">The rectangle that defines the destination region.</param>
 /// <param name="source">The source WriteableBitmap.</param>
 /// <param name="sourceRect">The rectangle that will be copied from the source to the destination.</param>
 public static void Blit(this WriteableBitmap bmp, Rect destRect, WriteableBitmap source, Rect sourceRect)
 {
     Blit(bmp, destRect, source, sourceRect, Colors.White, BlendMode.AlphaBlend);
 }
Example #21
0
        //http://gaggerostechnicalnotes.blogspot.com/2012/01/wpf-colors-scale.html
        private WriteableBitmap CompleteColorScale(System.Drawing.Color start, System.Drawing.Color end)
        {
            //var drawPlane = new System.Windows.Controls.Image();

            const int size = 64;

            const int width = 1;
            const int height = size;

            var bitmap = new WriteableBitmap(width, height, 96, 96, PixelFormats.Bgra32, null);
            var pixels = new uint[width * height];

            for (int i = 0; i < size; i++)
            {
                var newRed = start.R + ((end.R - start.R)/size)*i;
                var newGreen = start.G + ((end.G - start.G) / size) * i;
                var newBlue = start.B + ((end.B - start.B) / size) * i;

                //pixels[i] = (uint)((newBlue << 16) + (newGreen << 8) + (newRed << 0));
                pixels[i] = (uint)((255 << 24) + (newRed << 16) + (newGreen << 8) + newBlue);

            }

            bitmap.WritePixels(new Int32Rect(0, 0, width, height), pixels, width * 4, 0);
            return bitmap;
        }
Example #22
0
        public unsafe WriteableBitmap GetWriteableBitmap(int width, int height, float dpix, float dpiy, int rotation, RenderType type, bool rotateLandscapePages, bool convertToLetter, int maxSize)
        {
            WriteableBitmap write   = null;
            int             nLength = 0;
            IntPtr          data    = _Api.GetBitmapData(this.m_pNativeObject, out width, out height, dpix, dpiy, rotation, (int)type, rotateLandscapePages, convertToLetter, out nLength, maxSize);

            if (data == null || data == IntPtr.Zero)
            {
                throw new Exception("Unable to render pdf page to bitmap!");
            }

            if (type == RenderType.RGB)
            {
                const int depth     = 24;
                int       bmpstride = ((width * depth + 31) & ~31) >> 3;

                write = new WriteableBitmap(width, height, (double)dpix, (double)dpiy, PixelFormats.Bgr24, null);
                Int32Rect rect = new Int32Rect(0, 0, width, height);
                write.Lock();

                byte *ptrSrc  = (byte *)data;
                byte *ptrDest = (byte *)write.BackBuffer;
                for (int y = 0; y < height; y++)
                {
                    byte *pl = ptrDest;
                    byte *sl = ptrSrc;
                    for (int x = 0; x < width; x++)
                    {
                        //Swap these here instead of in MuPDF because most pdf images will be rgb or cmyk.
                        //Since we are going through the pixels one by one anyway swap here to save a conversion from rgb to bgr.
                        pl[2] = sl[0]; //b-r
                        pl[1] = sl[1]; //g-g
                        pl[0] = sl[2]; //r-b
                        //pl[3] = sl[3]; //alpha
                        pl += 3;
                        sl += 4;
                    }
                    ptrDest += bmpstride;
                    ptrSrc  += width * 4;
                }
                write.AddDirtyRect(rect);
                write.Unlock();
            }
            else if (type == RenderType.Grayscale)
            {
                const int depth     = 8;//(n * 8)
                int       bmpstride = ((width * depth + 31) & ~31) >> 3;

                write = new WriteableBitmap(width, height, (double)dpix, (double)dpiy, PixelFormats.Gray8, BitmapPalettes.Gray256);
                Int32Rect rect = new Int32Rect(0, 0, width, height);
                write.Lock();

                byte *ptrSrc  = (byte *)data;
                byte *ptrDest = (byte *)write.BackBuffer;
                for (int y = 0; y < height; y++)
                {
                    byte *pl = ptrDest;
                    byte *sl = ptrSrc;
                    for (int x = 0; x < width; x++)
                    {
                        pl[0] = sl[0]; //g
                        //pl[1] = sl[1]; //alpha
                        pl += 1;
                        sl += 2;
                    }
                    ptrDest += bmpstride;
                    ptrSrc  += width * 2;
                }
                write.AddDirtyRect(rect);
                write.Unlock();
            }
            else
            {
                write = new WriteableBitmap(width, height, (double)dpix, (double)dpiy, PixelFormats.BlackWhite, BitmapPalettes.BlackAndWhite);
                Int32Rect rect = new Int32Rect(0, 0, width, height);
                write.Lock();
                byte *ptrSrc  = (byte *)data;
                byte *ptrDest = (byte *)write.BackBuffer;
                for (int i = 0; i < nLength; i++)
                {
                    ptrDest[i] = ptrSrc[i];
                }
                write.AddDirtyRect(rect);
                write.Unlock();
            }
            _Api.FreeRenderedPage(this.m_pNativeObject);//Free unmanaged array
            if (write.CanFreeze)
            {
                write.Freeze();
            }
            return(write);
        }
        // Create a bitmap image from the elevation data
        private async Task <WriteableBitmap> CreateElevationImageAsync(ElevationData elevationData)
        {
            int thematicMin = elevationData.data[0];
            int thematicMax = elevationData.data[0];

            foreach (int elevValue in elevationData.data)
            {
                if (elevValue < thematicMin)
                {
                    thematicMin = elevValue;
                }
                if (elevValue > thematicMax)
                {
                    thematicMax = elevValue;
                }
            }

            int          totalRange = thematicMax - thematicMin;
            int          portion    = totalRange / 5;
            List <Color> cellColor  = new List <Color>();

            foreach (int elevValue in elevationData.data)
            {
                int startValue = thematicMin;
                for (int i = 0; i < 5; i++)
                {
                    if (Enumerable.Range(startValue, portion).Contains(elevValue))
                    {
                        cellColor.Add(colorRanges[i]);
                        break;
                    }
                    else if (i == 4)
                    {
                        cellColor.Add(colorRanges.Last());
                    }

                    startValue = startValue + portion;
                }
            }

            int rows = Convert.ToInt32(HeightTextBox.Text);
            int cols = Convert.ToInt32(WidthTextBox.Text);

            byte[] pixelData = new byte[rows * cols * 4];
            int    cell      = 0;
            int    pos       = 0;

            for (int x = 0; x < rows; x++)
            {
                for (int y = 0; y < cols; y++)
                {
                    Color color = cellColor[cell++];
                    pixelData[pos++] = color.B;
                    pixelData[pos++] = color.G;
                    pixelData[pos++] = color.R;
                    pixelData[pos++] = (byte)255;
                }
            }
            WriteableBitmap writeableBitmapElevation = new WriteableBitmap(rows, cols);
            Stream          stream = writeableBitmapElevation.PixelBuffer.AsStream();
            await stream.WriteAsync(pixelData, 0, pixelData.Length);

            stream.Flush();
            return(writeableBitmapElevation);
        }
Example #24
0
        protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo)
        {
            base.OnRenderSizeChanged(sizeInfo);

            Rectangle ClientRectangle = new Rectangle(0, 0, (int)RenderSize.Width, (int)RenderSize.Height);

            if (ClientRectangle.Width <= AxisMargin || ClientRectangle.Height <= AxisMargin)
            {
                return;
            }

            if (!_initialized)
            {
                _powerSpectrum = new byte[ClientRectangle.Width - 2 * AxisMargin];
                _temp          = new byte[_powerSpectrum.Length];
                _buffer        = new Bitmap(ClientRectangle.Width, ClientRectangle.Height, PixelFormat.Format32bppPArgb);
                _buffer2       = new Bitmap(ClientRectangle.Width, ClientRectangle.Height, PixelFormat.Format32bppPArgb);
                _graphics      = Graphics.FromImage(_buffer);
                _graphics2     = Graphics.FromImage(_buffer2);
                _gradientBrush = new LinearGradientBrush(new Rectangle(AxisMargin / 2, AxisMargin / 2, ClientRectangle.Width - AxisMargin / 2, ClientRectangle.Height - AxisMargin / 2), Color.White, Color.Black, LinearGradientMode.Vertical);
                _gradientBrush.InterpolationColors = _gradientColorBlend;
                _writeableBitmap = new WriteableBitmap(ClientRectangle.Width, ClientRectangle.Height, _buffer.HorizontalResolution, _buffer.VerticalResolution, System.Windows.Media.PixelFormats.Bgr32, null);
                _initialized     = true;

                ApplyZoom();
            }
            else
            {
                var temp = new byte[ClientRectangle.Width - 2 * AxisMargin];
                Fourier.SmoothCopy(_powerSpectrum, temp, _powerSpectrum.Length, (_temp.Length + temp.Length) / (float)_temp.Length, 0);
                _powerSpectrum = temp;
                _temp          = new byte[_powerSpectrum.Length];

                var oldBuffer = _buffer;
                _buffer = new Bitmap(ClientRectangle.Width, ClientRectangle.Height, PixelFormat.Format32bppPArgb);
                var oldBuffer2 = _buffer2;
                _buffer2 = new Bitmap(ClientRectangle.Width, ClientRectangle.Height, PixelFormat.Format32bppPArgb);

                _writeableBitmap = new WriteableBitmap(ClientRectangle.Width, ClientRectangle.Height, _buffer.HorizontalResolution, _buffer.VerticalResolution, System.Windows.Media.PixelFormats.Bgr32, null);

                _graphics.Dispose();
                _graphics = Graphics.FromImage(_buffer);
                ConfigureGraphics(_graphics);

                _graphics2.Dispose();
                _graphics2 = Graphics.FromImage(_buffer2);
                ConfigureGraphics(_graphics2);

                _graphics.Clear(Color.Black);
                var rect = new Rectangle(AxisMargin, 0, _buffer.Width - 2 * AxisMargin, _buffer.Height);
                _graphics.DrawImage(oldBuffer, rect, AxisMargin, 0, oldBuffer.Width - 2 * AxisMargin, oldBuffer.Height, GraphicsUnit.Pixel);
                oldBuffer.Dispose();
                oldBuffer2.Dispose();
                if (_spectrumWidth > 0)
                {
                    _xIncrement = _scale * (ClientRectangle.Width - 2 * AxisMargin) / _spectrumWidth;
                }
                _gradientBrush.Dispose();
                _gradientBrush  = new LinearGradientBrush(new Rectangle(AxisMargin / 2, AxisMargin / 2, ClientRectangle.Width - AxisMargin / 2, ClientRectangle.Height - AxisMargin / 2), Color.White, Color.Black, LinearGradientMode.Vertical);
                _gradientPixels = null;
                _gradientBrush.InterpolationColors = _gradientColorBlend;
            }

            GC.Collect();

            DrawGradient();
            BuildGradientVector();
            _performNeeded = true;
            var oldMouseIn = _mouseIn;

            _mouseIn = true;
            Perform();
            _mouseIn = oldMouseIn;
        }
Example #25
0
        /// <summary>
        /// Handles the OrientationChanged event.
        /// </summary>
        /// <param name="sender">Event source.</param>
        /// <param name="e">Event arguments.</param>
        private void HandleOrientationChanged(object sender, OrientationChangedEventArgs e)
        {
            // Stop/complete Storyboard in case it's active
            _storyboard.Stop();
            HandleStoryboardCompleted(null, null);

            if (IsAnimationEnabled)
            {
                // Capture device width/height
                var actualWidth  = ActualWidth;
                var actualHeight = ActualHeight;

                // Get "before" width/height
                bool normal = PageOrientation.Portrait == (PageOrientation.Portrait & _previousOrientation);
                var  width  = normal ? actualWidth : actualHeight;
                var  height = normal ? actualHeight : actualWidth;

                // Capture "before" visuals in a WriteableBitmap
                var writeableBitmap = new WriteableBitmap((int)width, (int)height);
                writeableBitmap.Render(this, null);
                writeableBitmap.Invalidate();

                // Create transforms for "before" content
                var beforeTranslateTransform = new TranslateTransform();
                var beforeRotateTransform    = new RotateTransform {
                    CenterX = actualWidth / 2, CenterY = actualHeight / 2
                };
                var beforeTransforms = new TransformGroup();
                beforeTransforms.Children.Add(beforeTranslateTransform);
                beforeTransforms.Children.Add(beforeRotateTransform);

                // Configure transforms for "before" content
                var translateDelta = (actualHeight - actualWidth) / 2;
                var beforeAngle    = 0.0;
                if (PageOrientation.LandscapeLeft == _previousOrientation)
                {
                    beforeAngle = -90;
                    beforeTranslateTransform.X = -translateDelta;
                    beforeTranslateTransform.Y = translateDelta;
                }
                else if (PageOrientation.LandscapeRight == _previousOrientation)
                {
                    beforeAngle = 90;
                    beforeTranslateTransform.X = -translateDelta;
                    beforeTranslateTransform.Y = translateDelta;
                }
                beforeRotateTransform.Angle = -beforeAngle;

                // Configure for "after" content
                var afterAngle = 0.0;
                if (PageOrientation.LandscapeLeft == e.Orientation)
                {
                    afterAngle = -90;
                }
                else if (PageOrientation.LandscapeRight == e.Orientation)
                {
                    afterAngle = 90;
                }
                _afterRotateTransform.CenterX = actualWidth / 2;
                _afterRotateTransform.CenterY = actualHeight / 2;

                // Create content with default background and WriteableBitmap overlay for "before"
                var container = new Grid
                {
                    Width            = width,
                    Height           = height,
                    Background       = (Brush)Application.Current.Resources["PhoneBackgroundBrush"],
                    RenderTransform  = beforeTransforms,
                    IsHitTestVisible = false,
                };
                var content = new Rectangle
                {
                    Fill = new ImageBrush
                    {
                        ImageSource = writeableBitmap,
                        Stretch     = Stretch.None,
                    }
                };
                container.Children.Add(content);

                // Configure Popup for displaying "before" content
                //_popup.Child = container;
                //_popup.IsOpen = true;

                _popup = container;
                Application.Current.GetFrame().OverlayGrid.Children.Add(_popup);

                // Update animations to fade from "before" to "after"
                Storyboard.SetTarget(_beforeOpacityAnimation, container);
                _beforeOpacityAnimation.Duration       = Duration;
                _beforeOpacityAnimation.EasingFunction = EasingFunction;
                Storyboard.SetTarget(_afterOpacityAnimation, this);
                _afterOpacityAnimation.Duration       = Duration;
                _afterOpacityAnimation.EasingFunction = EasingFunction;

                // Update animations to rotate from "before" to "after"
                Storyboard.SetTarget(_beforeRotationAnimation, beforeRotateTransform);
                _beforeRotationAnimation.From           = beforeRotateTransform.Angle;
                _beforeRotationAnimation.To             = _beforeRotationAnimation.From + (beforeAngle - afterAngle);
                _beforeRotationAnimation.Duration       = Duration;
                _beforeRotationAnimation.EasingFunction = EasingFunction;
                Storyboard.SetTarget(_afterRotationAnimation, _afterRotateTransform);
                _afterRotationAnimation.From           = -(beforeAngle - afterAngle);
                _afterRotationAnimation.To             = 0;
                _afterRotationAnimation.Duration       = Duration;
                _afterRotationAnimation.EasingFunction = EasingFunction;

                container.CacheMode = new BitmapCache();

                // Play the animations
                _storyboard.Begin();
            }

            // Save current orientation for next time
            _previousOrientation = e.Orientation;
        }
        public override BitmapSource CreateBitmap()
        {
            Bitmap = new WriteableBitmap(Width, Height, 96, 96, PixelFormat, null);

            return(Bitmap);
        }
Example #27
0
        public void Add(string key, ImageInformation imageInformation, WriteableBitmap bitmap)
        {
            var weakRef = new WeakReference <WriteableBitmap>(bitmap);

            _reusableBitmaps.TryAdd(key, new Tuple <WeakReference <WriteableBitmap>, ImageInformation>(weakRef, imageInformation));
        }
        private const byte TOP = 8;    // 1000

        /// <summary>
        /// Draws a line using a pen / stamp for the line 
        /// </summary>
        /// <param name="bmp">The WriteableBitmap containing the pixels as int RGBA value.</param>
        /// <param name="w">The width of one scanline in the pixels array.</param>
        /// <param name="h">The height of the bitmap.</param>
        /// <param name="x1">The x-coordinate of the start point.</param>
        /// <param name="y1">The y-coordinate of the start point.</param>
        /// <param name="x2">The x-coordinate of the end point.</param>
        /// <param name="y2">The y-coordinate of the end point.</param>
        /// <param name="penBmp">The pen bitmap.</param>
        public static void DrawLinePenned(this WriteableBitmap bmp, int x1, int y1, int x2, int y2, WriteableBitmap penBmp)
        {
            using (var context = bmp.GetBitmapContext())
            {
                using (var penContext = penBmp.GetBitmapContext())
                {
                    DrawLinePenned(context, bmp.PixelWidth, bmp.PixelHeight, x1, y1, x2, y2, penContext);
                }
            }
        }
Example #29
0
        public static WriteableBitmap ResizeImageToFullPage(Stream stream)
        {
            var rootVisual = Application.Current.RootVisual as PhoneApplicationFrame;

            //turn stream into bitmapimage object
            BitmapImage bitmapImage = new BitmapImage();

            bitmapImage.SetSource(stream);

            //calculate bounding box
            int    iOriginalWidth  = bitmapImage.PixelWidth;
            int    iOriginalHeight = bitmapImage.PixelHeight;
            double ratio;

            // Tall image
            if (iOriginalHeight > iOriginalWidth)
            {
                ratio = (double)rootVisual.ActualWidth / (double)iOriginalWidth;

                double newWidth  = rootVisual.ActualWidth;
                double newHeight = iOriginalHeight * ratio;

                //generate temporary control to render image
                Image temporaryImage = new Image {
                    Source = bitmapImage, Width = newWidth, Height = newHeight
                };

                //create writeablebitmap
                WriteableBitmap wb = new WriteableBitmap((int)newWidth, (int)Math.Round(newHeight, 0));
                wb.Render(temporaryImage, new TranslateTransform {
                    X = 0, Y = 0
                });
                wb.Invalidate();

                //get stream from writeablebitmap
                Stream streamResizedImage = new MemoryStream(); //will need to be disposed by whatever is using this method
                wb.SaveJpeg(streamResizedImage, (int)Math.Round(newWidth, 0), (int)Math.Round(newHeight, 0), 0, 70);
                return(wb);
            }
            else
            {
                ratio = (double)rootVisual.ActualHeight / (double)iOriginalHeight;

                double newHeight = rootVisual.ActualHeight;
                double newWidth  = iOriginalWidth * ratio;

                //generate temporary control to render image
                Image temporaryImage = new Image {
                    Source = bitmapImage, Width = newWidth, Height = newHeight
                };

                //create writeablebitmap
                WriteableBitmap wb = new WriteableBitmap((int)newWidth, (int)Math.Round(newHeight, 0));
                wb.Render(temporaryImage, new TranslateTransform {
                    X = 0, Y = 0
                });
                wb.Invalidate();

                //get stream from writeablebitmap
                Stream streamResizedImage = new MemoryStream(); //will need to be disposed by whatever is using this method
                wb.SaveJpeg(streamResizedImage, (int)Math.Round(newWidth, 0), (int)Math.Round(newHeight, 0), 0, 70);
                return(wb);
            }
        }
Example #30
0
        public static WriteableBitmap ToBitmap(this Mat mat)
        {
            var dataCount = mat.Width * mat.Height;

            var writableBitmap = new WriteableBitmap(new PixelSize(mat.Width, mat.Height), new Vector(96, 96),
                                                     PixelFormat.Bgra8888, AlphaFormat.Unpremul);



            using var lockBuffer = writableBitmap.Lock();



            unsafe
            {
                var targetPixels = (uint *)(void *)lockBuffer.Address;
                switch (mat.NumberOfChannels)
                {
                //Stopwatch sw = Stopwatch.StartNew();
                // Method 1 (Span copy)
                case 1:
                    var srcPixels1 = (byte *)(void *)mat.DataPointer;
                    for (var i = 0; i < dataCount; i++)
                    {
                        var color = srcPixels1[i];
                        targetPixels[i] = (uint)(color | color << 8 | color << 16 | 0xff << 24);
                    }

                    break;

                case 3:
                    var  srcPixels2 = (byte *)(void *)mat.DataPointer;
                    uint pixel      = 0;
                    for (uint i = 0; i < dataCount; i++)
                    {
                        targetPixels[i] = (uint)(srcPixels2[pixel++] | srcPixels2[pixel++] << 8 | srcPixels2[pixel++] << 16 | 0xff << 24);
                    }

                    break;

                case 4:

                    if (mat.Depth == DepthType.Cv8U)
                    {
                        var  srcPixels4 = (byte *)(void *)mat.DataPointer;
                        uint pixel4     = 0;
                        for (uint i = 0; i < dataCount; i++)
                        {
                            targetPixels[i] = (uint)(srcPixels4[pixel4++] | srcPixels4[pixel4++] << 8 | srcPixels4[pixel4++] << 16 | srcPixels4[pixel4++] << 24);
                        }
                    }
                    else if (mat.Depth == DepthType.Cv32S)
                    {
                        var srcPixels4 = (uint *)(void *)mat.DataPointer;
                        for (uint i = 0; i < dataCount; i++)
                        {
                            targetPixels[i] = srcPixels4[i];
                        }
                    }

                    break;
                }
            }

            return(writableBitmap);

            /*Debug.WriteLine($"Method 1 (Span copy): {sw.ElapsedMilliseconds}ms");
             *
             * // Method 2 (OpenCV Convertion + Copy Marshal)
             * sw.Restart();
             * CvInvoke.CvtColor(mat, target, ColorConversion.Bgr2Bgra);
             * var buffer = target.GetBytes();
             * Marshal.Copy(buffer, 0, lockBuffer.Address, buffer.Length);
             * Debug.WriteLine($"Method 2 (OpenCV Convertion + Copy Marshal): {sw.ElapsedMilliseconds}ms");
             *
             *
             * //sw.Restart();
             * CvInvoke.CvtColor(mat, target, ColorConversion.Bgr2Bgra);
             * unsafe
             * {
             *  var srcAddress = (uint*)(void*)target.DataPointer;
             *  var targetAddress = (uint*)(void*)lockBuffer.Address;
             * targetAddress = *srcAddress;
             * }
             * //Debug.WriteLine($"Method 3 (OpenCV Convertion + Set Address): {sw.ElapsedMilliseconds}ms");
             *
             * return writableBitmap;
             */
            /* for (var y = 0; y < mat.Height; y++)
             *  {
             *      Marshal.Copy(buffer, y * lockBuffer.RowBytes, new IntPtr(lockBuffer.Address.ToInt64() + y * lockBuffer.RowBytes), lockBuffer.RowBytes);
             *  }*/
        }
Example #31
0
 private void WriteToBitmap <T>(WriteableBitmap bmp, T[] buffer, int componets = 3)
 {
     bmp.Lock();
     bmp.WritePixels(new Int32Rect(0, 0, _imgWidth, _imgHeight), buffer, _imgWidth * componets, 0);
     bmp.Unlock();
 }
Example #32
0
 public static int GetStep(this WriteableBitmap bitmap)
 => (int)bitmap.Size.Width;
		private static async Task<Stream> resizeImageStream(IRandomAccessStream imageStream, int maxWidth, int maxHeight)
		#endif
		{
			#if WINDOWS_PHONE
			var image = new BitmapImage();
			image.CreateOptions = BitmapCreateOptions.None;
			image.SetSource(imageStream);

			var scaledStream = new MemoryStream();
			var newImage = new WriteableBitmap(image);
			Vector2 newSize;
			if (image.PixelWidth > maxWidth || image.PixelHeight > maxHeight) newSize = Reign.MathUtilities.FitInViewIfLarger(newImage.PixelWidth, newImage.PixelHeight, maxWidth, maxHeight);
			else newSize = new Vector2(image.PixelWidth, image.PixelHeight);
			newImage.SaveJpeg(scaledStream, (int)newSize.x, (int)newSize.y, 0, 95);
			scaledStream.Position = 0;

			return scaledStream;
			#else
			var decoder = await BitmapDecoder.CreateAsync(imageStream);
								
			var newStream = new InMemoryRandomAccessStream();
			var encoder = await BitmapEncoder.CreateForTranscodingAsync(newStream, decoder);
			Vector2 newSize;
			if (decoder.PixelWidth > maxWidth || decoder.PixelHeight > maxHeight) newSize = Reign.MathUtilities.FitInViewIfLarger(decoder.PixelWidth, decoder.PixelHeight, maxWidth, maxHeight);
			else newSize = new Vector2(decoder.PixelWidth, decoder.PixelHeight);
			encoder.BitmapTransform.ScaledWidth = (uint)newSize.x;
			encoder.BitmapTransform.ScaledHeight = (uint)newSize.y;
			await encoder.FlushAsync();

			return newStream.AsStream();
			#endif
		}
Example #34
0
 /// <summary>
 /// Gets the total length of this <see cref="WriteableBitmap"/></param>
 /// </summary>
 /// <param name="bitmap"></param>
 /// <returns>The total length of this <see cref="WriteableBitmap"/></returns>
 public static int GetLength(this WriteableBitmap bitmap)
 => (int)(bitmap.Size.Width * bitmap.Size.Height);
Example #35
0
        virtual public void testBlackBox()
        {
            Assert.IsFalse(testResults.Count == 0);

            IEnumerable <string> imageFiles = getImageFiles();
            int testCount = testResults.Count;

            int[] passedCounts           = new int[testCount];
            int[] misreadCounts          = new int[testCount];
            int[] tryHarderCounts        = new int[testCount];
            int[] tryHarderMisreadCounts = new int[testCount];

            foreach (var testImage in imageFiles)
            {
                var absPath = Path.GetFullPath(testImage);
                Log.InfoFormat("Starting {0}", absPath);

#if !SILVERLIGHT
                var image = new Bitmap(Image.FromFile(testImage));
#else
                var image = new WriteableBitmap(0, 0);
                image.SetSource(File.OpenRead(testImage));
#endif

                String expectedText;
                String expectedTextFile = Path.Combine(Path.GetDirectoryName(absPath), Path.GetFileNameWithoutExtension(absPath) + ".txt");
                if (File.Exists(expectedTextFile))
                {
                    expectedText = File.ReadAllText(expectedTextFile, System.Text.Encoding.UTF8);
                }
                else
                {
                    String expectedBinFile = Path.Combine(Path.GetDirectoryName(absPath), Path.GetFileNameWithoutExtension(absPath) + ".bin");
                    if (File.Exists(expectedBinFile))
                    {
                        // it is only a dirty workaround for some special cases
                        expectedText = File.ReadAllText(expectedBinFile, System.Text.Encoding.GetEncoding("ISO8859-1"));
                    }
                    else
                    {
                        throw new InvalidOperationException("Missing expected result file: " + expectedTextFile);
                    }
                }

                String expectedMetadataFile = Path.Combine(Path.GetDirectoryName(absPath), Path.GetFileNameWithoutExtension(absPath) + ".metadata.txt");
                var    expectedMetadata     = new Dictionary <string, string>();
                if (File.Exists(expectedMetadataFile))
                {
                    foreach (var row in File.ReadLines(expectedMetadataFile))
                    {
                        expectedMetadata.Add(row.Split('=')[0], string.Join("=", row.Split('=').Skip(1).ToArray()));
                    }
                }

                for (int x = 0; x < testCount; x++)
                {
                    var             testResult   = testResults[x];
                    float           rotation     = testResult.Rotation;
                    var             rotatedImage = rotateImage(image, rotation);
                    LuminanceSource source       = new BitmapLuminanceSource(rotatedImage);
                    BinaryBitmap    bitmap       = new BinaryBitmap(new HybridBinarizer(source));
                    try
                    {
                        if (decode(bitmap, rotation, expectedText, expectedMetadata, false))
                        {
                            passedCounts[x]++;
                            Log.Info("   without try-hard ... ok.");
                        }
                        else
                        {
                            misreadCounts[x]++;
                            Log.Info("   without try-hard ... fail.");
                        }
                    }
                    catch (ReaderException)
                    {
                        // continue
                        Log.Info("   without try-hard ... fail (exc).");
                    }
                    try
                    {
                        if (decode(bitmap, rotation, expectedText, expectedMetadata, true))
                        {
                            tryHarderCounts[x]++;
                            Log.Info("   with try-hard ... ok.");
                        }
                        else
                        {
                            tryHarderMisreadCounts[x]++;
                            Log.Info("   with try-hard ... fail.");
                        }
                    }
                    catch (ReaderException)
                    {
                        // continue
                        Log.Info("   with try-hard ... fail (exc).");
                    }
                }
            }

            // Print the results of all tests first
            int totalFound      = 0;
            int totalMustPass   = 0;
            int totalMisread    = 0;
            int totalMaxMisread = 0;
            var imageFilesCount = imageFiles.Count();
            for (int x = 0; x < testResults.Count; x++)
            {
                TestResult testResult = testResults[x];
                Log.InfoFormat("Rotation {0} degrees:", (int)testResult.Rotation);
                Log.InfoFormat(" {0} of {1} images passed ({2} required)",
                               passedCounts[x], imageFilesCount, testResult.MustPassCount);
                int failed = imageFilesCount - passedCounts[x];
                Log.InfoFormat(" {0} failed due to misreads, {1} not detected",
                               misreadCounts[x], failed - misreadCounts[x]);
                Log.InfoFormat(" {0} of {1} images passed with try harder ({2} required)",
                               tryHarderCounts[x], imageFilesCount, testResult.TryHarderCount);
                failed = imageFilesCount - tryHarderCounts[x];
                Log.InfoFormat(" {0} failed due to misreads, {1} not detected",
                               tryHarderMisreadCounts[x], failed - tryHarderMisreadCounts[x]);
                totalFound      += passedCounts[x] + tryHarderCounts[x];
                totalMustPass   += testResult.MustPassCount + testResult.TryHarderCount;
                totalMisread    += misreadCounts[x] + tryHarderMisreadCounts[x];
                totalMaxMisread += testResult.MaxMisreads + testResult.MaxTryHarderMisreads;
            }

            int totalTests = imageFilesCount * testCount * 2;
            Log.InfoFormat("Decoded {0} images out of {1} ({2}%, {3} required)",
                           totalFound, totalTests, totalFound * 100 / totalTests, totalMustPass);
            if (totalFound > totalMustPass)
            {
                Log.WarnFormat("+++ Test too lax by {0} images", totalFound - totalMustPass);
            }
            else if (totalFound < totalMustPass)
            {
                Log.WarnFormat("--- Test failed by {0} images", totalMustPass - totalFound);
            }

            if (totalMisread < totalMaxMisread)
            {
                Log.WarnFormat("+++ Test expects too many misreads by {0} images", totalMaxMisread - totalMisread);
            }
            else if (totalMisread > totalMaxMisread)
            {
                Log.WarnFormat("--- Test had too many misreads by {0} images", totalMisread - totalMaxMisread);
            }

            // Then run through again and assert if any failed
            for (int x = 0; x < testCount; x++)
            {
                TestResult testResult = testResults[x];
                String     label      = "Rotation " + testResult.Rotation + " degrees: Too many images failed";
                Assert.IsTrue(passedCounts[x] >= testResult.MustPassCount, label);
                Assert.IsTrue(tryHarderCounts[x] >= testResult.TryHarderCount, "Try harder, " + label);
                label = "Rotation " + testResult.Rotation + " degrees: Too many images misread";
                Assert.IsTrue(misreadCounts[x] <= testResult.MaxMisreads, label);
                Assert.IsTrue(tryHarderMisreadCounts[x] <= testResult.MaxTryHarderMisreads, "Try harder, " + label);
            }
        }
Example #36
0
 public static int GetPixelPos(this WriteableBitmap bitmap, int x, int y)
 => (int)(bitmap.Size.Width * y + x);
 /// <summary>
 /// `Used for creating UIElement for rendering this segment. This method is not
 /// intended to be called explicitly outside the Chart but it can be overriden by
 /// any derived class.
 /// </summary>
 /// <param name="size">Size of the panel</param>
 /// <returns>retuns UIElement</returns>
 public override UIElement CreateVisual(Size size)
 {
     bitmap     = fastSeries.Area.GetFastRenderSurface();
     fastBuffer = fastSeries.Area.GetFastBuffer();
     return(null);
 }
Example #38
0
 public static int GetPixelPos(this WriteableBitmap bitmap, System.Drawing.Point location) =>
 bitmap.GetPixelPos(location.X, location.Y);
        /// <summary>
        /// Draws a rectangle.
        /// x2 has to be greater than x1 and y2 has to be greater than y1.
        /// </summary>
        /// <param name="bmp">The WriteableBitmap.</param>
        /// <param name="x1">The x-coordinate of the bounding rectangle's left side.</param>
        /// <param name="y1">The y-coordinate of the bounding rectangle's top side.</param>
        /// <param name="x2">The x-coordinate of the bounding rectangle's right side.</param>
        /// <param name="y2">The y-coordinate of the bounding rectangle's bottom side.</param>
        /// <param name="color">The color.</param>
        public static void DrawRectangle(this WriteableBitmap bmp, int x1, int y1, int x2, int y2, Color color)
        {
            var col = ConvertColor(color);

            bmp.DrawRectangle(x1, y1, x2, y2, col);
        }
Example #40
0
 /// <summary>
 /// Gets a single pixel span to manipulate or read pixels
 /// </summary>
 /// <typeparam name="T">Pixel type</typeparam>
 /// <param name="mat"><see cref="Mat"/> Input</param>
 /// <returns>A <see cref="Span{T}"/> containing all pixels in data memory</returns>
 public static unsafe Span <uint> GetPixelSpan(this WriteableBitmap bitmap)
 {
     using var l = bitmap.Lock();
     return(new Span <uint>(l.Address.ToPointer(), bitmap.GetLength()));
 }
        /// <summary>
        /// Copies (blits) the pixels from the WriteableBitmap source to the destination WriteableBitmap (this).
        /// </summary>
        /// <param name="bmp">The destination WriteableBitmap.</param>
        /// <param name="destRect">The rectangle that defines the destination region.</param>
        /// <param name="source">The source WriteableBitmap.</param>
        /// <param name="sourceRect">The rectangle that will be copied from the source to the destination.</param>
        /// <param name="color">If not Colors.White, will tint the source image. A partially transparent color and the image will be drawn partially transparent. If the BlendMode is ColorKeying, this color will be used as color key to mask all pixels with this value out.</param>
        /// <param name="blendMode">The blending mode <see cref="BlendMode"/>.</param>
        internal static void Blit(this WriteableBitmap bmp, Rect destRect, WriteableBitmap source, Rect sourceRect, Color color, BlendMode blendMode)
        {
            if (color.A == 0)
            {
                return;
            }
#if WPF
            var isPrgba = source.Format == PixelFormats.Pbgra32 || source.Format == PixelFormats.Prgba64 || source.Format == PixelFormats.Prgba128Float;
#endif
            var dw = (int)destRect.Width;
            var dh = (int)destRect.Height;

            using (var srcContext = source.GetBitmapContext(ReadWriteMode.ReadOnly))
            {
                using (var destContext = bmp.GetBitmapContext())
                {
                    var sourceWidth = srcContext.Width;
                    var dpw = destContext.Width;
                    var dph = destContext.Height;

                    var intersect = new Rect(0, 0, dpw, dph);
                    intersect.Intersect(destRect);
                    if (intersect.IsEmpty)
                    {
                        return;
                    }

                    var sourcePixels = srcContext.Pixels;
                    var destPixels = destContext.Pixels;
                    var sourceLength = srcContext.Length;

                    int sourceIdx = -1;
                    int px = (int)destRect.X;
                    int py = (int)destRect.Y;

                    int x;
                    int y;
                    int idx;
                    double ii;
                    double jj;
                    int sr = 0;
                    int sg = 0;
                    int sb = 0;
                    int dr, dg, db;
                    int sourcePixel;
                    int sa = 0;
                    int da;
                    int ca = color.A;
                    int cr = color.R;
                    int cg = color.G;
                    int cb = color.B;
                    bool tinted = color != Colors.White;
                    var sw = (int)sourceRect.Width;
                    var sdx = sourceRect.Width / destRect.Width;
                    var sdy = sourceRect.Height / destRect.Height;
                    int sourceStartX = (int)sourceRect.X;
                    int sourceStartY = (int)sourceRect.Y;
                    int lastii, lastjj;
                    lastii = -1;
                    lastjj = -1;
                    jj = sourceStartY;
                    y = py;
                    for (int j = 0; j < dh; j++)
                    {
                        if (y >= 0 && y < dph)
                        {
                            ii = sourceStartX;
                            idx = px + y * dpw;
                            x = px;
                            sourcePixel = sourcePixels[0];

                            // Scanline BlockCopy is much faster (3.5x) if no tinting and blending is needed,
                            // even for smaller sprites like the 32x32 particles. 
                            if (blendMode == BlendMode.None && !tinted)
                            {
                                sourceIdx = (int)ii + (int)jj * sourceWidth;
                                var offset = x < 0 ? -x : 0;
                                var xx = x + offset;
                                var wx = sourceWidth - offset;
                                var len = xx + wx < dpw ? wx : dpw - xx;
                                if (len > sw) len = sw;
                                if (len > dw) len = dw;
                                BitmapContext.BlockCopy(srcContext, (sourceIdx + offset) * 4, destContext, (idx + offset) * 4, len * 4);
                            }

                     // Pixel by pixel copying
                            else
                            {
                                for (int i = 0; i < dw; i++)
                                {
                                    if (x >= 0 && x < dpw)
                                    {
                                        if ((int)ii != lastii || (int)jj != lastjj)
                                        {
                                            sourceIdx = (int)ii + (int)jj * sourceWidth;
                                            if (sourceIdx >= 0 && sourceIdx < sourceLength)
                                            {
                                                sourcePixel = sourcePixels[sourceIdx];
                                                sa = ((sourcePixel >> 24) & 0xff);
                                                sr = ((sourcePixel >> 16) & 0xff);
                                                sg = ((sourcePixel >> 8) & 0xff);
                                                sb = ((sourcePixel) & 0xff);
                                                if (tinted && sa != 0)
                                                {
                                                    sa = (((sa * ca) * 0x8081) >> 23);
                                                    sr = ((((((sr * cr) * 0x8081) >> 23) * ca) * 0x8081) >> 23);
                                                    sg = ((((((sg * cg) * 0x8081) >> 23) * ca) * 0x8081) >> 23);
                                                    sb = ((((((sb * cb) * 0x8081) >> 23) * ca) * 0x8081) >> 23);
                                                    sourcePixel = (sa << 24) | (sr << 16) | (sg << 8) | sb;
                                                }
                                            }
                                            else
                                            {
                                                sa = 0;
                                            }
                                        }
                                        if (blendMode == BlendMode.None)
                                        {
                                            destPixels[idx] = sourcePixel;
                                        }
                                        else if (blendMode == BlendMode.ColorKeying)
                                        {
                                            sr = ((sourcePixel >> 16) & 0xff);
                                            sg = ((sourcePixel >> 8) & 0xff);
                                            sb = ((sourcePixel) & 0xff);

                                            if (sr != color.R || sg != color.G || sb != color.B)
                                            {
                                                destPixels[idx] = sourcePixel;
                                            }

                                        }
                                        else if (blendMode == BlendMode.Mask)
                                        {
                                            int destPixel = destPixels[idx];
                                            da = ((destPixel >> 24) & 0xff);
                                            dr = ((destPixel >> 16) & 0xff);
                                            dg = ((destPixel >> 8) & 0xff);
                                            db = ((destPixel) & 0xff);
                                            destPixel = ((((da * sa) * 0x8081) >> 23) << 24) |
                                                        ((((dr * sa) * 0x8081) >> 23) << 16) |
                                                        ((((dg * sa) * 0x8081) >> 23) << 8) |
                                                        ((((db * sa) * 0x8081) >> 23));
                                            destPixels[idx] = destPixel;
                                        }
                                        else if (sa > 0)
                                        {
                                            int destPixel = destPixels[idx];
                                            da = ((destPixel >> 24) & 0xff);
                                            if ((sa == 255 || da == 0) &&
                                                           blendMode != BlendMode.Additive
                                                           && blendMode != BlendMode.Subtractive
                                                           && blendMode != BlendMode.Multiply
                                               )
                                            {
                                                destPixels[idx] = sourcePixel;
                                            }
                                            else
                                            {
                                                dr = ((destPixel >> 16) & 0xff);
                                                dg = ((destPixel >> 8) & 0xff);
                                                db = ((destPixel) & 0xff);
                                                if (blendMode == BlendMode.Alpha)
                                                {
                                                    var isa = 255 - sa;
#if NETFX_CORE
                                                     // Special case for WinRT since it does not use pARGB (pre-multiplied alpha)
                                                     destPixel = ((da & 0xff) << 24) |
                                                                 ((((sr * sa + isa * dr) >> 8) & 0xff) << 16) |
                                                                 ((((sg * sa + isa * dg) >> 8) & 0xff) <<  8) |
                                                                  (((sb * sa + isa * db) >> 8) & 0xff);
#elif WPF
                                                    if (isPrgba)
                                                    {
                                                        destPixel = ((da & 0xff) << 24) |
                                                                    (((((sr << 8) + isa * dr) >> 8) & 0xff) << 16) |
                                                                    (((((sg << 8) + isa * dg) >> 8) & 0xff) <<  8) |
                                                                     ((((sb << 8) + isa * db) >> 8) & 0xff);
                                                    }
                                                    else
                                                    {
                                                        destPixel = ((da & 0xff) << 24) |
                                                                    (((((sr * sa) + isa * dr) >> 8) & 0xff) << 16) |
                                                                    (((((sg * sa) + isa * dg) >> 8) & 0xff) <<  8) |
                                                                     ((((sb * sa) + isa * db) >> 8) & 0xff);
                                                    }
#else
                                                        destPixel = ((da & 0xff) << 24) |
                                                                    (((((sr << 8) + isa * dr) >> 8) & 0xff) << 16) |
                                                                    (((((sg << 8) + isa * dg) >> 8) & 0xff) <<  8) |
                                                                     ((((sb << 8) + isa * db) >> 8) & 0xff);
#endif
                                                }
                                                else if (blendMode == BlendMode.Additive)
                                                {
                                                    int a = (255 <= sa + da) ? 255 : (sa + da);
                                                    destPixel = (a << 24) |
                                                       (((a <= sr + dr) ? a : (sr + dr)) << 16) |
                                                       (((a <= sg + dg) ? a : (sg + dg)) << 8) |
                                                       (((a <= sb + db) ? a : (sb + db)));
                                                }
                                                else if (blendMode == BlendMode.Subtractive)
                                                {
                                                    int a = da;
                                                    destPixel = (a << 24) |
                                                       (((sr >= dr) ? 0 : (sr - dr)) << 16) |
                                                       (((sg >= dg) ? 0 : (sg - dg)) << 8) |
                                                       (((sb >= db) ? 0 : (sb - db)));
                                                }
                                                else if (blendMode == BlendMode.Multiply)
                                                {
                                                    // Faster than a division like (s * d) / 255 are 2 shifts and 2 adds
                                                    int ta = (sa * da) + 128;
                                                    int tr = (sr * dr) + 128;
                                                    int tg = (sg * dg) + 128;
                                                    int tb = (sb * db) + 128;

                                                    int ba = ((ta >> 8) + ta) >> 8;
                                                    int br = ((tr >> 8) + tr) >> 8;
                                                    int bg = ((tg >> 8) + tg) >> 8;
                                                    int bb = ((tb >> 8) + tb) >> 8;

                                                    destPixel = (ba << 24) |
                                                                ((ba <= br ? ba : br) << 16) |
                                                                ((ba <= bg ? ba : bg) << 8) |
                                                                ((ba <= bb ? ba : bb));
                                                }

                                                destPixels[idx] = destPixel;
                                            }
                                        }
                                    }
                                    x++;
                                    idx++;
                                    ii += sdx;
                                }
                            }
                        }
                        jj += sdy;
                        y++;
                    }
                }
            }
        }
        /// <summary>
        /// Creates a new resized WriteableBitmap.
        /// </summary>
        /// <param name="bmp">The WriteableBitmap.</param>
        /// <param name="width">The new desired width.</param>
        /// <param name="height">The new desired height.</param>
        /// <param name="interpolation">The interpolation method that should be used.</param>
        /// <returns>A new WriteableBitmap that is a resized version of the input.</returns>
        public static WriteableBitmap Resize(this WriteableBitmap bmp, int width, int height,
            Interpolation interpolation)
        {
            // Init vars
            int ws = bmp.PixelWidth;
            int hs = bmp.PixelHeight;
            #if SILVERLIGHT
             var ps = bmp.Pixels;
             var result = new WriteableBitmap(width, height);
             var pd = result.Pixels;
            #else
            bmp.Lock();
            var result = new WriteableBitmap(width, height, 96.0, 96.0, PixelFormats.Bgra32, null);
            result.Lock();
            unsafe
            {
                var ps = (int*) bmp.BackBuffer;
                var pd = (int*) result.BackBuffer;
            #endif
                float xs = (float) ws/width;
                float ys = (float) hs/height;

                float fracx, fracy, ifracx, ifracy, sx, sy, l0, l1;
                int c, x0, x1, y0, y1;
                byte c1a, c1r, c1g, c1b, c2a, c2r, c2g, c2b, c3a, c3r, c3g, c3b, c4a, c4r, c4g, c4b;
                byte a = 0, r = 0, g = 0, b = 0;

                // Nearest Neighbor
                if (interpolation == Interpolation.NearestNeighbor)
                {
                    int srcIdx = 0;
                    for (int y = 0; y < height; y++)
                    {
                        for (int x = 0; x < width; x++)
                        {
                            sx = x*xs;
                            sy = y*ys;
                            x0 = (int) sx;
                            y0 = (int) sy;

                            pd[srcIdx++] = ps[y0*ws + x0];
                        }
                    }
                }
                    // Bilinear
                else if (interpolation == Interpolation.Bilinear)
                {
                    int srcIdx = 0;
                    for (int y = 0; y < height; y++)
                    {
                        for (int x = 0; x < width; x++)
                        {
                            sx = x*xs;
                            sy = y*ys;
                            x0 = (int) sx;
                            y0 = (int) sy;

                            // Calculate coordinates of the 4 interpolation points
                            fracx = sx - x0;
                            fracy = sy - y0;
                            ifracx = 1f - fracx;
                            ifracy = 1f - fracy;
                            x1 = x0 + 1;
                            if (x1 >= ws)
                                x1 = x0;
                            y1 = y0 + 1;
                            if (y1 >= hs)
                                y1 = y0;

                            // Read source color
                            c = ps[y0*ws + x0];
                            c1a = (byte) (c >> 24);
                            c1r = (byte) (c >> 16);
                            c1g = (byte) (c >> 8);
                            c1b = (byte) (c);

                            c = ps[y0*ws + x1];
                            c2a = (byte) (c >> 24);
                            c2r = (byte) (c >> 16);
                            c2g = (byte) (c >> 8);
                            c2b = (byte) (c);

                            c = ps[y1*ws + x0];
                            c3a = (byte) (c >> 24);
                            c3r = (byte) (c >> 16);
                            c3g = (byte) (c >> 8);
                            c3b = (byte) (c);

                            c = ps[y1*ws + x1];
                            c4a = (byte) (c >> 24);
                            c4r = (byte) (c >> 16);
                            c4g = (byte) (c >> 8);
                            c4b = (byte) (c);

                            // Calculate colors
                            // Alpha
                            l0 = ifracx*c1a + fracx*c2a;
                            l1 = ifracx*c3a + fracx*c4a;
                            a = (byte) (ifracy*l0 + fracy*l1);

                            if (a > 0)
                            {
                                // Red
                                l0 = ifracx*c1r*c1a + fracx*c2r*c2a;
                                l1 = ifracx*c3r*c3a + fracx*c4r*c4a;
                                r = (byte) ((ifracy*l0 + fracy*l1)/a);

                                // Green
                                l0 = ifracx*c1g*c1a + fracx*c2g*c2a;
                                l1 = ifracx*c3g*c3a + fracx*c4g*c4a;
                                g = (byte) ((ifracy*l0 + fracy*l1)/a);

                                // Blue
                                l0 = ifracx*c1b*c1a + fracx*c2b*c2a;
                                l1 = ifracx*c3b*c3a + fracx*c4b*c4a;
                                b = (byte) ((ifracy*l0 + fracy*l1)/a);
                            }

                            // Write destination
                            pd[srcIdx++] = (a << 24) | (r << 16) | (g << 8) | b;
                        }
                    }
                }
            #if !SILVERLIGHT
            }
            result.AddDirtyRect(new Int32Rect(0, 0, width, height));
            result.Unlock();
            bmp.Unlock();
            #endif
            return result;
        }
 /// <summary>
 /// VignettingEffect クラスの新しいインスタンスを初期化します。
 /// </summary>
 /// <param name="maskBitmap">周辺光を表現するマスク画像</param>
 /// <param name="opacity">マスク画像の不透明度を表現する(0.0~1.0 不透明:1.0)</param>
 public VignettingEffect(WriteableBitmap maskBitmap, double opacity)
 {
     MaskBitmap = maskBitmap;
     Opacity = opacity;
 }
        /// <summary>
        /// Flips (reflects the image) eiter vertical or horizontal.
        /// </summary>
        /// <param name="bmp">The WriteableBitmap.</param>
        /// <param name="flipMode">The flip mode.</param>
        /// <returns>A new WriteableBitmap that is a flipped version of the input.</returns>
        public static WriteableBitmap Flip(this WriteableBitmap bmp, FlipMode flipMode)
        {
            // Use refs for faster access (really important!) speeds up a lot!
             var w = bmp.PixelWidth;
             var h = bmp.PixelHeight;
             var p = bmp.Pixels;
             var i = 0;
             WriteableBitmap result = null;

             if (flipMode == FlipMode.Horizontal)
             {
            result = new WriteableBitmap(w, h);
            var rp = result.Pixels;
            for (var y = h - 1; y >= 0; y--)
            {
               for (var x = 0; x < w; x++)
               {
                  var srcInd = y * w + x;
                  rp[i] = p[srcInd];
                  i++;
               }
            }
             }
             else if (flipMode == FlipMode.Vertical)
             {
            result = new WriteableBitmap(w, h);
            var rp = result.Pixels;
            for (var y = 0; y < h; y++)
            {
               for (var x = w - 1; x >= 0; x--)
               {
                  var srcInd = y * w + x;
                  rp[i] = p[srcInd];
                  i++;
               }
            }
             }

             return result;
        }
Example #45
0
        private static WriteableBitmap CreateBitmap(GifDataStream metadata)
        {
            var desc = metadata.Header.LogicalScreenDescriptor;
#if WPF
            var bitmap = new WriteableBitmap(desc.Width, desc.Height, 96, 96, PixelFormats.Bgra32, null);
#elif WINRT
            var bitmap = new WriteableBitmap(desc.Width, desc.Height);
#else
            #error Not implemented
#endif
            return bitmap;
        }
Example #46
0
        async void OnOpenAppBarButtonClick(object sender, RoutedEventArgs args)
        {
            // Create FileOpenPicker
            FileOpenPicker picker = new FileOpenPicker();

            picker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;

            // Initialize with filename extensions
            IReadOnlyList <BitmapCodecInformation> codecInfos =
                BitmapDecoder.GetDecoderInformationEnumerator();

            foreach (BitmapCodecInformation codecInfo in codecInfos)
            {
                foreach (string extension in codecInfo.FileExtensions)
                {
                    picker.FileTypeFilter.Add(extension);
                }
            }

            // Get the selected file
            StorageFile storageFile = await picker.PickSingleFileAsync();

            if (storageFile == null)
            {
                return;
            }

            // Open the stream and create a decoder
            BitmapDecoder decoder = null;

            using (IRandomAccessStreamWithContentType stream = await storageFile.OpenReadAsync())
            {
                string exception = null;

                try
                {
                    decoder = await BitmapDecoder.CreateAsync(stream);
                }
                catch (Exception exc)
                {
                    exception = exc.Message;
                }

                if (exception != null)
                {
                    MessageDialog msgdlg =
                        new MessageDialog("That particular image file could not be loaded. " +
                                          "The system reports on error of: " + exception);
                    await msgdlg.ShowAsync();

                    return;
                }

                // Get the first frame
                BitmapFrame bitmapFrame = await decoder.GetFrameAsync(0);

                // Get the source pixels
                PixelDataProvider dataProvider =
                    await bitmapFrame.GetPixelDataAsync(BitmapPixelFormat.Bgra8,
                                                        BitmapAlphaMode.Premultiplied,
                                                        new BitmapTransform(),
                                                        ExifOrientationMode.RespectExifOrientation,
                                                        ColorManagementMode.ColorManageToSRgb);

                srcPixels = dataProvider.DetachPixelData();
                dstPixels = new byte[srcPixels.Length];

                // Create WriteableBitmap and set as Image source
                bitmap = new WriteableBitmap((int)bitmapFrame.PixelWidth,
                                             (int)bitmapFrame.PixelHeight);
                pixelStream  = bitmap.PixelBuffer.AsStream();
                image.Source = bitmap;

                // Update bitmap from masked pixels
                UpdateBitmap();
            }

            // Enable the Save As button
            saveAsButton.IsEnabled = true;
        }
Example #47
0
        public async Task SaveFile(StorageFile file, IList <LayerModel> ls, int x, int y)
        {
            await Dispatcher.RunIdleAsync(_ => { });

            Loading = true;
            StorageFolder f = null;

            try
            {
                f = await StorageFolder.GetFolderFromPathAsync(file.Path.Replace(file.Name, ""));
            }
            catch (Exception)
            {
            }
            try
            {
                WriteableBitmap ot = new WriteableBitmap(x, y);
                foreach (var item in ls.Reverse())
                {
                    if (!item.IsShow)
                    {
                        continue;
                    }
                    IGrap.addImg(item.Bitmap, ot, (int)item.X, (int)item.Y, item.Opacity);
                }
                switch (file.FileType.ToLower())
                {
                case ".jpg":
                    await SaveIMG(ot, file, BitmapEncoder.JpegEncoderId);

                    break;

                case ".gif":
                    await SaveIMG(ot, file, BitmapEncoder.GifEncoderId);

                    return;     //xuy

                case ".png":
                    await SaveIMG(ot, file, BitmapEncoder.PngEncoderId);

                    if (f != null)
                    {
                        file = await f.CreateFileAsync(file.Name.Replace(".png", ".psd"), CreationCollisionOption.OpenIfExists);

                        using (var s = await file.OpenStreamForWriteAsync()) SavePSD(s, ls, x, y);
                    }
                    break;

                case ".psd":
                    using (var s = await file.OpenStreamForWriteAsync()) SavePSD(s, ls, x, y);
                    if (f != null)
                    {
                        file = await f.CreateFileAsync(file.Name.Replace(".psd", ".png"), CreationCollisionOption.OpenIfExists);
                        await SaveIMG(ot, file, BitmapEncoder.PngEncoderId);
                    }
                    break;

                default:
                    throw new Exception("ntype");
                }
            }
            catch (Exception e)
            {
                new MessageDialog(e.ToString()).ShowMux();
            }

            Loading = false;
        }
Example #48
0
 public static unsafe Span <uint> GetPixelRowSpan(this WriteableBitmap bitmap, int y, int length = 0, int offset = 0)
 {
     using var l = bitmap.Lock();
     return(new Span <uint>(IntPtr.Add(l.Address, (int)(bitmap.Size.Width * y + offset)).ToPointer(), (int)(length == 0 ? bitmap.Size.Width : length)));
 }
Example #49
0
        /// <summary>
        /// Releases unmanaged and - optionally - managed resources.
        /// </summary>
        /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
        protected virtual void Dispose(bool disposing)
        {
#if NETFX_CORE
            _stream.Dispose();
            _stream = null;
#endif
            _data = null;
            _bytes = null;
            _bitmap = null;
        }
Example #50
0
        /// <summary>
        /// Code to draw and place the map.
        /// Will first define basic info for drawing
        /// Then creates a byte array to define colors at each point in bitmap
        /// Then the bitmap will be placed on screen.
        /// </summary>
        public void DrawMap()
        {
            //First define parameters.
            ParentContainer.Width  = Map.Width;
            ParentContainer.Height = Map.Height;

            PixelFormat pf = PixelFormats.Bgr32;

            RawStride = (Map.Width * pf.BitsPerPixel + 7) / 8;
            byte[] rawImage = new byte[RawStride * Map.Height];


            //Next use those parameters to populate the array and define each pixel's colour.
            for (int i = 0; i < Map.Height; i++)
            {
                for (int j = 0; j < RawStride; j += 4)
                {
                    int index   = (i * RawStride) + j;
                    int actualJ = j / 4;

                    if (Map[actualJ, i].HomeBase)
                    {
                        for (int k = 0; k < 4; k++)
                        {
                            rawImage[index + k] = ColorScale.BiomeColors[12, k];
                        }
                    }

                    else if (Map[actualJ, i].Explored)
                    {
                        int BiomeIndex = (int)(10 * Map[i, actualJ].Elevation);


                        for (int k = 0; k < 4; k++)
                        {
                            rawImage[index + k] = ColorScale.BiomeColors[BiomeIndex, k];
                        }
                    }

                    else
                    {
                        for (int k = 0; k < 4; k++)
                        {
                            rawImage[index + k] = ColorScale.BiomeColors[11, k];
                        }
                    }
                }
            }

            //Finally generate and apply bitmap image.
            BitmapSource baseMap;

            MapImagePane.Width  = Map.Width;
            MapImagePane.Height = Map.Height;

            baseMap = BitmapSource.Create(Map.Width, Map.Height, 96, 96, pf, null, rawImage, RawStride);

            MapImage = new WriteableBitmap(baseMap);

            MapImagePane.Source = MapImage;
        }
        /// <summary>
        /// Copies (blits) the pixels from the WriteableBitmap source to the destination WriteableBitmap (this).
        /// </summary>
        /// <param name="bmp">The destination WriteableBitmap.</param>
        /// <param name="destRect">The rectangle that defines the destination region.</param>
        /// <param name="source">The source WriteableBitmap.</param>
        /// <param name="sourceRect">The rectangle that will be copied from the source to the destination.</param>
        /// <param name="color">If not Colors.White, will tint the source image. A partially transparent color and the image will be drawn partially transparent.</param>
        /// <param name="BlendMode">The blending mode <see cref="BlendMode"/>.</param>
        public static void Blit(this WriteableBitmap bmp, Rect destRect, WriteableBitmap source, Rect sourceRect, Color color, BlendMode BlendMode)
        {
            if (color.A == 0)
             {
            return;
             }
             int dw = (int)destRect.Width;
             int dh = (int)destRect.Height;
             int dpw = bmp.PixelWidth;
             int dph = bmp.PixelHeight;
             Rect intersect = new Rect(0, 0, dpw, dph);
             intersect.Intersect(destRect);
             if (intersect.IsEmpty)
             {
            return;
             }
             int sourceWidth = source.PixelWidth;

             int[] sourcePixels = source.Pixels;
             int[] destPixels = bmp.Pixels;
             int sourceLength = sourcePixels.Length;
             int destLength = destPixels.Length;
             int sourceIdx = -1;
             int px = (int)destRect.X;
             int py = (int)destRect.Y;
             int right = px + dw;
             int bottom = py + dh;
             int x;
             int y;
             int idx;
             double ii;
             double jj;
             int sr = 0;
             int sg = 0;
             int sb = 0;
             int dr, dg, db;
             int sourcePixel;
             int sa = 0;
             int da;
             int ca = color.A;
             int cr = color.R;
             int cg = color.G;
             int cb = color.B;
             bool tinted = color != Colors.White;
             double sdx = sourceRect.Width / destRect.Width;
             double sdy = sourceRect.Height / destRect.Height;
             int sourceStartX = (int)sourceRect.X;
             int sourceStartY = (int)sourceRect.Y;
             int lastii, lastjj;
             lastii = -1;
             lastjj = -1;
             jj = sourceStartY;
             y = py;
             for (int j = 0; j < dh; j++)
             {
            if (y >= 0 && y < dph)
            {
               ii = sourceStartX;
               idx = px + y * dpw;
               x = px;
               sourcePixel = sourcePixels[0];

               for (int i = 0; i < dw; i++)
               {
                  if (x >= 0 && x < dpw)
                  {
                     if ((int)ii != lastii || (int)jj != lastjj)
                     {
                        sourceIdx = (int)ii + (int)jj * sourceWidth;
                        if (sourceIdx >= 0 && sourceIdx < sourceLength)
                        {
                            sourcePixel = sourcePixels[sourceIdx];
                            sa = ((sourcePixel >> 24) & 0xff);
                            sr = ((sourcePixel >> 16) & 0xff);
                            sg = ((sourcePixel >> 8) & 0xff);
                            sb = ((sourcePixel) & 0xff);
                            if (tinted && sa != 0)
                            {
                                sa = (((sa * ca) * 0x8081) >> 23);
                                sr = ((((((sr * cr) * 0x8081) >> 23) * ca) * 0x8081) >> 23);
                                sg = ((((((sg * cg) * 0x8081) >> 23) * ca) * 0x8081) >> 23);
                                sb = ((((((sb * cb) * 0x8081) >> 23) * ca) * 0x8081) >> 23);
                                sourcePixel = (sa << 24) | (sr << 16) | (sg << 8) | sb;
                            }
                        }
                        else
                        {
                           sa = 0;
                        }
                     }
                     if (BlendMode == BlendMode.None)
                     {
                        destPixels[idx] = sourcePixel;
                     }
                     else if (sa > 0)
                     {
                        int destPixel = destPixels[idx];
                        da = ((destPixel >> 24) & 0xff);
                        if ((sa == 255 || da == 0) &&
                           BlendMode != BlendMode.Additive &&
                           BlendMode != BlendMode.Subtractive
                           )
                        {
                           destPixels[idx] = sourcePixel;
                        }
                        else
                        {
                           dr = ((destPixel >> 16) & 0xff);
                           dg = ((destPixel >> 8) & 0xff);
                           db = ((destPixel) & 0xff);
                           if (BlendMode == BlendMode.AlphaBlend)
                           {
                               destPixel = ((sa + (((da * (255 - sa)) * 0x8081) >> 23)) << 24) |
                                   ((sr + (((dr * (255 - sa)) * 0x8081) >> 23)) << 16) |
                                   ((sg + (((dg * (255 - sa)) * 0x8081) >> 23)) << 8) |
                                   ((sb + (((db * (255 - sa)) * 0x8081) >> 23)));
                           }
                           else if (BlendMode == BlendMode.Additive)
                           {
                               int a = (255 <= sa + da) ? 255 : (sa + da);
                               destPixel = (a << 24) |
                                    (((a <= sr + dr) ? a : (sr + dr)) << 16) |
                                    (((a <= sg + dg) ? a : (sg + dg)) << 8) |
                                    (((a <= sb + db) ? a : (sb + db)));
                           }
                           else if (BlendMode == BlendMode.Subtractive)
                           {
                               int a = da;
                               destPixel = (a << 24) |
                                    (((sr >= dr) ? 0 : (sr - dr)) << 16) |
                                    (((sg >= dg) ? 0 : (sg - dg)) << 8) |
                                    (((sb >= db) ? 0 : (sb - db)));
                           }
                           destPixels[idx] = destPixel;
                        }
                     }
                  }
                  x++;
                  idx++;
                  ii += sdx;
               }
            }
            jj += sdy;
            y++;
             }
        }
Example #52
0
        private void Timer_Tick(object sender, EventArgs e)
        {
            if (image2.Visibility == Visibility.Visible)
            {
                TimeSpan timeClose = TimeSpan.Parse(timeShopOpen);
                if (DateTime.Now.Hour == (timeClose.Hours > 10 ? timeClose.Hours : timeClose.Hours + 12) && DateTime.Now.Minute > timeClose.Minutes)
                {
                    string[] lines = File.ReadAllLines("Ads\\prices.txt");
                    Dictionary <string, string> prices = new Dictionary <string, string>();
                    foreach (string l in lines)
                    {
                        string[] values = l.Split(new char[] { '=' });
                        prices.Add(values[0], values[1]);
                    }
                    prices["reopen"] = "";
                    StringBuilder sb = new StringBuilder();
                    foreach (KeyValuePair <string, string> k in prices)
                    {
                        sb.AppendLine(k.Key + "=" + k.Value);
                    }
                    File.WriteAllText("Ads\\prices.txt", sb.ToString());

                    image2.Visibility       = Visibility.Hidden;
                    timeShopOpen            = "";
                    textTimeOpen.Visibility = Visibility.Hidden;
                }
                return;
            }

            if (timeShopOpen != "")
            {
                image2.Source           = new BitmapImage(new Uri("timeOpen.PNG", UriKind.RelativeOrAbsolute));
                image2.Visibility       = Visibility.Visible;
                textTimeOpen.Text       = timeShopOpen;
                textTimeOpen.Visibility = Visibility.Visible;

                return;
            }

            if (video.Visibility == Visibility.Visible)
            {
                if (timeSpanEndVideo.Seconds > 1 ? video.Position > timeSpanEndVideo : videoEnded)
                {
                    video.Visibility = Visibility.Collapsed;
                    video.Stop();
                    video.MediaEnded -= Video_MediaEnded;
                    videoEnded        = false;
                    timeSpanEndVideo  = new TimeSpan();
                    progressValue     = 0;
                }
                return;
            }

            if (progressValue == 0)
            {
                hideAllTexts();
                getPrices();

                images = Directory.GetFiles("Ads").ToList();
                images = images.Where(s => s.EndsWith("mp4") | s.EndsWith("png", true, CultureInfo.CurrentCulture)
                                      | s.EndsWith("jpg", true, CultureInfo.CurrentCulture) | s.EndsWith("jpeg", true, CultureInfo.CurrentCulture)).ToList();

                if (imageIndex >= images.Count)
                {
                    imageIndex = 0;
                }


                if (images[imageIndex].EndsWith("mp4"))
                {
                    string duration = images[imageIndex];
                    var    match    = Regex.Match(duration, "\\(\\d{1,3}\\)");
                    if (match.Success)
                    {
                        timeSpanEndVideo = new TimeSpan(0, 0, -1 * int.Parse(match.Value, NumberStyles.AllowParentheses));
                    }
                    else
                    {
                        video.MediaEnded += Video_MediaEnded;
                    }
                    video.Visibility = Visibility.Visible;
                    video.Source     = new Uri(images[imageIndex], UriKind.Relative);
                    video.Play();
                    imageIndex++;
                    image.Fill = Brushes.White;
                    return;
                }

                showSpecificPriceText(images[imageIndex]);

                BitmapImage bi = new BitmapImage(new Uri(images[imageIndex], UriKind.Relative));
                if (images[imageIndex].Contains("alfa"))
                {
                    original = bi;
                    int    stride = bi.PixelWidth * (bi.Format.BitsPerPixel / 8);
                    byte[] pixels = new byte[bi.PixelHeight * stride];
                    bi.CopyPixels(pixels, stride, 0);
                    for (int i = 0; i < pixels.Length; i++)
                    {
                        if ((i + 1) % 4 == 0)
                        {
                            continue;
                        }
                        pixels[i] = (byte)(0xFF - pixels[i]);
                    }

                    inverted = new WriteableBitmap(bi);
                    inverted.WritePixels(new Int32Rect(0, 0, bi.PixelWidth, bi.PixelHeight), pixels, stride, 0);
                }

                image.Fill = new ImageBrush(bi);
                //bi.StreamSource.Close();

                var ss = System.Windows.Forms.Screen.AllScreens;
                if (ss.Length == 1)
                {
                    powerOff    = 3;
                    WindowState = WindowState.Minimized;
                }
                if (powerOff > 0)
                {
                    if (ss.Length == 2)
                    {
                        if (--powerOff == 0)
                        {
                            double dpi         = ss[0].Bounds.Width / SystemParameters.PrimaryScreenWidth;
                            var    workingArea = ss[1].Bounds;
                            Left        = workingArea.Left / dpi;
                            Top         = workingArea.Top;
                            WindowState = WindowState.Maximized;
                        }
                    }
                }
            }

            if (images[imageIndex].Contains("alfa") && progressValue > max / 2 && progressValue % 3 == 0)
            {
                if (progressValue % 6 == 0)
                {
                    image.Fill = new ImageBrush(original);
                }
                else
                {
                    image.Fill = new ImageBrush(inverted);
                }
            }

            progress.Value = progressValue * 100 / max;
            progressValue += 1;

            if (progressValue > max)
            {
                if (inverted != null)
                {
                    inverted = null;
                }
                progressValue = 0;
                imageIndex++;

                //RenderTargetBitmap image2 = new RenderTargetBitmap((int)imageCards.RenderSize.Width, (int)imageCards.RenderSize.Height, 96, 96, PixelFormats.Default);
                ////grid1.UpdateLayout();
                //image2.Render(grid1);
                //imageCards.Source =image2;
            }
        }
 /// <summary>
 /// Copies (blits) the pixels from the WriteableBitmap source to the destination WriteableBitmap (this).
 /// </summary>
 /// <param name="bmp">The destination WriteableBitmap.</param>
 /// <param name="destPosition">The destination position in the destination bitmap.</param>
 /// <param name="source">The source WriteableBitmap.</param>
 /// <param name="sourceRect">The rectangle that will be copied from the source to the destination.</param>
 /// <param name="color">If not Colors.White, will tint the source image. A partially transparent color and the image will be drawn partially transparent.</param>
 /// <param name="BlendMode">The blending mode <see cref="BlendMode"/>.</param>
 public static void Blit(this WriteableBitmap bmp, Point destPosition, WriteableBitmap source, Rect sourceRect, Color color, BlendMode BlendMode)
 {
     Rect destRect = new Rect(destPosition, new Size(sourceRect.Width, sourceRect.Height));
      Blit(bmp, destRect, source, sourceRect, color, BlendMode);
 }
Example #54
0
 public SpriteViewModel()
 {
     _spriteImage = new WriteableBitmap(8, 16, 96, 96, PixelFormats.Bgra32, null);
 }
Example #55
0
 public static unsafe Span <uint> GetPixelSpan(this WriteableBitmap bitmap, int length, int offset = 0)
 {
     using var l = bitmap.Lock();
     return(new Span <uint>(IntPtr.Add(l.Address, offset).ToPointer(), length));
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="WriteableBitmapWrapper" /> class.
 /// </summary>
 /// <param name="pixelWidth">Width of the pixel.</param>
 /// <param name="pixelHeight">Height of the pixel.</param>
 /// <param name="dpiX">The dpi X.</param>
 /// <param name="dpiY">The dpi Y.</param>
 /// <param name="pixelFormat">The pixel format.</param>
 /// <param name="palette">The palette.</param>
 public WriteableBitmapWrapper(int pixelWidth, int pixelHeight, PixelFormat pixelFormat, int dpiX = 96, int dpiY = 96, BitmapPalette palette = null)
 {
     pixelFormat.Guard("pixelFormat");
     source = new WriteableBitmap(pixelWidth, pixelHeight, dpiX, dpiY, pixelFormat, palette);
 }
        /// <summary>
        /// Rotates the bitmap in 90° steps clockwise and returns a new rotated WriteableBitmap.
        /// </summary>
        /// <param name="bmp">The WriteableBitmap.</param>
        /// <param name="angle">The angle in degress the bitmap should be rotated in 90° steps clockwise.</param>
        /// <returns>A new WriteableBitmap that is a rotated version of the input.</returns>
        public static WriteableBitmap Rotate(this WriteableBitmap bmp, int angle)
        {
            // Use refs for faster access (really important!) speeds up a lot!
             var w = bmp.PixelWidth;
             var h = bmp.PixelHeight;
             var p = bmp.Pixels;
             var i = 0;
             WriteableBitmap result = null;
             angle %= 360;

             if (angle > 0 && angle <= 90)
             {
            result = new WriteableBitmap(h, w);
            var rp = result.Pixels;
            for (var x = 0; x < w; x++)
            {
               for (var y = h - 1; y >= 0; y--)
               {
                  var srcInd = y * w + x;
                  rp[i] = p[srcInd];
                  i++;
               }
            }
             }
             else if (angle > 90 && angle <= 180)
             {
            result = new WriteableBitmap(w, h);
            var rp = result.Pixels;
            for (var y = h - 1; y >= 0; y--)
            {
               for (var x = w - 1; x >= 0; x--)
               {
                  var srcInd = y * w + x;
                  rp[i] = p[srcInd];
                  i++;
               }
            }
             }
             else if (angle > 180 && angle <= 270)
             {
            result = new WriteableBitmap(h, w);
            var rp = result.Pixels;
            for (var x = w - 1; x >= 0; x--)
            {
               for (var y = 0; y < h; y++)
               {
                  var srcInd = y * w + x;
                  rp[i] = p[srcInd];
                  i++;
               }
            }
             }
             else
             {
            result = bmp.Clone();
             }
             return result;
        }
Example #58
0
 public static Span <uint> GetSinglePixelSpan(this WriteableBitmap bitmap, int x, int y, int length = 1)
 {
     using var l = bitmap.Lock();
     return(bitmap.GetPixelSpan(length, bitmap.GetPixelPos(x, y)));
 }
        /// <summary>
        /// Creates a new cropped WriteableBitmap.
        /// </summary>
        /// <param name="bmp">The WriteableBitmap.</param>
        /// <param name="x">The x coordinate of the rectangle that defines the crop region.</param>
        /// <param name="y">The y coordinate of the rectangle that defines the crop region.</param>
        /// <param name="width">The width of the rectangle that defines the crop region.</param>
        /// <param name="height">The height of the rectangle that defines the crop region.</param>
        /// <returns>A new WriteableBitmap that is a cropped version of the input.</returns>
        public static WriteableBitmap Crop(this WriteableBitmap bmp, int x, int y, int width, int height)
        {
            var srcWidth = bmp.PixelWidth;
             var srcHeight = bmp.PixelHeight;

             // If the rectangle is completly out of the bitmap
             if(x > srcWidth || y > srcHeight)
             {
            return new WriteableBitmap(0, 0);
             }

             // Clamp to boundaries
             if (x < 0) x = 0;
             if (x + width >= srcWidth) width = (srcWidth - 1) - x;
             if (y < 0) y = 0;
             if (y + height >= srcHeight) height = (srcHeight - 1) - y;

             // Copy the pixels line by line using fast BlockCopy
             var result = new WriteableBitmap(width, height);
             for (var line = 0; line < height; line++)
             {
            var srcOff = ((y + line) * srcWidth + x) * SizeOfArgb;
            var dstOff = line * width * SizeOfArgb;
            Buffer.BlockCopy(bmp.Pixels, srcOff, result.Pixels, dstOff, width * SizeOfArgb);
             }
             return result;
        }
Example #60
0
 public static Span <uint> GetSinglePixelPosSpan(this WriteableBitmap bitmap, int pos, int length = 3)
 => bitmap.GetPixelSpan(length, pos);