Exemple #1
0
        public static BitmapSource ConvertCore(BitmapSource image, Color biasColor)
        {
            if (image == null)
            {
                return(null);
            }
            BitmapSource bitmapSource;

            if (image.Format == PixelFormats.Bgra32 && image.PixelWidth <= 128 && image.PixelHeight <= 128)
            {
                bitmapSource = ConvertToGrayScale(image, biasColor);
            }
            else
            {
                if (biasColor.R != byte.MaxValue || biasColor.G != byte.MaxValue || biasColor.B != byte.MaxValue)
                {
                    throw new NotSupportedException();
                }
                FormatConvertedBitmap formatConvertedBitmap = new FormatConvertedBitmap();
                formatConvertedBitmap.BeginInit();
                formatConvertedBitmap.DestinationFormat = PixelFormats.Gray32Float;
                formatConvertedBitmap.Source            = image;
                formatConvertedBitmap.EndInit();
                if (formatConvertedBitmap.CanFreeze)
                {
                    formatConvertedBitmap.Freeze();
                }
                bitmapSource = formatConvertedBitmap;
            }
            return(bitmapSource);
        }
        /// <summary>
        /// 从图片中获取背景颜色
        /// </summary>
        /// <param name="bitmap">图片</param>
        public static Color GetImageColorForBackground(FormatConvertedBitmap bitmap)
        {
            const int bytesPerPixel = 3;

            if (bitmap.CanFreeze)
            {
                bitmap.Freeze();
            }
            var pixels = new byte[bitmap.PixelHeight * bitmap.PixelWidth * bytesPerPixel];

            bitmap.CopyPixels(pixels, bitmap.PixelWidth * bytesPerPixel, 0);
            var width  = bitmap.PixelWidth;
            var height = bitmap.PixelHeight;

            //计算颜色的均值
            Color color = GetColorOfRegion(pixels, width, height, 0, width, 0, height);

            var hsl = new HslColor(color);

            if (IsNotSaturateEnough(hsl) && !IsAlmostZeroSaturation(hsl))
            {
                hsl.Saturation += 0.2;
            }

            return(Revise(hsl).ToRgb());
        }
        private static FormatConvertedBitmap ConvertToGrayscale(BitmapImage image)
        {
            var grayBitmapSource = new FormatConvertedBitmap();

            grayBitmapSource.BeginInit();
            grayBitmapSource.Source            = image;
            grayBitmapSource.DestinationFormat = PixelFormats.Gray32Float;
            grayBitmapSource.EndInit();
            grayBitmapSource.Freeze();
            return(grayBitmapSource);
        }
Exemple #4
0
        private static BitmapSource _ToFormat(BitmapSource source, PixelFormat format)
        {
            var bitmap = new FormatConvertedBitmap();

            bitmap.BeginInit();
            bitmap.DestinationFormat = format;
            bitmap.Source            = source;
            bitmap.EndInit();
            bitmap.Freeze();
            return(bitmap);
        }
Exemple #5
0
        public static Bitmap ToGdiBitmap(BitmapSource bmp)
        {
            // below code refernces blog entry by luche:
            // http://www.ruche-home.net/%A4%DC%A4%E4%A4%AD%A4%B4%A4%C8/2011-08-02/CopyPixels%20%A5%E1%A5%BD%A5%C3%A5%C9%A4%F2%CD%D1%A4%A4%A4%BF%20WPF%20BitmapSource%20%A4%AB%A4%E9%20GDI%20Bitmap%20%A4%D8%A4%CE%CA%D1%B4%B9

            if (bmp.Format != PixelFormats.Bgra32)
            {
                // convert format
                bmp = new FormatConvertedBitmap(bmp,
                                                PixelFormats.Bgra32, null, 0);
                bmp.Freeze();
            }

            // prepare values
            var width  = (int)bmp.Width;
            var height = (int)bmp.Height;
            var stride = width * 4;

            // prepare buffer
            var buffer = new byte[stride * height];

            // copy to byte array
            bmp.CopyPixels(buffer, stride, 0);

            // create bitmap
            var result = new Bitmap(width, height, SDI::PixelFormat.Format32bppArgb);

            // set bitmap content
            try
            {
                // locking bits
                SDI::BitmapData bd = null;
                try
                {
                    bd = result.LockBits(new Rectangle(0, 0, width, height),
                                         SDI::ImageLockMode.WriteOnly, SDI::PixelFormat.Format32bppArgb);
                    Marshal.Copy(buffer, 0, bd.Scan0, buffer.Length);
                }
                finally
                {
                    if (bd != null)
                    {
                        result.UnlockBits(bd);
                    }
                }
            }
            catch
            {
                result.Dispose();
                throw;
            }

            return(result);
        }
        private static BitmapSource Convert(BitmapSource source)
        {
            FormatConvertedBitmap bitmap = new FormatConvertedBitmap();

            bitmap.BeginInit();
            bitmap.Source            = source;
            bitmap.DestinationFormat = PixelFormats.Gray8;
            bitmap.EndInit();
            bitmap.Freeze();
            return(bitmap);
        }
