Пример #1
0
        public static BitmapSource GetImageToDraw(string str_name, string str_table_name, bool big_gui, bool is_mirrored)
        {
            string strImagePath   = string.Empty;
            bool   bNeedToUpscale = false;
            string strImageName   = System.IO.Path.GetFileNameWithoutExtension(str_name);

            try
            {
                strImagePath = App.DB.GetImagePathFromMemory(strImageName, str_table_name, big_gui);
                if (string.IsNullOrEmpty(strImagePath) && big_gui)
                {
                    // if big image doesn't exist let's use the small one and upscale it
                    strImagePath   = App.DB.GetImagePathFromMemory(strImageName, str_table_name, false);
                    bNeedToUpscale = true;
                }
            }
            catch //sometimes it gives an exception other times it returns string empty, :/ I should check this more carefully
            {
                // if big image doesn't exist let's use the small one and upscale it
                strImagePath   = App.DB.GetImagePathFromMemory(strImageName, str_table_name, false);
                bNeedToUpscale = true;
            }

            BitmapImage  image        = new BitmapImage(new Uri(strImagePath));
            BitmapSource sourceReturn = ConvertImageDpi(image, App.I.DpiX, App.I.DpiY);

            if (bNeedToUpscale && !is_mirrored)
            {
                sourceReturn = new TransformedBitmap(sourceReturn, new ScaleTransform(-2, 2, 0, 0));
            }
            else if (bNeedToUpscale)
            {
                sourceReturn = new TransformedBitmap(sourceReturn, new ScaleTransform(2, 2));
            }
            else if (is_mirrored)
            {
                sourceReturn = new TransformedBitmap(sourceReturn, new ScaleTransform(-1, 1, 0, 0));
            }

            sourceReturn.Freeze();
            return(sourceReturn);
        }
Пример #2
0
        private static TransformedBitmap Scale(BitmapSource src, double scale)
        {
            // Set up the transformed thumbnail
            TransformedBitmap thumb = new TransformedBitmap();

            thumb.BeginInit();
            thumb.Source = src;
            TransformGroup transform = new TransformGroup();

            // Scale
            double xScale = Math.Min(1.0, Math.Max(1.0 / (double)src.PixelWidth, scale));
            double yScale = Math.Min(1.0, Math.Max(1.0 / (double)src.PixelHeight, scale));

            transform.Children.Add(new ScaleTransform(xScale, yScale));

            thumb.Transform = transform;
            thumb.EndInit();
            thumb.Freeze();
            return(thumb);
        }
Пример #3
0
        public void NextImage(Point direction)
        {
            spriteIndex++;
            if (spriteIndex >= spriteCount)
            {
                spriteIndex = 0;
            }
            BitmapSource image      = new BitmapImage(imageUri);
            BitmapSource croppedImg = new CroppedBitmap(image, new Int32Rect(spriteIndex * ((int)image.Width / spriteCount),
                                                                             0, (int)image.Width / spriteCount, 64));

            currDir = (direction == Direction.Left || direction == Direction.Right) ? direction : currDir;
            if (currDir == Direction.Left)
            {
                croppedImg = new TransformedBitmap(croppedImg, new ScaleTransform(-1, 1, 0, 0));
            }
            Rect.Fill   = new ImageBrush(croppedImg);
            Rect.Width  = croppedImg.Width;
            Rect.Height = croppedImg.Height;
        }
Пример #4
0
        private void Button_Click_3(object sender, RoutedEventArgs e)
        {
            if (width_text.Text == "" | height_text.Text == "")
            {
                MessageBox.Show("PLease enter the height and the width of the image", "Content Required Message");
            }
            else
            {
                int w = Convert.ToInt32(width_text.Text);
                int h = Convert.ToInt32(height_text.Text);


                TransformedBitmap tb = new TransformedBitmap();
                tb.BeginInit();
                tb.Source    = bm;
                tb.Transform = new ScaleTransform(bm.PixelWidth / w, bm.PixelHeight / h);
                tb.EndInit();
                image_control.Source = tb;
            }
        }
Пример #5
0
        public void Resize(Bitmap src, Bitmap dst, object options = null)
        {
            var source = Misc.AllocWriteableBitmap(src.Width, src.Height, src.Depth, src.Channel);

            Misc.CopyToWritableBitmap(source, src);
            var          scaleTransform = new ScaleTransform((double)dst.Width / src.Width, (double)dst.Height / src.Height);
            BitmapSource transformed    = new TransformedBitmap(source, scaleTransform);

            if (transformed.Format.BitsPerPixel > 64)
            {
                var converted = new FormatConvertedBitmap();
                converted.BeginInit();
                converted.Source            = transformed;
                converted.DestinationFormat = dst.Channel == 4 ? PixelFormats.Rgba64 : PixelFormats.Rgb48;
                converted.EndInit();

                transformed = converted;
            }
            transformed.CopyPixels(Int32Rect.Empty, dst.Scan0, dst.Stride * dst.Height, dst.Stride);
        }
