Ejemplo n.º 1
0
      /// <summary>
      /// Converts the input BitmapSource to the Pbgra32 format WriteableBitmap which is internally used by the WriteableBitmapEx.
      /// </summary>
      /// <param name="source">The source bitmap.</param>
      /// <returns></returns>
      public static WriteableBitmap ConvertToPbgra32Format(BitmapSource source)
      {
         // Convert to Pbgra32 if it's a different format
         if (source.Format == PixelFormats.Pbgra32)
         {
            return new WriteableBitmap(source);
         }

         var formatedBitmapSource = new FormatConvertedBitmap();
         formatedBitmapSource.BeginInit();
         formatedBitmapSource.Source = source;
         formatedBitmapSource.DestinationFormat = PixelFormats.Pbgra32;
         formatedBitmapSource.EndInit();
         return new WriteableBitmap(formatedBitmapSource);
      }
Ejemplo n.º 2
0
        private void GrayScale()
        {
            /*BitmapImage bitmap = new BitmapImage();
             * bitmap.BeginInit();
             * bitmap.StreamSource = Image;
             * bitmap.EndInit();*/

            FormatConvertedBitmap grayBitmapSource = new FormatConvertedBitmap();

            grayBitmapSource.BeginInit();
            //grayBitmapSource.Source = BitmapImageSource;
            grayBitmapSource.DestinationFormat = PixelFormats.Gray32Float;
            grayBitmapSource.EndInit();

            /*Image grayImage = new Image();
             * grayImage.Width = 300;
             * grayImage.Source = grayBitmapSource;*/

            //imageTest.Source = grayBitmapSource;
        }
        private void GrayScaleButton_OnClick(object sender, RoutedEventArgs e)
        {
            BitmapImage bitmap   = new BitmapImage();
            string      filePath = FilePath.Text;

            bitmap.BeginInit();
            bitmap.UriSource = new Uri(filePath);
            bitmap.EndInit();

            FormatConvertedBitmap grayBitmapSource = new FormatConvertedBitmap();

            grayBitmapSource.BeginInit();

            grayBitmapSource.Source = bitmap;

            grayBitmapSource.DestinationFormat = PixelFormats.Gray32Float;
            grayBitmapSource.EndInit();

            ModifiedImageViewer.Source = grayBitmapSource;
        }
Ejemplo n.º 4
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);
        }
        /// <summary>
        ///     Changes the pixel format.
        /// </summary>
        /// <param name="bmpSource">The BitmapSource source.</param>
        /// <param name="pixFormat">The pix format.</param>
        /// <returns></returns>
        public static FormatConvertedBitmap ChangePixelFormat(BitmapSource bmpSource,
                                                              PixelFormat pixFormat)
        {
            if (bmpSource == null)
            {
                return(null);
            }

            var bmpConverted = new FormatConvertedBitmap();

            // Change properties within a BeginInit/EndInit block.
            bmpConverted.BeginInit();
            bmpConverted.Source = bmpSource;
            // Set to new pixel format.
            bmpConverted.DestinationFormat = pixFormat;
            bmpConverted.EndInit();


            return(bmpConverted);
        }
Ejemplo n.º 6
0
        private void TestingButton()
        {
            // If no image is loaded --- AVOID NULL REFERENCE
            if (ImageViewWindow.Source == null)
            {
                return;
            }
            // make it gray
            FormatConvertedBitmap grayBitmap = new FormatConvertedBitmap();

            grayBitmap.BeginInit();

            grayBitmap.Source = bitmap;

            grayBitmap.DestinationFormat = PixelFormats.Gray8;

            grayBitmap.EndInit();

            ImageViewWindow.Source = grayBitmap;
        }
Ejemplo n.º 7
0
        public void ExecuteSaveAsCommand(object parameter)
        {
            SaveFileDialog saveDlg = new SaveFileDialog();

            saveDlg.Filter = "Tiff(Gray8)|*.tif";

            if (saveDlg.ShowDialog() == true)
            {
                FormatConvertedBitmap convertImage = new FormatConvertedBitmap();
                convertImage.BeginInit();
                convertImage.Source            = Workspace.This.ImageGalleryVM.DisplayImage;
                convertImage.DestinationFormat = PixelFormats.Gray8;
                convertImage.EndInit();
                TiffBitmapEncoder encoder = new TiffBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(convertImage));
                FileStream fileStream = new FileStream(saveDlg.FileName, FileMode.Create, FileAccess.ReadWrite);
                encoder.Save(fileStream);
                fileStream.Close();
            }
        }