Exemple #7
0
        public static BitmapSource Convert16BppTo8BppSource(BitmapSource source)
        {
            FormatConvertedBitmap s = new FormatConvertedBitmap();

            s.BeginInit();
            s.Source            = source;
            s.DestinationFormat = System.Windows.Media.PixelFormats.Gray8;
            s.EndInit();
            s.Freeze();
            return(s);
        }
Exemple #8
0
        public void InitializeFromVectorGraphics(VisualBrush visualBrush, double width, double height) //, Boolean grey)
        {
            RenderTargetBitmap renderTargetImage = CreateFromVectorGraphics(visualBrush, width, height);

            CachedFormatConvertedBitmap = new FormatConvertedBitmap(renderTargetImage, PixelFormats.Gray32Float, null, 0);
            CachedFormatConvertedBitmap.Freeze();

            CachedOpacityMask         = new ImageBrush(renderTargetImage);
            CachedOpacityMask.Opacity = 0.4;
            CachedOpacityMask.Freeze();

            SetGrey(!IsEnabled);
        }
        private static async Task <byte[]> ToBytesAsync(this BitmapSource bitmap)
        {
            if (bitmap.Format.BitsPerPixel != 32)
            {
                bitmap = new FormatConvertedBitmap(bitmap, PixelFormats.Bgra32, null, 0.0);
                bitmap.Freeze();
            }
            int stride = bitmap.GetStride();

            byte[] bytes = new byte[stride * bitmap.PixelHeight];
            await Task.Run(delegate
            {
                bitmap.CopyPixels(bytes, stride, 0);
            });

            return(bytes);
        }
Exemple #10
0
        public static BitmapSource GetClipboardImage(bool containsAlpha = false)
        {
            BitmapSource bitmapSource = null;

            if (Clipboard.ContainsImage())
            {
                bitmapSource = Clipboard.GetImage();
            }
            else if (Clipboard.ContainsFileDropList())
            {
                var fileDropList = Clipboard.GetFileDropList();
                if (fileDropList.Count <= 0)
                {
                    return(null);
                }
                bitmapSource = GetImageFromFile(fileDropList [0]);
            }
            else if (Clipboard.ContainsText())
            {
                string text = Clipboard.GetText();
                if (!File.Exists(text))
                {
                    return(null);
                }
                bitmapSource = GetImageFromFile(text);
            }
            else
            {
                return(null);
            }

            if (bitmapSource == null)
            {
                return(null);
            }

            bitmapSource = new FormatConvertedBitmap(bitmapSource,
                                                     containsAlpha
                                ? System.Windows.Media.PixelFormats.Bgra32
                                : System.Windows.Media.PixelFormats.Bgr24, null, 0);
            bitmapSource.Freeze();

            return(bitmapSource);
        }
        /// キャプチャしたHBitmapをBitmapSource(Freezed)にして返す
        /// @param request スクリーンキャプチャ設定をまとめたリクエスト
        /// @return スクリーンキャプチャ結果が格納されたBitmapSource
        private BitmapSource Capture(ScreenCaptureRequest request)
        {
            if (request.ClippingWidth <= 0 || request.ClippingHeight <= 0)
            {
                // Debug.WriteLine("Invalid clipping size", "ScreenCaptureTimer.CaptureByGetDIBits");
                return(null);
            }

            // HBitmapからBitmapSourceを作成
            BitmapSource bitmap = null;

            using (var result = request.Execute()) {
                if (result == null)
                {
                    return(bitmap);
                }

                // HBitmapからBitmapSourceに変換
                bitmap = Imaging.CreateBitmapSourceFromHBitmap(
                    result.Bitmap, IntPtr.Zero, Int32Rect.Empty,
                    BitmapSizeOptions.FromEmptyOptions());

                // Debug.WriteLine(string.Format("Captured: {0:D}x{1:D}",
                //                 bitmap.PixelWidth, bitmap.PixelHeight),
                //                 "ScreenCapture");
            }

            // Alphaチャンネル情報を削除
            bitmap = new FormatConvertedBitmap(bitmap, PixelFormats.Bgr32, null, 0.0);

            /// @todo(me) あまり大きな画像をメモリにおいておきたくない。
            ///           とはいえ、TransformedBitmapはちょっと重過ぎる。
            ///           メモリよりもCPUリソースを残しておきたいのでこのままでいいかも。
            //bitmap = this.Resize(bitmap);

            // スレッド越しにアクセスされるためFreeze
            bitmap.Freeze();
            return(bitmap);
        }