Пример #6
0
        /// <summary>
        /// Поворачивает изображение фиксированно!!!!
        /// </summary>
        /// <param name="img">BitmapSource</param>
        /// <param name="angle">angle</param>
        /// <returns>BitmapSource</returns>
        public static BitmapSource RotateImage(this BitmapSource img, double angle = 0)
        {
            if (Math.Abs(angle) > 0.01 && Math.Abs(angle % 90) < 0.01)
            {
                // Create the TransformedBitmap to use as the Image source.
                var tb = new TransformedBitmap(img, new RotateTransform(angle));
                // Set the Image source.
                return(tb);
            }
            //корректируем размер будующего имэйджа
            double cos = Math.Abs(Math.Cos(angle * Math.PI / 180));
            double sin = Math.Abs(Math.Sin(angle * Math.PI / 180));

            double newWidth  = img.PixelWidth * cos + img.PixelHeight * sin;
            double newHeight = img.PixelHeight * cos + img.PixelWidth * sin;

            //поворачиваем
            return(GenerateCroppedImage(img, new Point(img.PixelWidth / 2, img.PixelHeight / 2),
                                        newWidth, newHeight, angle));
        }
Пример #7
0
        private void Apply_rotate(object sender, RoutedEventArgs e)
        {
            string text = rotate_txt.Text;

            if (text == "")
            {
                MessageBox.Show("The textbox is empty ,please enter a suitable degree");
            }
            else
            {
                double            number         = Convert.ToDouble(text);
                TransformedBitmap transformation = new TransformedBitmap();
                transformation.BeginInit();
                transformation.Source = bm;
                RotateTransform rotate = new RotateTransform(number);
                transformation.Transform = rotate;
                transformation.EndInit();
                image_control.Source = transformation;
            }
        }
Пример #8
0
        void CaptureListener.OnBuffer(CaptureDevice i_sender, double i_sample_time, IntPtr i_buffer, int i_buffer_len)
        {
            int w = i_sender.video_width;
            int h = i_sender.video_height;
            int s = w * (i_sender.video_bit_count / 8);

            try
            {
                Dispatcher.BeginInvoke(new Action(delegate()
                {
                    TransformedBitmap b = new TransformedBitmap();
                    b.BeginInit();
                    b.Source = BitmapSource.Create(w, h, 96.0, 96.0, PixelFormats.Bgr32, BitmapPalettes.WebPalette, i_buffer, i_buffer_len, s);
                    b.SetValue(TransformedBitmap.TransformProperty, new ScaleTransform(-1, -1));
                    b.EndInit();
                    image1.SetValue(Image.SourceProperty, b);
                }), null);
            }
            catch {}
        }
Пример #9
0
        BitmapSource GetBitmapGfx(BitmapGfx gfx, int size)
        {
            int xoff;
            int tileSize = 0;

            for (int i = 0; i < m_bitmapSizes.Length; ++i)
            {
                if (size <= m_bitmapSizes[i])
                {
                    tileSize = m_bitmapSizes[i];
                    break;
                }
            }

            if (tileSize == 0)
            {
                tileSize = m_bitmapSizes.Max();
            }

            xoff = 1;

            for (int i = 0; i < m_bitmapSizes.Length; ++i)
            {
                if (tileSize == m_bitmapSizes[i])
                {
                    break;
                }

                xoff += m_bitmapSizes[i] + 3;
            }

            BitmapSource bmp = new CroppedBitmap(m_bitmap, new Int32Rect(xoff, 1 + 35 * gfx.BitmapIndex, tileSize, tileSize));

            if (size != tileSize)
            {
                double scale = (double)size / tileSize;
                bmp = new TransformedBitmap(bmp, new ScaleTransform(scale, scale));
            }

            return(bmp);
        }