Ejemplo n.º 8
0
        public HostTile(HostInstall model)
        {
            InitializeComponent();
            _model           = model;
            this.DataContext = model;

            try
            {
                BitmapImage source = new BitmapImage();
                source.BeginInit();
                source.UriSource = new Uri($"pack://application:,,,/Assets/{model.Name}.jpg", UriKind.Absolute);
                source.EndInit();

                if (!model.HostInstalled)
                {
                    FormatConvertedBitmap newFormatedBitmapSource = new FormatConvertedBitmap();
                    newFormatedBitmapSource.BeginInit();
                    newFormatedBitmapSource.Source            = source;
                    newFormatedBitmapSource.DestinationFormat = PixelFormats.Gray32Float;
                    newFormatedBitmapSource.EndInit();

                    Banner.Source = newFormatedBitmapSource;
                }
                else
                {
                    Banner.Source = source;
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }

            this._model.PropertyChanged += (sender, args) =>
            {
                if (args.PropertyName == nameof(HostInstall.Active) && _model.Active != null)
                {
                    Xceed.Wpf.Toolkit.MessageBox.Show("Application installed", "", MessageBoxButton.OK, MessageBoxImage.Information);
                }
            };
        }
Ejemplo n.º 9
0
        public void Open(string path)
        {
            filePath = path;
            // 读取图片
            BitmapImage sourceImage = new BitmapImage();

            sourceImage.BeginInit();
            sourceImage.UriSource = new Uri(AppDomain.CurrentDomain.BaseDirectory + path, UriKind.Absolute);//打开图片
            sourceImage.EndInit();
            BitmapSource pixelImage = sourceImage;

            // 设置图片格式 rgba
            FormatConvertedBitmap newFormatedBitmapSource = new FormatConvertedBitmap();

            newFormatedBitmapSource.BeginInit();
            newFormatedBitmapSource.Source            = pixelImage;
            newFormatedBitmapSource.DestinationFormat = PixelFormats.Bgra32;
            newFormatedBitmapSource.EndInit();
            pixelImage = newFormatedBitmapSource;

            // 获得图片数据
            width  = pixelImage.PixelWidth;
            height = pixelImage.PixelHeight;

            int stride = pixelImage.PixelWidth * 4;

            byte[] pixels = new byte[pixelImage.PixelHeight * stride];
            pixelImage.CopyPixels(pixels, stride, 0);
            colorData = new Color[width, height];

            for (int i = 0; i < width; i++)
            {
                for (int j = 0; j < height; j++)
                {
                    colorData[i, j].b = pixels[(j * width + i) * 4];
                    colorData[i, j].g = pixels[(j * width + i) * 4 + 1];
                    colorData[i, j].r = pixels[(j * width + i) * 4 + 2];
                    colorData[i, j].a = pixels[(j * width + i) * 4 + 3];
                }
            }
        }
Ejemplo n.º 10
0
        public SixelRawImage(BitmapSource bitmap)
        {
            // https://docs.microsoft.com/en-us/dotnet/framework/wpf/graphics-multimedia/how-to-convert-a-bitmapsource-to-a-different-pixelformat
            FormatConvertedBitmap formatConvertedBitmap = new FormatConvertedBitmap();

            formatConvertedBitmap.BeginInit();
            formatConvertedBitmap.Source            = bitmap;
            formatConvertedBitmap.DestinationFormat = PixelFormats.Bgr24;
            formatConvertedBitmap.EndInit();

            var(width, height) = (formatConvertedBitmap.PixelWidth, formatConvertedBitmap.PixelHeight);
            var stride = (width * formatConvertedBitmap.Format.BitsPerPixel + 7) / 8;

            // 8バイトづつ
            var rawpixeldata = new byte[stride * height];

            formatConvertedBitmap.CopyPixels(rawpixeldata, stride, 0);

            StringBuilder builder = new StringBuilder();

            for (int i = 0; i < (height + 5) / 6; i++)
            {
                for (int k = 0; k < width; k++)
                {
                    int item = 63;
                    for (int j = 0; j < 6; j++)
                    {
                        int index = (6 * i + j) * width * 3 + k * 3;
                        if (index < stride * height && rawpixeldata[index] == 0xFF)
                        {
                            item += 1 << j;
                        }
                    }
                    builder.Append(char.ConvertFromUtf32(item));
                }

                builder.Append("-"); // create new line
            }

            instr = builder.ToString();
        }
        public static FormatConvertedBitmap ConvertToBgr32Format(BitmapSource source)
        {
            // Convert to Pbgra32 if it's a different format
            //if (source.Format == PixelFormats.Bgr32) {
            //    return new WriteableBitmap(source);
            //}
            var formattedBitmapSource = new FormatConvertedBitmap();

            formattedBitmapSource.BeginInit();
            formattedBitmapSource.Source            = source;
            formattedBitmapSource.DestinationFormat = PixelFormats.Bgr32;
            formattedBitmapSource.EndInit();
            //formattedBitmapSource.CopyPixels();
            return(formattedBitmapSource);
            //WriteableBitmap wb = new WriteableBitmap(formatedBitmapSource);
            ////delete

            //formatedBitmapSource = null;
            //GC.Collect();
            //return wb;
        }
Ejemplo n.º 12
0
        public static void SetArmySelected(string armySource)
        {
            foreach (KeyValuePair <Image, string> image in allImages)
            {
                if (String.IsNullOrEmpty(armySource) || (armySource == image.Value))
                {
                    image.Key.Source = new BitmapImage(new Uri(image.Value));
                }

                else
                {
                    FormatConvertedBitmap bwImage = new FormatConvertedBitmap();
                    bwImage.BeginInit();
                    bwImage.Source            = new BitmapImage(new Uri(image.Value));
                    bwImage.DestinationFormat = PixelFormats.Gray8;
                    bwImage.EndInit();

                    image.Key.Source = bwImage;
                }
            }
        }
Ejemplo n.º 13
0
        private void Map_MenuItem_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();

            openFileDialog.Filter      = "Image Files (*.bmp, *.jpg, *.png, *.gif)|*.bmp;*.jpg; *.png; *.gif";
            openFileDialog.FilterIndex = 1;

            if (openFileDialog.ShowDialog() == true)
            {
                System.IO.FileInfo File         = new System.IO.FileInfo(openFileDialog.FileName);
                BitmapImage        coloredImage = new BitmapImage(new Uri(openFileDialog.FileName));

                FormatConvertedBitmap grayBitmap = new FormatConvertedBitmap();
                grayBitmap.BeginInit();
                grayBitmap.Source            = coloredImage;
                grayBitmap.DestinationFormat = PixelFormats.Gray8;
                grayBitmap.EndInit();

                Map.Background = new ImageBrush(grayBitmap);
            }
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="bitmap">Source image</param>
        /// <param name="converter">Converter to use</param>
        public unsafe ColorImage(BitmapSource bitmap, ColorSpaceConverter converter)
        {
            float o1, o2, o3;
            int   rows    = bitmap.PixelHeight;
            int   columns = bitmap.PixelWidth;

            _handler = new FloatArrayHandler(rows, columns, 3);

            FormatConvertedBitmap bmp = new FormatConvertedBitmap();

            bmp.BeginInit();
            bmp.Source            = bitmap;
            bmp.DestinationFormat = PixelFormats.Rgb24;
            bmp.EndInit();
            byte[] pixels = new byte[rows * columns * 3];
            bmp.CopyPixels(pixels, columns * 3, 0);
            fixed(byte *src = pixels)
            {
                fixed(float *dst = _handler.RawArray)
                {
                    byte * srcPtr = src;
                    float *dstPtr = dst;
                    int    length = rows * columns;

                    while (length-- > 0)
                    {
                        float i1 = *srcPtr++;
                        float i2 = *srcPtr++;
                        float i3 = *srcPtr++;
                        o1 = o2 = o3 = 0;
                        converter(i1, i2, i3, ref o1, ref o2, ref o3);
                        *dstPtr++ = o1;
                        *dstPtr++ = o2;
                        *dstPtr++ = o3;
                    }
                }
            }

            pixels = null;
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Construction d'un module à partir de son chemin d'accès
        /// </summary>
        /// <param name="path"></param>
        public Module(string path)
        {
            if (File.Exists(path))
            {
                // Enregistrement du nom de fichier du module (avec l'extension)
                this.file_name = Path.GetFileName(path);

                // Lecture du fichier app.json du module
                Stream         propertiesFile = Assembly.LoadFile(path).GetManifestResourceStream("Project_Manager_Module.Module.app.json");
                StreamReader   reader         = new StreamReader(propertiesFile);
                JsonTextReader jsonReader     = new JsonTextReader(reader);
                JObject        jsonContent    = (JObject)JToken.ReadFrom(jsonReader);

                // Enregistrement des propriétés
                this.name          = jsonContent["name"].ToString();
                this.description   = jsonContent["description"].ToString();
                this.require_login = (bool)jsonContent["require_login"];

                // Fermeture du lecteur
                jsonReader.Close();
                reader.Close();

                // Lecture du logo du module
                Stream      imgStream = Assembly.LoadFile(path).GetManifestResourceStream("Project_Manager_Module.Module.logo.png");
                BitmapImage logo      = new BitmapImage();
                logo.BeginInit();
                logo.StreamSource = imgStream;
                logo.EndInit();
                imgStream.Close();
                this.logo = logo;

                // Création de la version en nuances de gris du logo
                FormatConvertedBitmap logoGreyScaled = new FormatConvertedBitmap();
                logoGreyScaled.BeginInit();
                logoGreyScaled.Source            = this.logo;
                logoGreyScaled.DestinationFormat = PixelFormats.Gray32Float;
                logoGreyScaled.EndInit();
                this.logo_greyscale = logoGreyScaled;
            }
        }
Ejemplo n.º 16
0
        private void getBackImageSource(BitmapSource i)
        {
            if (i == null)
            {
                EnablebackImage   = null;
                unEnablebackImage = null;
                return;
            }
            FormatConvertedBitmap b = new FormatConvertedBitmap();

            b.BeginInit();
            b.Source            = i;
            b.DestinationFormat = PixelFormats.Gray8;
            b.EndInit();
            FormatConvertedBitmap b1 = new FormatConvertedBitmap();

            b1.BeginInit();
            b1.Source = i;
            b1.EndInit();
            EnablebackImage   = b1;
            unEnablebackImage = b;
        }
Ejemplo n.º 17
0
        public static FormatConvertedBitmap ConvertToGrayScale(string fileName)
        {
            BitmapImage myBitmapImage = new BitmapImage();

            // BitmapSource objects like BitmapImage can only have their properties
            // changed within a BeginInit/EndInit block.
            myBitmapImage.BeginInit();
            myBitmapImage.UriSource = new Uri(fileName, UriKind.Relative);

            // To save significant application memory, set the DecodePixelWidth or
            // DecodePixelHeight of the BitmapImage value of the image source to the desired
            // height or width of the rendered image. If you don't do this, the application will
            // cache the image as though it were rendered as its normal size rather then just
            // the size that is displayed.
            // Note: In order to preserve aspect ratio, set DecodePixelWidth
            // or DecodePixelHeight but not both.
            myBitmapImage.EndInit();

            ////////// Convert the BitmapSource to a new format ////////////
            // Use the BitmapImage created above as the source for a new BitmapSource object
            // which is set to a gray scale format using the FormatConvertedBitmap BitmapSource.
            // Note: New BitmapSource does not cache. It is always pulled when required.

            FormatConvertedBitmap newFormatedBitmapSource = new FormatConvertedBitmap();

            // BitmapSource objects like FormatConvertedBitmap can only have their properties
            // changed within a BeginInit/EndInit block.
            newFormatedBitmapSource.BeginInit();

            // Use the BitmapSource object defined above as the source for this new
            // BitmapSource (chain the BitmapSource objects together).
            newFormatedBitmapSource.Source = myBitmapImage;

            // Set the new format to Gray32Float (grayscale).
            newFormatedBitmapSource.DestinationFormat = PixelFormats.Gray32Float;
            newFormatedBitmapSource.EndInit();

            return(newFormatedBitmapSource);
        }
Ejemplo n.º 18
0
        private static Image CreateIcon(drawing.Bitmap image, out Image grayIcon)
        {
            var icon = new Image();

            var iconSource = GetIconSource(image);

            icon.Source = iconSource;

            grayIcon = new Image();
            FormatConvertedBitmap grayBitmap = new FormatConvertedBitmap();

            grayBitmap.BeginInit();
            grayBitmap.Source            = iconSource;
            grayBitmap.DestinationFormat = PixelFormats.Gray8;
            grayIcon.OpacityMask         = new ImageBrush(iconSource);
            grayBitmap.EndInit();
            // Set Source property of Image

            grayIcon.Source = grayBitmap;

            return(icon);
        }
Ejemplo n.º 19
0
        //---------------------------------------------------------------------------

        /**
         * @fn		public void SetImage(BitmapImage bmpimg, Stretch stretch = Stretch.None)
         * @brief	WriteableBitmap Type을 Align Control에 Set.
         * @return	void
         * @param	BitmapImage     bmpimg  : Source Image.
         * @param	Stretch         stretch : Stretch Option.
         * @remark
         * - Stretch Option을 Fill로 할 경우, 배율이 맞지 않을 수 있음.
         * - 배율 조정 + Fit을 원하면 GetFitScale을 사용하여 수동으로 화면 Scale 조정 할 것.
         * @author	선경규(Kyeong Kyu - Seon)
         * @date	2020/3/9  16:40
         */
        public void SetImage(BitmapImage bmpimg, Stretch stretch = Stretch.None)
        {
            WriteableBitmap wbm = null;

            FormatConvertedBitmap newFormatedBitmapSource = new FormatConvertedBitmap();

            // BitmapSource objects like FormatConvertedBitmap can only have their properties
            // changed within a BeginInit/EndInit block.
            newFormatedBitmapSource.BeginInit();

            // Use the BitmapSource object defined above as the source for this new
            // BitmapSource (chain the BitmapSource objects together).
            newFormatedBitmapSource.Source = bmpimg;

            // Set the new format to Gray32Float (grayscale).
            newFormatedBitmapSource.DestinationFormat = PixelFormats.Bgr24;
            newFormatedBitmapSource.EndInit();

            wbm = new WriteableBitmap(newFormatedBitmapSource);

            m_ImgBrs         = new ImageBrush(wbm);
            m_ImgBrs.Stretch = stretch;
            if (m_ImgBrs != null)
            {
                m_ImgBrsOrg = m_ImgBrs.Clone();
            }
            if (m_ImgBrs.Stretch == Stretch.None)
            {
                lib_Canvas.Width  = m_ImgBrs.ImageSource.Width;
                lib_Canvas.Height = m_ImgBrs.ImageSource.Height;
            }

            m_nWidth   = (int)m_ImgBrs.ImageSource.Width;
            m_nHeight  = (int)m_ImgBrs.ImageSource.Height;
            m_nChannel = (int)(wbm.Format.BitsPerPixel / 8.0);

            lib_Canvas.Background = new ImageBrush(wbm);
            m_dScale = myScaleTransform.ScaleX;
        }
Ejemplo n.º 20
0
        public void UpdateImage()
        {
            try
            {
                Uri myUri = new Uri(m_images.m_pathThumb, UriKind.RelativeOrAbsolute);
                BmpBitmapDecoder decoder = new BmpBitmapDecoder(myUri, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad);
                BitmapSource     bi3     = decoder.Frames[0];

                // Begin: Fix 61368
                if (m_images.m_colorMode == EnumColorType.black_white)
                {
                    bi3 = BitmapFrame.Create(new TransformedBitmap(bi3, new ScaleTransform(0.1, 0.1)));

                    // https://msdn.microsoft.com/en-us/library/system.windows.media.imaging.formatconvertedbitmap(v=vs.100).aspx
                    FormatConvertedBitmap bmpSrc = new FormatConvertedBitmap();
                    bmpSrc.BeginInit();
                    bmpSrc.Source            = bi3;
                    bmpSrc.DestinationFormat = PixelFormats.Gray2;
                    bmpSrc.EndInit();

                    imgBody.Source = bmpSrc;
                }
                else
                {
                    imgBody.Source = bi3;
                }
                // End: Fix 61368

                this.Background = Brushes.White;
                this.Width      = 105;
                this.Height     = 140;
            }
            catch
            {
            }

            m_iSimgReady = (null != imgBody.Source);
        }
Ejemplo n.º 21
0
        private static ImageSource Convert(BitmapSource input, PixelFormat format)
        {
            ////////// Convert the BitmapSource to a new format ////////////
            // Use the BitmapImage created above as the source for a new BitmapSource object
            // which is set to a gray scale format using the FormatConvertedBitmap BitmapSource.
            // Note: New BitmapSource does not cache. It is always pulled when required.

            FormatConvertedBitmap newFormatedBitmapSource = new FormatConvertedBitmap();

            // BitmapSource objects like FormatConvertedBitmap can only have their properties
            // changed within a BeginInit/EndInit block.
            newFormatedBitmapSource.BeginInit();

            // Use the BitmapSource object defined above as the source for this new
            // BitmapSource (chain the BitmapSource objects together).
            newFormatedBitmapSource.Source = input;

            // Set the new format to Gray32Float (grayscale).
            newFormatedBitmapSource.DestinationFormat = format;
            newFormatedBitmapSource.EndInit();

            return(newFormatedBitmapSource);
        }
        static ImageBrush LoadImage(string Dir)
        {
            BitmapImage bmp = new BitmapImage();

            bmp.BeginInit();
            bmp.UriSource         = new Uri(Dir);
            bmp.DecodePixelWidth  = 100;
            bmp.DecodePixelHeight = 100;
            bmp.EndInit();

            FormatConvertedBitmap convBMP = new FormatConvertedBitmap();

            convBMP.BeginInit();
            convBMP.Source            = bmp;
            convBMP.DestinationFormat = PixelFormats.Bgra32;
            Console.WriteLine(convBMP.Source.Format);
            convBMP.EndInit();

            ImageBrush ibrush = new ImageBrush();

            ibrush.ImageSource = CreateTransparent(convBMP, makeTransparnt);
            return(ibrush);
        }
Ejemplo n.º 23
0
        private FormatConvertedBitmap ColorConv(TransformedBitmap input)
        {
            FormatConvertedBitmap ret = new FormatConvertedBitmap();

            ret.BeginInit();
            ret.Source = input;
            switch (PictureConverter.ConvOptions.PixelFormat)
            {
            case PixFormat.Bit24:
                ret.DestinationFormat = PixelFormats.Rgb24;
                break;

            case PixFormat.Bit32:
                ret.DestinationFormat = PixelFormats.Bgra32;
                break;

            case PixFormat.Indexed:
                ret.DestinationFormat = PixelFormats.Indexed8;
                break;
            }
            ret.EndInit();
            return(ret);
        }
        public MemoryStream ReduceColorDepth(Bitmap bmp)
        {
            var ms = new MemoryStream();

            bmp.Save(ms, ImageFormat.Png);

            var bi = new BitmapImage();

            bi.BeginInit();
            bi.StreamSource = ms;
            bi.EndInit();

            var newFormatedBitmapSource = new FormatConvertedBitmap();

            newFormatedBitmapSource.BeginInit();

            newFormatedBitmapSource.Source = bi;

            var myPalette = new BitmapPalette(bi, 256);

            newFormatedBitmapSource.DestinationPalette = myPalette;

            //Set PixelFormats
            newFormatedBitmapSource.DestinationFormat = PixelFormats.Indexed8;
            newFormatedBitmapSource.EndInit();

            var pngBitmapEncoder = new PngBitmapEncoder();

            pngBitmapEncoder.Interlace = PngInterlaceOption.Off;
            pngBitmapEncoder.Frames.Add(BitmapFrame.Create(newFormatedBitmapSource));

            var memstream = new MemoryStream();

            pngBitmapEncoder.Save(memstream);
            memstream.Position = 0;
            return(memstream);
        }
Ejemplo n.º 25
0
        public Bitmap BitmapFromSource(BitmapSource bitmapsource)
        {
            try
            {
                //convert image format
                var src = new FormatConvertedBitmap();
                src.BeginInit();
                src.Source            = bitmapsource;
                src.DestinationFormat = System.Windows.Media.PixelFormats.Bgra32;
                src.EndInit();

                //copy to bitmap
                Bitmap bitmap = new Bitmap(src.PixelWidth, src.PixelHeight, PixelFormat.Format32bppArgb);
                var    data   = bitmap.LockBits(new Rectangle(Point.Empty, bitmap.Size), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb);
                src.CopyPixels(System.Windows.Int32Rect.Empty, data.Scan0, data.Height * data.Stride, data.Stride);
                bitmap.UnlockBits(data);

                return(bitmap);
            }
            catch (Exception e)
            {
                return(null);
            }
        }
Ejemplo n.º 26
0
    //public override event EventHandler<ExceptionEventArgs> DecodeFailed;
    //public override event EventHandler DownloadCompleted;
    //public override event EventHandler<ExceptionEventArgs> DownloadFailed;
    //public override event EventHandler<DownloadProgressEventArgs> DownloadProgress;


    #region statics
    /// <summary>
    /// Converts BitmapSource to Bitmap.
    /// </summary>
    /// <param name="sourceWpf">BitmapSource</param>
    /// <returns>Bitmap</returns>
    private static System.Drawing.Bitmap ConvertToBitmap(System.Windows.Media.Imaging.BitmapSource sourceWpf)
    {
        System.Windows.Media.Imaging.BitmapSource bmpWpf = sourceWpf;

        // PixelFormat settings/conversion
        System.Drawing.Imaging.PixelFormat formatBmp = System.Drawing.Imaging.PixelFormat.Format32bppArgb;
        if (sourceWpf.Format == PixelFormats.Bgr24)
        {
            formatBmp = System.Drawing.Imaging.PixelFormat.Format24bppRgb;
        }
        else if (sourceWpf.Format == System.Windows.Media.PixelFormats.Pbgra32)
        {
            formatBmp = System.Drawing.Imaging.PixelFormat.Format32bppPArgb;
        }
        else if (sourceWpf.Format != System.Windows.Media.PixelFormats.Bgra32)
        {
            // Convert BitmapSource
            FormatConvertedBitmap convertWpf = new FormatConvertedBitmap();
            convertWpf.BeginInit();
            convertWpf.Source            = sourceWpf;
            convertWpf.DestinationFormat = PixelFormats.Bgra32;
            convertWpf.EndInit();
            bmpWpf = convertWpf;
        }

        // Copy/Convert to Bitmap
        var bmp = new System.Drawing.Bitmap(bmpWpf.PixelWidth, bmpWpf.PixelHeight, formatBmp);

        System.Drawing.Rectangle rect = new System.Drawing.Rectangle(System.Drawing.Point.Empty, bmp.Size);
        BitmapData data = bmp.LockBits(rect, ImageLockMode.WriteOnly, formatBmp);

        bmpWpf.CopyPixels(System.Windows.Int32Rect.Empty, data.Scan0, data.Height * data.Stride, data.Stride);
        bmp.UnlockBits(data);

        return(bmp);
    }
Ejemplo n.º 27
0
        private byte[] GetDecodedPixels(Int32Rect bounds)
        {
            Debug.Assert(
                (bounds.X >= 0) &&
                (bounds.Y >= 0) &&
                ((bounds.X + bounds.Width) <= _pixelWidth) &&
                ((bounds.Y + bounds.Height) <= _pixelHeight)
                );

            int stride = bounds.Width * 4;

            byte[] pixels = new Byte[stride * bounds.Height];

            FormatConvertedBitmap converter = new FormatConvertedBitmap();

            converter.BeginInit();
            converter.Source            = _image;
            converter.DestinationFormat = PixelFormats.Pbgra32;
            converter.EndInit();

            converter.CriticalCopyPixels(bounds, pixels, stride, 0);

            return(pixels);
        }
Ejemplo n.º 28
0
        public override void Write(Stream file, ImageData image)
        {
            var header = new byte[0x14];

            var depth       = (short)(24 == image.BPP ? 0 : 32 == image.BPP ? 1 : 2);
            var compression = (ushort)3;
            var flags       = (ushort)17;
            var mode        = (ushort)0;

            using (var memeStream = new MemoryStream(header))
            {
                using (var binaryWriter = new BinaryWriter(memeStream))
                {
                    binaryWriter.Write(Signature);
                    binaryWriter.Write((ushort)image.OffsetX);
                    binaryWriter.Write((ushort)image.OffsetY);
                    binaryWriter.Write((ushort)image.Width);
                    binaryWriter.Write((ushort)image.Height);
                    binaryWriter.Write(compression);
                    binaryWriter.Write(flags);
                    binaryWriter.Write(depth);
                    binaryWriter.Write(mode);
                }
            }

            var metaData = ReadMetaData(BinaryStream.FromArray(header, ""));

            var bitmap      = image.Bitmap;
            var pixelFormat = CheckFormat(image.BPP);

            int stride = (int)(image.Width * pixelFormat.BitsPerPixel / 8 + 3) & ~3;

            if (pixelFormat != bitmap.Format)
            {
                var converted_bitmap = new FormatConvertedBitmap();
                converted_bitmap.BeginInit();
                converted_bitmap.Source            = image.Bitmap;
                converted_bitmap.DestinationFormat = pixelFormat;
                converted_bitmap.EndInit();
                bitmap = converted_bitmap;
            }

            var data     = new byte[image.Height * stride];
            var row_data = new byte[stride];
            var rect     = new Int32Rect(0, 0, (int)image.Width, 1);

            for (uint row = 0; row < image.Height; ++row)
            {
                bitmap.CopyPixels(rect, row_data, stride, 0);
                rect.Y++;
                row_data.CopyTo(data, row * stride);
            }

            using (var binaryWriter = new BinaryWriter(file))
            {
                binaryWriter.Write(header);
                using (var writer = new Writer(data,
                                               binaryWriter, (CrxMetaData)metaData))
                {
                    writer.Write();
                }
            }
        }
Ejemplo n.º 29
0
        /// <summary>
        /// 根据指定的 Enable 图像,自动生成对象的 Enable 图像和 Disable 图像。
        /// </summary>
        public void GenerateSources(ImageSource enabledSource)
        {
            this.EnabledSource = enabledSource;
            if (enabledSource == null)
            {
                this.DisabledSource = null;
            }
            else if (enabledSource is BitmapSource)
            {
                try
                {
                    // 图像灰处理。因为缺省的 FormatConvertedBitmap.Gray8 不支持 Alpha 通道,因此
                    // 只能自己写函数来转换成灰度图像了。
                    BitmapSource source = enabledSource as BitmapSource;

                    // 将图像转换成 BGRA32 的固定格式
                    if (!source.Format.Equals(PixelFormats.Bgra32))
                    {
                        FormatConvertedBitmap newFormatedBitmapSource = new FormatConvertedBitmap();
                        newFormatedBitmapSource.BeginInit();
                        newFormatedBitmapSource.Source            = source;
                        newFormatedBitmapSource.DestinationFormat = PixelFormats.Bgra32;
                        newFormatedBitmapSource.EndInit();
                        //
                        source = newFormatedBitmapSource;
                    }

                    // 灰度化的三个颜色分量的权值
                    const int RedPart   = (int)(0.299 * 65536);
                    const int GreenPart = (int)(0.587 * 65536);
                    const int BluePart  = (65536 - RedPart - GreenPart);

                    // 得到图像的点阵数据
                    int    stride = source.PixelWidth * 4;
                    byte[] pixels = new byte[stride * source.PixelHeight];
                    source.CopyPixels(pixels, stride, 0);
                    // 循环转换所有的点
                    for (int j = 0, offset = 0; j < source.PixelHeight; ++j)
                    {
                        for (int i = 0; i < source.PixelWidth; ++i, offset += 4)
                        {
                            byte gray = (byte)((pixels[offset + 2] * BluePart +
                                                pixels[offset + 1] * GreenPart +
                                                pixels[offset + 0] * RedPart +
                                                65536 / 2) / 65536);
                            pixels[offset + 0]         =
                                pixels[offset + 1]     =
                                    pixels[offset + 2] = gray;
                        }
                    }

                    // 创建新图像
                    source = BitmapImage.Create(source.PixelWidth, source.PixelHeight,
                                                source.DpiX, source.DpiY, source.Format, source.Palette, pixels, stride);
                    //
                    this.DisabledSource = source;
                }
                catch (Exception)
                {
                    this.DisabledSource = null;
                }
            }
            else
            {
                this.DisabledSource = null;
            }

            this.UpdateSource();
        }
Ejemplo n.º 30
0
        private string DecodeImageAndCompress(string file, Func <int, int, int, int, TileData> tileGetter)
        {
            BitmapImage image = new BitmapImage(new Uri(file, UriKind.Absolute));

            FormatConvertedBitmap dec = new FormatConvertedBitmap();

            dec.BeginInit();
            dec.Source            = image;
            dec.DestinationFormat = PixelFormats.Bgra32;
            dec.EndInit();

            int height = dec.PixelHeight;
            int width  = dec.PixelWidth;
            int stride = width * 4;
            var bytes  = new byte[height * width * 4];

            dec.CopyPixels(bytes, stride, 0);

            StringBuilder sb = new StringBuilder();

            sb.AppendLine("local b = require 'map_gen.shared.builders'");
            sb.AppendLine("return b.decompress({");
            sb.Append("height = ").Append(height).AppendLine(",");
            sb.Append("width = ").Append(width).AppendLine(",");
            sb.AppendLine("data = {");

            for (int i = 0; i < height; i++)
            {
                sb.Append("\t{");

                TileData prev  = null;
                int      count = 0;

                for (int j = 0; j < width; j++)
                {
                    int  k = (i * width + j) * 4;
                    byte b = bytes[k];
                    byte g = bytes[k + 1];
                    byte r = bytes[k + 2];
                    byte a = bytes[k + 3];

                    var tile = tileGetter(r, g, b, a);

                    if (prev == null)
                    {
                        prev  = tile;
                        count = 1;
                    }
                    else if (prev == tile)
                    {
                        count++;
                    }
                    else
                    {
                        sb.Append(prev.Number).Append(',').Append(count).Append(',');
                        prev  = tile;
                        count = 1;
                    }
                }
                if (prev != null)
                {
                    sb.Append(prev.Number).Append(',').Append(count).Append(',');
                }

                sb.AppendLine("},");
            }

            sb.AppendLine("}");
            sb.Append("})");

            return(sb.ToString());
        }
Ejemplo n.º 31
0
        public PixelFormatsExample()
        {
            //<SnippetPixelFormatConversion>

            ///// Create a BitmapImage and set it's DecodePixelWidth to 200. Use  /////
            ///// this BitmapImage as a source for other BitmapSource objects.    /////

            BitmapImage myBitmapImage = new BitmapImage();

            // BitmapSource objects like BitmapImage can only have their properties
            // changed within a BeginInit/EndInit block.
            myBitmapImage.BeginInit();
            myBitmapImage.UriSource = new Uri("sampleImages/WaterLilies.jpg", UriKind.Relative);

            // To save significant application memory, set the DecodePixelWidth or
            // DecodePixelHeight of the BitmapImage value of the image source to the desired
            // height or width of the rendered image. If you don't do this, the application will
            // cache the image as though it were rendered as its normal size rather then just
            // the size that is displayed.
            // Note: In order to preserve aspect ratio, set DecodePixelWidth
            // or DecodePixelHeight but not both.
            myBitmapImage.DecodePixelWidth = 200;
            myBitmapImage.EndInit();

            ////////// Convert the BitmapSource to a new format ////////////
            // Use the BitmapImage created above as the source for a new BitmapSource object
            // which is set to a gray scale format using the FormatConvertedBitmap BitmapSource.
            // Note: New BitmapSource does not cache. It is always pulled when required.

            FormatConvertedBitmap newFormatedBitmapSource = new FormatConvertedBitmap();

            // BitmapSource objects like FormatConvertedBitmap can only have their properties
            // changed within a BeginInit/EndInit block.
            newFormatedBitmapSource.BeginInit();

            // Use the BitmapSource object defined above as the source for this new
            // BitmapSource (chain the BitmapSource objects together).
            newFormatedBitmapSource.Source = myBitmapImage;


            // Set the new format to Gray32Float (grayscale).
            newFormatedBitmapSource.DestinationFormat = createPixelFormat();
            newFormatedBitmapSource.EndInit();
            //</SnippetPixelFormatConversion>

            // Create Image Element
            Image myImage = new Image();

            myImage.Width = 200;
            //set image source
            myImage.Source = newFormatedBitmapSource;

            // Add Image to the UI
            StackPanel myStackPanel = new StackPanel();

            myStackPanel.Children.Add(myImage);

            // Add TextBox
            // TextBlock myTextBlock = new TextBlock();
            // myTextBlock.Text = "Mask Value: " + stringOfValues + " bpp: " + bpp.ToString();
            // myStackPanel.Children.Add(myTextBlock);
            this.Content = myStackPanel;
        }