Exemple #12
0
        public void PaintAnimationGIF(LocalDecoder decoder)
        {
            frameCount   = decoder.Frames.Count;
            framePos     = 0;
            bitmapFrames = decoder.Frames;

            bmp = decoder.Frames[0];
            int width     = (int)Image.MinWidth;
            int height    = (int)Image.MinHeight;
            int imgWidth  = bmp.PixelWidth;
            int imgHeight = bmp.PixelHeight;

            ObjectAnimationUsingKeyFrames animation = new ObjectAnimationUsingKeyFrames();

            LogWriter.write("This File is Animation GIF.");
            isAnimation = true;

            long time = 0;
            long span = 1000 * 10;

            byte[] imgBuffer = new byte[imgWidth * imgHeight];

            WriteableBitmap wbmp = new WriteableBitmap(imgWidth, imgHeight, bmp.DpiX, bmp.DpiY, PixelFormats.Indexed8, bmp.Palette);

            GetScaleValue v = GetScale(imgWidth, imgHeight, width, height, bmp.DpiX, bmp.DpiY);

            scaleX = v.scaleX;
            scaleY = v.scaleY;
            int resizeWidth  = v.resizeWidth;
            int resizeHeight = v.resizeHight;

            if (bmp.Format != PixelFormats.Indexed8)
            {
                bmp = new FormatConvertedBitmap(bmp, PixelFormats.Indexed8, null, 0);
                bmp.Freeze();
            }

            offsetX = (width - resizeWidth) / 2.0;
            offsetY = (height - resizeHeight) / 2.0;

            TransformGroup transforms = new TransformGroup();

            transforms.Children.Add(new ScaleTransform(scaleX, scaleY));
            Matrix matrix = new Matrix(1, 0, 0, 1, offsetX, offsetY);

            transforms.Children.Add(new MatrixTransform(matrix));
            Image.RenderTransform = transforms;

            Image.Source = bmp;

            byte[] buf = new byte[imgWidth * imgHeight];
            bmp.CopyPixels(buf, imgWidth, 0);
            wbmp.WritePixels(new Int32Rect(0, 0, imgWidth, imgHeight), buf, imgWidth, 0);


            for (int i = 0; i < frameCount; i++)
            {
                BitmapSource   fbmp = bitmapFrames[i];
                int            transpearentColor = 0;
                BitmapMetadata metadata = fbmp.Metadata as BitmapMetadata;
                bool           transpearent = false, hasLocalPalette = false;
                int            delay = 0, startX = 0, startY = 0, w = imgWidth, h = imgHeight;

                BitmapPalette palette = bmp.Palette;

                if (metadata != null)
                {
                    try
                    {
                        startX       = (UInt16)metadata.GetQuery("/imgdesc/Left");
                        startY       = (UInt16)metadata.GetQuery("/imgdesc/Top");
                        w            = (UInt16)metadata.GetQuery("/imgdesc/Width");
                        h            = (UInt16)metadata.GetQuery("/imgdesc/Height");
                        delay        = (UInt16)metadata.GetQuery("/grctlext/Delay") * 10;
                        transpearent = (Boolean)metadata.GetQuery("/grctlext/TransparencyFlag");
                        if (transpearent)
                        {
                            transpearentColor = (Byte)metadata.GetQuery("/grctlext/TransparentColorIndex");
                        }
                        hasLocalPalette = (Boolean)metadata.GetQuery("/imgdesc/LocalColorTableFlag");
                        if (hasLocalPalette)
                        {
                            int size = (byte)metadata.GetQuery("/imgdesc/LocalColorTableSize");
                            palette = fbmp.Palette;
                        }
                    }
                    catch
                    {
                        LogWriter.write("Query Error");
                        //no data
                    }
                }


                if (fbmp.Format != PixelFormats.Indexed8)
                {
                    fbmp = new FormatConvertedBitmap(fbmp, PixelFormats.Indexed8, null, 0);
                    fbmp.Freeze();
                }

                byte[] fbuf = new byte[w * h];
                fbmp.CopyPixels(fbuf, w, 0);

                if (transpearent)
                {
                    for (int y = 0; y < h; y++)
                    {
                        int srcOffset  = y * w;
                        int destOffset = (startY + y) * imgWidth + startX;
                        for (int x = 0; x < w; x++)
                        {
                            if (transpearentColor != fbuf[srcOffset + x])
                            {
                                buf[destOffset + x] = fbuf[srcOffset + x];
                            }
                        }
                    }
                }
                else
                {
                    for (int y = 0; y < h; y++)
                    {
                        int srcOffset  = y * w;
                        int destOffset = (y + startY) * imgWidth + startX;
                        Array.Copy(fbuf, srcOffset, buf, destOffset, w);
                    }
                }


                WriteableBitmap wfbmp = new WriteableBitmap(imgWidth, imgHeight, bmp.DpiX, bmp.DpiY, PixelFormats.Indexed8, palette);
                wfbmp.WritePixels(new Int32Rect(0, 0, imgWidth, imgHeight), buf, imgWidth, 0);

                DiscreteObjectKeyFrame key = new DiscreteObjectKeyFrame();
                key.KeyTime = new TimeSpan(time);
                //                key.Value = bitmapFrames[i];
                key.Value = wfbmp;
                animation.KeyFrames.Add(key);
                time += delay * span;
            }
            animation.RepeatBehavior = RepeatBehavior.Forever;
            animation.Duration       = new TimeSpan(time);

            Image.RenderTransform = transforms;
            Image.BeginAnimation(Image.SourceProperty, animation);

            Image.Source = bmp;
        }