Пример #10
0
        protected override void StartVideoInternal()
        {
            worker = new Thread(() => {
                try
                {
                    udpClient = new UdpClient(new IPEndPoint(IPAddress.Any, Port));
                    while (worker == Thread.CurrentThread)
                    {
                        IPEndPoint ip = null;
                        var bytes     = udpClient.Receive(ref ip);
                        // Console.WriteLine(bytes.Length);
                        using (var stream = new MemoryStream(bytes))
                        {
                            var decoder = new JpegBitmapDecoder(stream,
                                                                BitmapCreateOptions.PreservePixelFormat,
                                                                BitmapCacheOption.OnLoad);
                            var bitmapSource = decoder.Frames[0];
                            bitmapSource.Freeze();

                            var rotatedSource = new TransformedBitmap();
                            rotatedSource.BeginInit();
                            rotatedSource.Source    = bitmapSource;
                            rotatedSource.Transform = new RotateTransform(90);
                            rotatedSource.EndInit();

                            this.FrameArrived(rotatedSource);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Trace.WriteLine("Worker crash: " + ex.Message);
                    StopVideoInternal();
                    StartVideoInternal();
                    return;
                }

                StopVideoInternal();
            });
            worker.Start();
        }
Пример #11
0
        private void CaptureButton_Click(object sender, RoutedEventArgs e)
        {
            // Store current image from the webcam
            var bitmap = Player.CurrentBitmap;

            if (bitmap == null)
            {
                return;
            }

            Transform tr             = new ScaleTransform(-1, 1);
            var       transformedBmp = new TransformedBitmap();

            transformedBmp.BeginInit();
            transformedBmp.Source    = bitmap;
            transformedBmp.Transform = tr;
            transformedBmp.EndInit();
            bitmap = transformedBmp;

            CapturedImage = bitmap;
        }
Пример #12
0
        private static void CacheTile(ref BitmapSource image, ref ImageData <byte[]> pixels, ref ImageData <Colour[]> colours)
        {
            if (!(image.PixelWidth == UI_MAP_TILE_PIXELSIZE && image.PixelHeight == UI_MAP_TILE_PIXELSIZE))
            {
                image = new TransformedBitmap(image,
                                              new ScaleTransform(UI_MAP_TILE_PIXELSIZE / (double)image.PixelWidth,
                                                                 UI_MAP_TILE_PIXELSIZE / (double)image.PixelHeight));
            }

            Debug.Assert(image.Format.BitsPerPixel == 32);
            Debug.Assert(image.PixelWidth == UI_MAP_TILE_PIXELSIZE);
            Debug.Assert(image.PixelHeight == UI_MAP_TILE_PIXELSIZE);

            image.Freeze();
            pixels = new ImageData <byte[]> {
                Data = CopyPixels(image), Width = image.PixelWidth, Height = image.PixelHeight
            };
            colours = new ImageData <Colour[]> {
                Data = ConvertToColour(pixels.Data), Width = image.PixelWidth, Height = image.PixelHeight
            };
        }
Пример #13
0
        public override BitmapSource Process(BitmapSource bmp, IFrameDestination dest)
        {
            if (bmp.PixelWidth == Width && bmp.PixelHeight == Height && !FlipHorizontally && !FlipVertically)
            {
                return(bmp);
            }
            var sw = new Stopwatch();

            sw.Start();
            var resized = new TransformedBitmap(bmp, new ScaleTransform(
                                                    Width / bmp.Width * (FlipHorizontally ? -1 : 1),
                                                    Height / bmp.Height * (FlipVertically ? -1 : 1),
                                                    (double)bmp.PixelWidth / 2,
                                                    (double)bmp.PixelHeight / 2));
            var rBmp = BitmapFrame.Create(resized);

            rBmp.Freeze();

            _whenProcessed.OnNext(rBmp);
            return(rBmp);
        }
Пример #14
0
        private void MirrorX_Click(object sender, RoutedEventArgs e)
        {
            TransformedBitmap tb = new TransformedBitmap();
            BitmapImage       bi = new BitmapImage(new Uri(this.wn.FileName));

            tb.BeginInit();
            tb.Source = bi;
            // Set image rotation.
            if (transformScale.ScaleY == -1)
            {
                transformScale = new ScaleTransform(transformScale.ScaleX, 1);
            }
            else
            {
                transformScale = new ScaleTransform(transformScale.ScaleX, -1);
            }
            tb.Transform = transformScale;
            tb.EndInit();
            // Set the Image source.
            this.wn.imageOn.Source = tb;
        }
Пример #15
0
        public override IImmagine applica(IImmagine immagineSorgente, Correzione correzione)
        {
            throw new NotImplementedException("occorre un container per traslare");

            // TODO da capire.
            // Concettualmente non ha senso traslare una immagine su se stessa.
            // Occorre avere un riferimento, un contenitore esterno su cui agire.
            // Una immagine con appiccicata una traslazione ha senso, ma l'immagine risultante da sola che senso ha ?
#if CONCETTUALMENTE_NON_VALIDO
            ImmagineWic  imgSorgente  = (ImmagineWic)immagineSorgente;
            BitmapSource bitmapSource = imgSorgente.bitmapSource;

            TranslateTransform tt = (TranslateTransform)this.ConvertTo(correzione, typeof(TranslateTransform));

            // Create the TransformedBitmap to use as the Image source.
            TransformedBitmap tb = new TransformedBitmap(bitmapSource, tt);

            ImmagineWic modificata = new ImmagineWic(tb);
            return(modificata);
#endif
        }
        /// <summary>
        ///     Resizes the image presented by the <paramref name="imageData"/> to a <paramref name="newSize"/>.
        /// </summary>
        /// <param name="imageData">
        ///     The binary data of the image to resize.
        /// </param>
        /// <param name="newSize">
        ///     The size to which to resize the image.
        /// </param>
        /// <param name="keepAspectRatio">
        ///     A flag indicating whether to save original aspect ratio.
        /// </param>
        /// <returns>
        ///     The structure which contains binary data of resized image and the actial size of resized image depending on <paramref name="keepAspectRatio"/> value.
        /// </returns>
        /// <exception cref="InvalidOperationException">
        ///     An error occurred during resizing the image.
        /// </exception>
        public static Task <ImageInfo> ResizeAsync(this byte[] imageData, Size newSize, bool keepAspectRatio)
        {
            var result        = new ImageInfo();
            var image         = imageData.ToBitmap();
            var percentWidth  = (double)newSize.Width / (double)image.PixelWidth;
            var percentHeight = (double)newSize.Height / (double)image.PixelHeight;

            ScaleTransform transform;

            if (keepAspectRatio)
            {
                transform = percentWidth < percentHeight
                                ? new ScaleTransform {
                    ScaleX = percentWidth, ScaleY = percentWidth
                }
                                : new ScaleTransform {
                    ScaleX = percentHeight, ScaleY = percentHeight
                };
            }
            else
            {
                transform = new ScaleTransform {
                    ScaleX = percentWidth, ScaleY = percentHeight
                };
            }

            var resizedImage = new TransformedBitmap(image, transform);

            using (var memoryStream = new MemoryStream())
            {
                var jpegEncoder = new JpegBitmapEncoder();
                jpegEncoder.Frames.Add(BitmapFrame.Create(resizedImage));
                jpegEncoder.Save(memoryStream);

                result.Data = memoryStream.ToArray();
                result.Size = new Size(resizedImage.PixelWidth, resizedImage.PixelHeight);
            }

            return(Task.FromResult(result));
        }
Пример #17
0
        private Bitmap ConvertCanvasToBitmap(Canvas canvas)
        {
            if (canvas == null)
            {
                return(null);
            }

            canvas.Background = new SolidColorBrush(Colors.LightSteelBlue);

            // reset current transform (in case it is scaled or rotated)
            Transform transform = canvas.LayoutTransform;

            canvas.LayoutTransform = null;

            // needed otherwise the image output is black
            System.Windows.Size size = new System.Windows.Size(canvas.Width, canvas.Height);
            canvas.Measure(size);
            canvas.Arrange(new System.Windows.Rect(size));

            RenderTargetBitmap renderBitmap = new RenderTargetBitmap((int)size.Width, (int)size.Height, 96d, 96d, PixelFormats.Pbgra32);

            renderBitmap.Render(canvas);

            canvas.LayoutTransform = transform;

            Bitmap bmp;

            using (MemoryStream outStream = new MemoryStream())
            {
                double       scaleX = 18.0 / renderBitmap.PixelWidth;
                double       scaleY = 18.0 / renderBitmap.PixelHeight;
                BitmapSource bitmap = new TransformedBitmap(renderBitmap, new ScaleTransform(scaleX, scaleY));

                PngBitmapEncoder enc = new PngBitmapEncoder();
                enc.Frames.Add(BitmapFrame.Create(bitmap));
                enc.Save(outStream);
                bmp = new Bitmap(outStream);
            }
            return(bmp);
        }
Пример #18
0
        /// <summary>
        /// 刷新图片,主要是选择图片改变后或窗口大小变动时使用。
        /// </summary>
        public void RefreshImage()
        {
            var            tempImageSource = GlobalScheme.PreviewBS;
            ScaleTransform st = new ScaleTransform();

            st.ScaleX = (preview.ActualWidth - 20) / (double)tempImageSource.PixelWidth;
            if (st.ScaleX < 0.1)
            {
                st.ScaleX = 0.1;
            }
            else if (st.ScaleX > 6)
            {
                st.ScaleX = 6;
            }
            st.ScaleY  = st.ScaleX;
            scale.Text = ((int)(st.ScaleX * 100)).ToString();
            var thumbPic = new TransformedBitmap(tempImageSource, st);

            //var newImageSource = new FormatConvertedBitmap(thumbPic, PixelFormats.Bgra32, null, 0);

            imageControl.Source = thumbPic;
        }
Пример #19
0
        public static BitmapSource GetResized(BitmapSource source, int size)
        {
            var backup = source.Clone();

            try
            {
                var transformedBitmap = new TransformedBitmap();
                transformedBitmap.BeginInit();
                transformedBitmap.Source = source;
                var scaleX         = size / (double)source.PixelWidth;
                var scaleY         = size / (double)source.PixelHeight;
                var scaleTransform = new ScaleTransform(scaleX, scaleY, source.Width / 2, source.Height / 2);
                transformedBitmap.Transform = scaleTransform;
                transformedBitmap.EndInit();
                source = transformedBitmap;
            }
            catch
            {
                source = backup;
            }
            return(source);
        }
Пример #20
0
        private void CropDraft()
        {
            if (SquareDraft == null || SquareDraft.IsDownloading)
            {
                return;
            }

            var rectangle = CroppingRectangle;

            double scaleX = SquareDraft.DpiX / 96;
            double scaleY = SquareDraft.DpiY / 96;

            var imgRect = new Rect(0, 0, SquareDraft.Width, SquareDraft.Height);

            rectangle.Intersect(imgRect);
            rectangle.Scale(scaleX, scaleY);

            if (rectangle == Rect.Empty)
            {
                rectangle = new Rect(0, 0, 1, 1);
            }

            var intRect = new Int32Rect((int)rectangle.X, (int)rectangle.Y, (int)Math.Round(rectangle.Width), (int)Math.Round(rectangle.Height));

            try
            {
                var croppedBmp = new CroppedBitmap(SquareDraft, intRect);


                double scale = 1;
                if (intRect.Width != intRect.Height)
                {
                    scale = (double)intRect.Height / intRect.Width;
                }

                SquareFinal = new TransformedBitmap(croppedBmp, new ScaleTransform(scale, 1));
            }
            catch { }
        }
Пример #21
0
        private static bool Report(int hwnd, int lParam)
        {
            IntPtr        ptr  = new IntPtr(hwnd);
            tagWINDOWINFO info = new tagWINDOWINFO();

            GetWindowInfo(ptr, ref info);

            if (IsWindowVisible(ptr) && !IsIconic(ptr) && info.cxWindowBorders > 0 && info.cyWindowBorders > 0)
            {
                string title = GetText(new IntPtr(hwnd));

                if (title != "")
                {
                    WindowSpec spec = new WindowSpec();
                    spec.Caption = title;
                    spec.Hwnd    = ptr;
                    spec.Info    = info;

                    Bitmap            bm = GetWindowPreview(spec);
                    BitmapImage       bi = ConvertBitmapToBitmapImage(bm);
                    TransformedBitmap tb = new TransformedBitmap();
                    tb.BeginInit();
                    tb.Source = bi;

                    double ratio     = bi.Height / bi.Width;
                    double newHeight = 150 * ratio;
                    double scaleX    = 150 / bi.Width;
                    double scaleY    = newHeight / bi.Height;

                    ScaleTransform transform = new ScaleTransform(scaleX, scaleY);
                    tb.Transform = transform;
                    tb.EndInit();
                    spec.Preview = tb;
                    WindowNames.Add(spec);
                }
            }

            return(true);
        }
Пример #22
0
        static public byte[] GetBytesFromThumbnail(BitmapSource imageSource, string imageFormat, int maxPixelLength, int jpegQuality = 80)
        {
            var scale = new ScaleTransform();

            if (imageSource.Width > imageSource.Height)
            {
                scale.ScaleX = scale.ScaleY = (double)maxPixelLength / (double)imageSource.PixelWidth;
            }
            else
            {
                scale.ScaleX = scale.ScaleY = (double)maxPixelLength / (double)imageSource.PixelHeight;
            }

            var transformedBitmap = new TransformedBitmap(imageSource, scale);

            BitmapEncoder encoder;
            var           extension = imageFormat.ToLower();

            if (extension == "png")
            {
                encoder = new PngBitmapEncoder();
            }
            else if (extension == "jpg")
            {
                encoder = new JpegBitmapEncoder();
            }
            else
            {
                throw new FileFormatException("Unknown file format");
            }

            encoder.Frames.Add(BitmapFrame.Create(transformedBitmap));

            using (var memoryStream = new MemoryStream())
            {
                encoder.Save(memoryStream);
                return(memoryStream.GetBuffer());
            }
        }
Пример #23
0
        /// <summary>
        /// Draws out the player.
        /// </summary>
        /// <returns>a drawing.</returns>
        private Drawing GetPlayer()
        {
            DrawingGroup g = new DrawingGroup();

            if (this.oldPlayer == null || this.oldPlayerPosition != this.model.MyPlayer.Cords || this.model.MousePosition != this.oldMousePosition)
            {
                Point       p        = new Point(this.model.MousePosition.X - (this.model.MyPlayer.Cords.X * GameModel.TileSize), this.model.MousePosition.Y - (this.model.MyPlayer.Cords.Y * GameModel.TileSize));
                double      rotation = Math.Atan2(p.Y, p.X) * 180 / Math.PI;
                BitmapImage bmp;
                if (this.model.MyPlayer.BeingDamagedByLava)
                {
                    bmp = GetImage("100onfire.png");
                }
                else
                {
                    bmp = GetImage("100.png");
                }

                TransformedBitmap tb = new TransformedBitmap();
                tb.BeginInit();
                tb.Source    = bmp;
                tb.Transform = new RotateTransform(90);
                tb.EndInit();

                ImageDrawing drawing = new ImageDrawing(tb, new Rect(this.model.MyPlayer.Cords.X * GameModel.TileSize, this.model.MyPlayer.Cords.Y * GameModel.TileSize, GameModel.TileSize, GameModel.TileSize));

                RotateTransform rotate = new RotateTransform(rotation, (this.model.MyPlayer.Cords.X * GameModel.TileSize) + (GameModel.TileSize / 2), (this.model.MyPlayer.Cords.Y * GameModel.TileSize) + (GameModel.TileSize / 2));

                g.Children.Add(new DrawingGroup()
                {
                    Children = { drawing }, Transform = rotate
                });

                this.oldPlayer         = g;
                this.oldPlayerPosition = this.model.MyPlayer.Cords;
            }

            return(this.oldPlayer);
        }
Пример #24
0
        public override Task <BitmapSource> GetThumbnail(Size renderSize)
        {
            var fullSize = Meta.GetSize();

            return(new Task <BitmapSource>(() =>
            {
                try
                {
                    using (var buffer = new MemoryStream(Meta.GetThumbnail()))
                    {
                        if (buffer.Length == 0)
                        {
                            return null;
                        }

                        var img = new BitmapImage();
                        img.BeginInit();
                        img.StreamSource = buffer;
                        img.CacheOption = BitmapCacheOption.OnLoad;
                        //// specific renderSize to avoid .net's double to int conversion
                        //img.DecodePixelWidth = Math.Max(1, (int) Math.Floor(renderSize.Width));
                        //img.DecodePixelHeight = Math.Max(1, (int) Math.Floor(renderSize.Height));
                        img.EndInit();

                        var scaled = new TransformedBitmap(img,
                                                           new ScaleTransform(fullSize.Width / img.PixelWidth, fullSize.Height / img.PixelHeight));

                        Helper.DpiHack(scaled);
                        scaled.Freeze();
                        return scaled;
                    }
                }
                catch (Exception e)
                {
                    ProcessHelper.WriteLog(e.ToString());
                    return null;
                }
            }));
        }
        //private void ConvertImage(string filePath)
        //{
        //    // convert image
        //    // Load up the original bitmap.
        //    Bitmap source = (Bitmap)Bitmap.FromFile(filePath);

        //    //Creat a 16 bit copy of it using the graphics class
        //    Bitmap dest = new Bitmap(source.Width, source.Height, System.Drawing.Imaging.PixelFormat.Format16bppRgb565);
        //    using (Graphics g = Graphics.FromImage(dest))
        //    {
        //        g.DrawImageUnscaled(source, 0, 0);
        //    }

        //    //Get a copy of the byte array you need to send to your tft
        //    Rectangle r = new Rectangle(0, 0, dest.Width, dest.Height);
        //    BitmapData bd = dest.LockBits(r, System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format16bppRgb565);
        //    TempByteArray = new byte[dest.Width * dest.Height * 2];
        //    Marshal.Copy(bd.Scan0, TempByteArray, 0, TempByteArray.Length);
        //    dest.UnlockBits(bd);

        //    //A 16 bit copy of the data you need to send to your tft is now sitting in the TftData array.

        //    UpdateStatus("Converted file to new format:");
        //}

        //private void ConvertImage2(string filePath)
        //{

        //    // different approach

        //    BitmapImage source = new BitmapImage(new Uri(filePath));

        //    FormatConvertedBitmap FmtCnvBmp = new FormatConvertedBitmap(source, PixelFormats.Bgr565, null, 1.0);
        //    TempByteArray = new byte[96 * 64 * 2];
        //    FmtCnvBmp.CopyPixels(TempByteArray, 96 * 2, 0);
        //}

        //private void ConvertImage3(string filePath)
        //{

        //    // approach 3 - 2 + reversing array

        //    BitmapImage source = new BitmapImage(new Uri(filePath));

        //    FormatConvertedBitmap FmtCnvBmp = new FormatConvertedBitmap(source, PixelFormats.Bgr565, null, 1.0);
        //    TempByteArray = new byte[96 * 64 * 2];
        //    FmtCnvBmp.CopyPixels(TempByteArray, 96 * 2, 0);

        //    Array.Reverse(TempByteArray);
        //}

        //private void ConvertImage4(string filePath)
        //{

        //    // approach 4 - 2 + converting each

        //    BitmapImage source = new BitmapImage(new Uri(filePath));

        //    FormatConvertedBitmap FmtCnvBmp = new FormatConvertedBitmap(source, PixelFormats.Bgr565, null, 1.0);
        //    TempByteArray = new byte[96 * 64 * 2];
        //    FmtCnvBmp.CopyPixels(TempByteArray, 96 * 2, 0);

        //    //for (int i = 1; i <= TempByteArray.Length; i++)
        //    //{
        //    //}

        //    int x = BitConverter.ToInt32(TempByteArray, 0);
        //    int y = Endian.SwapInt32(x);
        //    TempByteArray = BitConverter.GetBytes(y);
        //}

        //private void ConvertImage5(string filePath)
        //{
        //    Bitmap bmp = (Bitmap)Bitmap.FromFile(filePath);

        //    // this gets one line's output

        //    var data = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height),
        //            ImageLockMode.ReadOnly,
        //            System.Drawing.Imaging.PixelFormat.Format16bppRgb565);
        //        try
        //        {
        //            // var ptr = (IntPtr)((long)data.Scan0 + data.Stride * (bmp.Height - line - 1));  // commented out to avoid errors
        //            // var ret = new int[bmp.Width];
        //            // System.Runtime.InteropServices.Marshal.Copy(ptr, ret, 0, ret.Length * 4);
        //            // TempByteArray = ret; // commented out to avoid errors
        //        }
        //        finally
        //        {
        //            bmp.UnlockBits(data);
        //        }


        //}

        //private void ConvertImage6(string filePath)
        //{
        //    // manual conversion to RGB 565
        //    // from Java code at http://stackoverflow.com/questions/8319770/java-image-conversion-to-rgb565

        //    // load original bitmap
        //    Bitmap bufImg = (Bitmap)Bitmap.FromFile(filePath);

        //    // create 16 bit copy using graphics class
        //    Bitmap sendImg = new Bitmap(bufImg.Width, bufImg.Height, System.Drawing.Imaging.PixelFormat.Format16bppRgb565);
        //    using (Graphics g = Graphics.FromImage(sendImg))
        //    {
        //        g.DrawImageUnscaled(bufImg, 0, 0);
        //    }

        //    int numByte = 0;
        //    byte[] OutputImageArray = new byte[outputWidth * outputHeight * 2];

        //    int i = 0;
        //    int j = 0;
        //    int len = OutputImageArray.Length;

        //    for (i = 0; i < outputWidth; i++)
        //    {
        //        for (j = 0; j < outputHeight; j++)
        //        {

        //            System.Drawing.Color c = sendImg.GetPixel(i, j);
        //            int aRGBpix = sendImg.GetPixel(i, j).ToArgb();
        //            int alpha;
        //            int red = c.R;
        //            int green = c.G;
        //            int blue = c.B;

        //            //RGB888
        //            red = (aRGBpix >> 16) & 0x0FF;
        //            green = (aRGBpix >> 8) & 0x0FF;
        //            blue = (aRGBpix >> 0) & 0x0FF;
        //            alpha = (aRGBpix >> 24) & 0x0FF;

        //            //RGB565
        //            red = red >> 3;
        //            green = green >> 2;
        //            blue = blue >> 3;

        //            //A pixel is represented by a 4-byte (32 bit) integer, like so:
        //            //00000000 00000000 00000000 11111111
        //            //^ Alpha  ^Red     ^Green   ^Blue
        //            //Converting to RGB565

        //            short pixel_to_send = 0;
        //            int pixel_to_send_int = 0;
        //            pixel_to_send_int = (red << 11) | (green << 5) | (blue);
        //            pixel_to_send = (short)pixel_to_send_int;

        //            //dividing into bytes
        //            byte byteH = (byte)((pixel_to_send >> 8) & 0x0FF);
        //            byte byteL = (byte)(pixel_to_send & 0x0FF);

        //            //Writing it to array - High-byte is second
        //            OutputImageArray[numByte] = byteH;
        //            OutputImageArray[numByte + 1] = byteL;

        //            numByte += 2;
        //        }
        //    }

        //    // done - now return val
        //    TempByteArray = new byte[outputWidth * outputHeight * 2];
        //    TempByteArray = OutputImageArray;
        //}

        //public static void getRGB(Bitmap image, int startX, int startY, int w, int h, int[] rgbArray, int offset, int scansize)
        //{
        //    // function from http://stackoverflow.com/questions/4747428/getting-rgb-array-from-image-in-c-sharp
        //    //
        //    // for ConvertImage6 (Java-adapted function)
        //    //
        //    const int PixelWidth = 3;
        //    const System.Drawing.Imaging.PixelFormat PixFormat = System.Drawing.Imaging.PixelFormat.Format24bppRgb;

        //    // En garde!
        //    if (image == null) throw new ArgumentNullException("image");
        //    if (rgbArray == null) throw new ArgumentNullException("rgbArray");
        //    if (startX < 0 || startX + w > image.Width) throw new ArgumentOutOfRangeException("startX");
        //    if (startY < 0 || startY + h > image.Height) throw new ArgumentOutOfRangeException("startY");
        //    if (w < 0 || w > scansize || w > image.Width) throw new ArgumentOutOfRangeException("w");
        //    if (h < 0 || (rgbArray.Length < offset + h * scansize) || h > image.Height) throw new ArgumentOutOfRangeException("h");

        //    BitmapData data = image.LockBits(new Rectangle(startX, startY, w, h), System.Drawing.Imaging.ImageLockMode.ReadOnly, PixFormat);
        //    try
        //    {
        //        byte[] pixelData = new Byte[data.Stride];
        //        for (int scanline = 0; scanline < data.Height; scanline++)
        //        {
        //            Marshal.Copy(data.Scan0 + (scanline * data.Stride), pixelData, 0, data.Stride);
        //            for (int pixeloffset = 0; pixeloffset < data.Width; pixeloffset++)
        //            {
        //                // PixelFormat.Format32bppRgb means the data is stored
        //                // in memory as BGR. We want RGB, so we must do some
        //                // bit-shuffling.
        //                rgbArray[offset + (scanline * scansize) + pixeloffset] =
        //                    (pixelData[pixeloffset * PixelWidth + 2] << 16) +   // R
        //                    (pixelData[pixeloffset * PixelWidth + 1] << 8) +    // G
        //                    pixelData[pixeloffset * PixelWidth];                // B
        //            }
        //        }
        //    }
        //    finally
        //    {
        //        image.UnlockBits(data);
        //    }
        //}

        #endregion

        #region Image Processing

        private byte[] ConvertImage(BitmapSource source)
        {
            // approach #7 - #3 + 180 rotation
            //
            // converts to RGB565, then flips array at end (for big Endian)
            //   so in between, rotates 180 deg to compensate

            FormatConvertedBitmap FmtCnvBmp;

            if (outputBigEndian)
            {
                // big Endian, so let's first rotate 180

                TransformedBitmap transformBmp = new TransformedBitmap();
                transformBmp.BeginInit();
                transformBmp.Source = source;
                RotateTransform transform = new RotateTransform(180);
                transformBmp.Transform = transform;
                transformBmp.EndInit();

                FmtCnvBmp = new FormatConvertedBitmap(transformBmp, PixelFormats.Bgr565, null, 1.0);
            }
            else
            {
                // little Endian- nothing to do
                FmtCnvBmp = new FormatConvertedBitmap(source, PixelFormats.Bgr565, null, 1.0);
            }

            byte[] TempByteArray = new byte[96 * 64 * 2];
            FmtCnvBmp.CopyPixels(TempByteArray, 96 * 2, 0);

            if (outputBigEndian)
            {
                // if big Endian, time to reverse the array
                Array.Reverse(TempByteArray);
            }

            return(TempByteArray);
        }
Пример #26
0
        public void AffectImage(Dictionary <String, Object> args)
        {
            Image      image             = (Image)args["DisplayedImage"];
            int        presenterID       = (int)args["PresenterID"];
            List <int> presenters        = (List <int>)args["SynchronizedPresenters"];
            var        transformedBitmap = new TransformedBitmap();

            transformedBitmap.BeginInit();
            transformedBitmap.Source    = image.Bitmap;
            transformedBitmap.Transform = new RotateTransform(90);
            transformedBitmap.EndInit();
            image.Bitmap = transformedBitmap;

            RotateImageEvent ri         = new RotateImageEvent();
            IEventAggregator aggregator = GlobalEvent.GetEventAggregator();

            presenters.Add(presenterID);
            ri.Image                  = image;
            ri.PresenterID            = presenterID;
            ri.SynchronizedPresenters = presenters;
            aggregator.GetEvent <RotateImageEvent>().Publish(ri);
        }
Пример #27
0
        private void AddKeyFrame(byte[] frameData)
        {
            BitmapSource bitmap = BitmapSource.Create(format.Width, format.Height, 96, 96, System.Windows.Media.PixelFormats.Bgr32, null, frameData, format.Width * 4);

            ScaleTransform    scale        = new ScaleTransform(0.5, 0.5);
            TransformedBitmap scaledBitMap = new TransformedBitmap(bitmap, scale);

            JpegBitmapEncoder encoder = new JpegBitmapEncoder();

            encoder.Frames.Add(BitmapFrame.Create(scaledBitMap));

            MemoryStream ms = new MemoryStream();

            encoder.Save(ms);

            ms.Seek(0, SeekOrigin.Begin);
            JpegBitmapDecoder jpg = new JpegBitmapDecoder(ms, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);

            ms.Dispose();

            keyFrames.Add(jpg.Frames[0]);
        }
Пример #28
0
        byte[] CreateBitmapFromDepthData(byte[] depthDataColorPixels, int width, int height)
        {
            // Creates a new empty image with the pre-defined palette
            BitmapSource image = BitmapSource.Create(
                width,
                height,
                96,
                96,
                PixelFormats.Gray8,
                null,
                depthDataColorPixels,
                width);

            //Scaling to 1:1 aspect ratio
            RenderOptions.SetBitmapScalingMode(image, BitmapScalingMode.HighQuality);
            image = new TransformedBitmap(image, new ScaleTransform(1, (double)width / (double)height));

            byte[] result = null;

            using (MemoryStream stream = new MemoryStream())
            {
                JpegBitmapEncoder encoder = new JpegBitmapEncoder
                {
                    FlipHorizontal = false,
                    FlipVertical   = false,
                    QualityLevel   = 90,
                    Rotation       = Rotation.Rotate0
                };
                encoder.Frames.Add(BitmapFrame.Create(image));
                encoder.Save(stream);
                stream.Seek(0, 0);
                result = stream.ToArray();
                //using (var fileStream = new System.IO.FileStream(@"c:\temp\kinect\" + "file_" + DateTime.Now.ToShortTimeString() + ".jpeg", System.IO.FileMode.Create))
                //{
                //    encoder.Save(fileStream);
                //}
            }
            return(result);
        }
Пример #29
0
        public static BitmapSource GetResized(BitmapSource Source, int Size)
        {
            BitmapSource backup = Source.Clone();

            try
            {
                TransformedBitmap scaled = new TransformedBitmap();
                scaled.BeginInit();
                scaled.Source = Source;
                double         scX = (double)Size / (double)Source.PixelWidth;
                double         scy = (double)Size / (double)Source.PixelHeight;
                ScaleTransform tr  = new ScaleTransform(scX, scy, Source.Width / 2, Source.Height / 2);
                scaled.Transform = tr;
                scaled.EndInit();
                Source = scaled;
            }
            catch (Exception)
            {
                Source = backup;
            }
            return(Source);
        }
Пример #30
0
        void CaptureListener.OnBuffer(CaptureDevice oCaptureDevice, double i_sample_time, IntPtr i_buffer,
                                      int i_buffer_len)
        {
            Dispatcher.Invoke(new Action(delegate()
            {
                TransformedBitmap b = new TransformedBitmap();
                b.BeginInit();
                b.Source = BitmapSource.Create(oCaptureDevice.video_width, oCaptureDevice.video_height, 96.0, 96.0,
                                               PixelFormats.Bgr32, BitmapPalettes.WebPalette, i_buffer,
                                               i_buffer_len, oCaptureDevice.video_width * (oCaptureDevice.video_bit_count / 8));
                b.SetValue(TransformedBitmap.TransformProperty, new ScaleTransform(-1, -1));
                b.EndInit();
                this.ImgMainZm.SetValue(Image.SourceProperty, b);

                this.ARMarkerSystem.update(this.ARCameraSensor);
                this.CvMainZm.Children.Clear();

                if (this.ARMarkerSystem.isExistMarker(this.MarkerID_Hiro))
                {
                    this.DrawARDetectInfo(this.MarkerID_Hiro, "Hiro");
                }
                if (this.ARMarkerSystem.isExistMarker(this.MarkerID_KanJi))
                {
                    this.DrawARDetectInfo(this.MarkerID_KanJi, "KanJi");
                }
                if (this.ARMarkerSystem.isExistMarker(this.MarkerID_VTT))
                {
                    this.DrawARDetectInfo(this.MarkerID_VTT, "VTT");
                }
                if (this.ARMarkerSystem.isExistMarker(this.MarkerID_ABB))
                {
                    this.DrawARDetectInfo(this.MarkerID_ABB, "ABB");
                }
                if (this.ARMarkerSystem.isExistMarker(this.Marker_Hello))
                {
                    this.DrawARDetectInfo(this.Marker_Hello, "Hello");
                }
            }));
        }