Exemple #13
0
        /// <inheritdoc />
        protected override string HashImageStream(Stream s, int size)
        {
            s.Seek(0, SeekOrigin.Begin);

            //Create an image with a small size
            var bmi = new BitmapImage
            {
                CreateOptions = BitmapCreateOptions.DelayCreation | BitmapCreateOptions.IgnoreColorProfile,
            };

            bmi.BeginInit();
            bmi.StreamSource      = s;
            bmi.DecodePixelWidth  = size;
            bmi.DecodePixelHeight = size;
            bmi.EndInit();
            bmi.Freeze();

            //Convert the image format to argb32bpp so the pixel size will always be 4
            var fcbm = new FormatConvertedBitmap();

            fcbm.BeginInit();
            fcbm.Source            = bmi;
            fcbm.DestinationFormat = PixelFormats.Bgra32;
            fcbm.EndInit();
            fcbm.Freeze();

            //Copy the image's data to a new array
            //Mostly gotten from here https://social.msdn.microsoft.com/Forums/vstudio/en-US/82a5731e-e201-4aaf-8d4b-062b138338fe/getting-pixel-information-from-a-bitmapimage?forum=wpf
            var pixelSize = PixelFormats.Bgra32.BitsPerPixel / 8;
            var stride    = fcbm.PixelWidth * pixelSize;
            var bytes     = new byte[fcbm.PixelHeight * stride];

            fcbm.CopyPixels(bytes, stride, 0);

            var brightnesses = new float[fcbm.PixelHeight * fcbm.PixelWidth];
            var currentPixel = 0;

            switch (pixelSize)
            {
            case 4:                     //RGBA
                for (int y = 0; y < fcbm.PixelHeight; ++y)
                {
                    for (int x = 0; x < fcbm.PixelWidth; ++x)
                    {
                        var index = y * stride + x * pixelSize;
                        var r     = bytes[index];
                        var g     = bytes[index + 1];
                        var b     = bytes[index + 2];
                        var a     = bytes[index + 3];
                        brightnesses[currentPixel] = CalculateBrightness(a, r, g, b);
                        ++currentPixel;                                 //Could do currentPixel++ above, but that's less clear
                    }
                }
                break;

            case 3:                     //RGB
                for (int y = 0; y < fcbm.PixelHeight; ++y)
                {
                    for (int x = 0; x < fcbm.PixelWidth; ++x)
                    {
                        var index = y * stride + x * pixelSize;
                        var r     = bytes[index];
                        var g     = bytes[index + 1];
                        var b     = bytes[index + 2];
                        brightnesses[currentPixel] = CalculateBrightness(255, r, g, b);
                        ++currentPixel;
                    }
                }
                break;

            default:
                throw new NotSupportedException("The default implementation of this method only supports 32 and 24 bit pixels.");
            }
            return(BrightnessesToString(brightnesses));
        }