Exemple #1
1
        /// <summary>
        /// Retrieve the palette for the quantized image
        /// </summary>
        /// <param name="original">Any old palette, this is overrwritten</param>
        /// <returns>The new color palette</returns>
        protected override ColorPalette GetPalette(ColorPalette original)
        {
            // First off convert the octree to _maxColors colors
            List<Color> palette = _octree.Palletize(_maxColors - 1);

            // Then convert the palette based on those colors
            for (int index = 0; index < palette.Count; index++)
            {
                original.Entries[index] = palette[index];
            }

            #if ORIGINAL_CODE
            for (int i = palette.Count; i < original.Entries.Length; ++i)
            {
                original.Entries[i] = Color.FromArgb(255, 0, 0, 0);
            }

            // Add the transparent color
            original.Entries[_maxColors] = Color.FromArgb(0, 0, 0, 0);
            #else // PCX Plugin
            // For PCX: Pad with transparency
            for (int i = palette.Count; i < original.Entries.Length; ++i)
                original.Entries[i] = Color.Transparent;
            #endif
            return original;
        }
Exemple #2
0
        /// <summary>
        /// Retrieve the palette for the quantized image
        /// </summary>
        /// <param name="original">Any old palette, this is overrwritten</param>
        /// <returns>The new color palette</returns>
        protected override ColorPalette GetPalette( ColorPalette original )
        {
            // First off convert the octree to _maxColors colors
            ArrayList	palette = _octree.Palletize ( _maxColors - 1 ) ;

            //// Then convert the palette based on those colors
            //for ( int index = 0 ; index < palette.Count ; index++ )
            //	original.Entries[index] = (Color)palette[index] ;

            //// Add the transparent color
            //original.Entries[_maxColors] = Color.FromArgb ( 0 , 0 , 0 , 0 ) ;

            // Then convert the palette based on those colors
            for (int index = 0; index < palette.Count; index++)
            {
                Color TestColor = (Color)palette[index];
                //Test set transparent color when color transparency used
                if (TestColor.ToArgb() == Color.Transparent.ToArgb())
                {
                    TestColor = Color.FromArgb(0, 0, 0, 0);
                }
                original.Entries[index] = TestColor;
            }
            //Clear unused palette entries
            for (int index = palette.Count; index < _maxColors; index++)
            {
                original.Entries[index] = Color.FromArgb(255, 0, 0, 0);
            }
            // Add the transparent color when alpha transparency used
            original.Entries[_maxColors] = Color.FromArgb(0, Color.Transparent);
            return original;
        }
Exemple #3
0
        public Bitmap getImg(int index)
        {
            int ofs = 0;

            for (int i = 0; i < index; i++)
            {
                ofs += sizes[i * 2] * sizes[i * 2 + 1];
            }
            int    w   = sizes[index * 2];
            int    h   = sizes[index * 2 + 1];
            Bitmap bmp = new Bitmap(w, h, System.Drawing.Imaging.PixelFormat.Format8bppIndexed);

            System.Drawing.Imaging.ColorPalette pal = bmp.Palette;
            Palette pl = Palettes.get().getPalette(comboBox2.Text);

            for (int i = 0; i < 256; i++)
            {
                pal.Entries[i] = pl.cls[i];
            }
            bmp.Palette = pal;
            byte[] data = new byte[w * h];
            Array.Copy(vga, ofs, data, 0, w * h);
            BitmapData bd = bmp.LockBits(new Rectangle(0, 0, w, h),
                                         ImageLockMode.WriteOnly, bmp.PixelFormat);

            for (int i = 0; i < bd.Height; i++)
            {
                System.Runtime.InteropServices.Marshal.Copy(data, (i * bd.Width), new IntPtr(bd.Scan0.ToInt64() + i * bd.Stride), bd.Width);
            }
            bmp.UnlockBits(bd);
            return(bmp);
        }
 private ColorPalette _GetColorPalette()
 {
     int size = -1;
     int status = SafeNativeMethods.Gdip.GdipGetImagePaletteSize(new HandleRef(this, this.nativeImage), out size);
     if (status != 0)
     {
         throw SafeNativeMethods.Gdip.StatusException(status);
     }
     ColorPalette palette = new ColorPalette(size);
     IntPtr ptr = Marshal.AllocHGlobal(size);
     status = SafeNativeMethods.Gdip.GdipGetImagePalette(new HandleRef(this, this.nativeImage), ptr, size);
     try
     {
         if (status != 0)
         {
             throw SafeNativeMethods.Gdip.StatusException(status);
         }
         palette.ConvertFromMemory(ptr);
     }
     finally
     {
         Marshal.FreeHGlobal(ptr);
     }
     return palette;
 }
Exemple #5
0
        public static void ReplaceColorInPalette(ref Image refImage, ColorPalette refPalette, Color victimColor, Color newColor)
        {
            //get it's palette
            ColorPalette ncp = refPalette;

            // Start with the refPalette
            System.Drawing.Imaging.ColorPalette palette = refPalette;
            for (int x = 0; x < palette.Entries.Length; x++)
            {
                System.Drawing.Color color = palette.Entries[x];
                int alpha = 255;
                // if we found our victim
                if (color.R == victimColor.R && color.B == victimColor.B && color.G == victimColor.G)
                {
                    // replace it in the palette
                    ncp.Entries[x] = System.Drawing.Color.FromArgb(victimColor.A, newColor.R, newColor.G, newColor.B);
                }
                else
                {
                    ncp.Entries[x] = System.Drawing.Color.FromArgb(color.A, color.R, color.G, color.B);
                }
            }
            //re-insert the palette
            refImage.Palette = ncp;
        }
Exemple #6
0
		public Palette(Stream s)
		{
			StreamReader input = new StreamReader(s);
			string[] line=new string[0];
			name = input.ReadLine();

			Bitmap b = new Bitmap(1,1,PixelFormat.Format8bppIndexed);
			cp = b.Palette;

			for(byte i=0;i<0xFF;i++)
			{
				string allLine = input.ReadLine().Trim();
				if(allLine[0]==COMMENT)
				{
					i--;
					continue;
				}
				
				line = allLine.Split(',');
				cp.Entries[i] = Color.FromArgb(int.Parse(line[0]),int.Parse(line[1]),int.Parse(line[2]));				
			}
			Color old = cp.Entries[PckImage.TRANSPARENT_COLOR_INDEX];
			cp.Entries[PckImage.TRANSPARENT_COLOR_INDEX]=Color.FromArgb(0,old);
			b.Dispose();
		}
Exemple #7
0
        static ColorPalette MakePalette()
        {
            if (palette != null)
                return palette;

            var bmp = new Bitmap(1, 1, PixelFormat.Format4bppIndexed);
            palette = bmp.Palette;
            palette.Entries[0] = Color.FromArgb(0, 0, 0);
            palette.Entries[1] = Color.FromArgb(0, 0, 162);
            palette.Entries[2] = Color.FromArgb(0, 162, 0);
            palette.Entries[3] = Color.FromArgb(0, 162, 162);
            palette.Entries[4] = Color.FromArgb(162, 0, 0);
            palette.Entries[5] = Color.FromArgb(162, 0, 162);
            palette.Entries[6] = Color.FromArgb(170, 85, 0);
            palette.Entries[7] = Color.FromArgb(168, 168, 168);
            palette.Entries[8] = Color.FromArgb(82, 82, 82);
            palette.Entries[9] = Color.FromArgb(80, 80, 255);
            palette.Entries[10] = Color.FromArgb(80, 255, 80);
            palette.Entries[11] = Color.FromArgb(80, 255, 255);
            palette.Entries[12] = Color.FromArgb(255, 80, 80);
            palette.Entries[13] = Color.FromArgb(255, 80, 255);
            palette.Entries[14] = Color.FromArgb(255, 255, 80);
            palette.Entries[15] = Color.FromArgb(255, 255, 255);

            return palette;
        }
        /// <summary>
        /// Retrieve the palette for the quantized image
        /// </summary>
        /// <param name="palette">Any old palette, this is overrwritten</param>
        /// <returns>The new color palette</returns>
        protected override ColorPalette GetPalette( ColorPalette palette )
        {
            for ( int index = 0 ; index < _colors.Length ; index++ )
                palette.Entries[index] = _colors[index] ;

            return palette ;
        }
 private static ColorPalette BuildPalette(ColorPalette palette, PaletteColorHistory[] paletteHistogram)
 {
     for (int paletteColorIndex = 0; paletteColorIndex < paletteHistogram.Length; paletteColorIndex++)
     {
         palette.Entries[paletteColorIndex] = paletteHistogram[paletteColorIndex].ToNormalizedColor();
     }
     return palette;
 }
        public Bitmap GetTransparent(Color transparentColor, byte tranparenz)
        {
            Bitmap tmpBitmap;
            int    newStride = 0;

            if (pixelFormat == System.Drawing.Imaging.PixelFormat.Format24bppRgb)
            {
                newStride = stride / 3 * 4;
            }
            else if (pixelFormat == System.Drawing.Imaging.PixelFormat.Format32bppArgb)
            {
                newStride = stride;
            }
            else
            {
                tmpBitmap = (Bitmap)Bild.Clone();
                System.Drawing.Imaging.ColorPalette tmpColorPalette = tmpBitmap.Palette;
                for (int i = 0; i < colorPalette.Entries.Length; i++)
                {
                    if (colorPalette.Entries[i].ToArgb() == transparentColor.ToArgb())
                    {
                        Color col = Color.FromArgb(tranparenz, tmpBitmap.Palette.Entries[i].R,
                                                   tmpBitmap.Palette.Entries[i].G, tmpBitmap.Palette.Entries[i].B);
                        tmpColorPalette.Entries[i] = col;
                    }
                }
                tmpBitmap.Palette = tmpColorPalette;
                return(tmpBitmap);
            }

            tmpBitmap = new Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
            byte[] tmpBildDaten = new byte[height * newStride];
            for (int y = 0; y < height; y++)
            {
                for (int x = 0; x < width; x++)
                {
                    if (color[x, y].ToArgb() != transparentColor.ToArgb())
                    {
                        tmpBildDaten[y * width * 4 + x * 4 + 3] = color[x, y].A;
                    }
                    else
                    {
                        tmpBildDaten[y * width * 4 + x * 4 + 3] = tranparenz;
                    }
                    tmpBildDaten[y * width * 4 + x * 4 + 2] = color[x, y].R;
                    tmpBildDaten[y * width * 4 + x * 4 + 1] = color[x, y].G;
                    tmpBildDaten[y * width * 4 + x * 4]     = color[x, y].B;
                }
            }
            System.Drawing.Imaging.BitmapData tmpBmpData =
                tmpBitmap.LockBits(rect, System.Drawing.Imaging.ImageLockMode.WriteOnly,
                                   tmpBitmap.PixelFormat);
            IntPtr ptr = tmpBmpData.Scan0;

            System.Runtime.InteropServices.Marshal.Copy(tmpBildDaten, 0, ptr, height * newStride);
            tmpBitmap.UnlockBits(tmpBmpData);
            return(tmpBitmap);
        }
Exemple #11
0
        private void ImageCallbackFunc(IntPtr pData, ref MyCamera.MV_FRAME_OUT_INFO_EX pFrameInfo, IntPtr pUser)
        {
            try
            {
                lock (this)
                {
                    newBmp = new Bitmap(pFrameInfo.nWidth, pFrameInfo.nHeight, PixelFormat.Format8bppIndexed);
                    // Lock the bits of the bitmap.
                    BitmapData bmpData = newBmp.LockBits(new Rectangle(0, 0, newBmp.Width, newBmp.Height), ImageLockMode.ReadWrite, newBmp.PixelFormat);
                    IntPtr     ptrBmp  = bmpData.Scan0;

                    //palette
                    System.Drawing.Imaging.ColorPalette palette = newBmp.Palette;
                    for (int i = 0; i < 256; ++i)
                    {
                        palette.Entries[i] = Color.FromArgb(255, i, i, i);
                    }
                    newBmp.Palette = palette;

                    //convert to bytes data
                    newBytes = new byte[bmpData.Stride * newBmp.Height];
                    Marshal.Copy(pData, newBytes, 0, newBytes.Length);
                    //reverse y
                    if (this.reverseY)
                    {
                        newBytes = this.bytesReverseY(newBytes, bmpData.Stride, newBmp.Height);
                    }
                    //copy to ptr
                    Marshal.Copy(newBytes, 0, ptrBmp, newBytes.Length);
                    newBmp.UnlockBits(bmpData);

                    this.CurrentBytes = newBytes;
                    this.LastBmp      = this.CurrentBmp;
                    this.CurrentBmp   = newBmp;
                }

                BmpGrabedEvnet.Set();
                this.TriggerSts.Update(true);
                BitmapGrabbed?.Invoke(CurrentBmp, true);
                BytesSaveBuffer?.Invoke(CurrentBytes);

                // Reduce the number of displayed images to a reasonable amount
                // if the camera is acquiring images very fast.
                this.currDisplayedTime = DateTime.Now;
                if (this.currDisplayedTime - this.lastDisplayedTime > TimeSpan.FromMilliseconds(70))
                {
                    this.BitmapDisplayed?.Invoke(this.CurrentBmp);
                    this.lastDisplayedTime = this.currDisplayedTime;
                    // the LastBmp can be dispose after BitmapDisplayed invoke execute.
                    this.LastBmp.Dispose();
                }
            }
            catch
            {
                BitmapGrabbed?.Invoke(null, false);
            }
        }
Exemple #12
0
 static FastBitmap()
 {
     Bitmap bmp = new Bitmap(1, 1, PixelFormat.Format8bppIndexed);
     _palette = bmp.Palette;
     for (int i = 0; i <= 255; i++)
     {
         _palette.Entries[i] = Color.FromArgb(i, i, i);
     }
 }
Exemple #13
0
 public static void SetPalette()
 {
     tempPalette = bmpGray.Palette;
     for (int i = 0; i < 256; i++)
     {
         tempPalette.Entries[i] = Color.FromArgb(i, i, i);
     }
     bmpGray.Palette = tempPalette;
 }
 private void FillPalette(ColorPalette pal)
 {
     int len = pal.Entries.Length;
     for(int i=0; i<len; i++)
     {
         int c = i % 256;
         pal.Entries[i] = Color.FromArgb(c,c,c);
     }
 }
        /// <summary>
        /// Builds a color palette from the given <see cref="PaletteColorHistory"/>.
        /// </summary>
        /// <param name="palette">
        /// The <see cref="ColorPalette"/> to fill.
        /// </param>
        /// <param name="paletteHistory">
        /// The <see cref="PaletteColorHistory"/> containing the sum of all pixel data.
        /// </param>
        /// <returns>
        /// The <see cref="ColorPalette"/>.
        /// </returns>
        private static ColorPalette BuildPalette(ColorPalette palette, PaletteColorHistory[] paletteHistory)
        {
            int length = paletteHistory.Length;
            for (int i = 0; i < length; i++)
            {
                palette.Entries[i] = paletteHistory[i].ToNormalizedColor();
            }

            return palette;
        }
        public static void ConverToGifImageWithNewColor(ref Image refImage, ColorPalette refPalette, Color victimColor, Color newColor)
        {
            ReplaceColorInPalette(ref refImage, refPalette, victimColor, newColor);

            // Rewrite the bitmap data in a new image
            Image gifImage = Core.GifImage.CreateGifImage(ref refImage);

            refImage.Dispose();

            refImage = gifImage;
        }
Exemple #17
0
        /// <summary>
        /// Initializes the new sprite frame of the specified size pre-filled with 0xff (transparent byte).
        /// </summary>
        /// <param name="sizeOfSPR">The size in bytes of the frame, including 2 bytes each for height and width</param>
        /// <param name="width">The width of the frame in pixels</param>
        /// <param name="height">The height of the frame in pixels</param>
        /// <param name="palette">The ColorPalette to associate with this frame</param>
        /// <remarks> 
        /// We preset all bytes to 0xff, an unused palette entry that signifies a 
        /// transparent pixel.The default is 0x00, but that's actually used for 
        /// black.This is required due to the manual compression the 7KAA developers
        /// used in the SPR files. See <see cref="SetPixels(FileStream)"/> for the implementation.
        /// </remarks>
        public SpriteFrame(int sizeOfSPR, int width, int height, ColorPalette palette)
        {
            this.SprSize = sizeOfSPR;
            this.Height = height;
            this.Width = width;

            this.PixelSize = this.Height * this.Width;
            this.FrameData = new byte[PixelSize];
            FrameData = Enumerable.Repeat<byte>(0xff, PixelSize).ToArray();
            this.Palette = palette;
        }
Exemple #18
0
 public PaletteViewer()
 {
     this.SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
     this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);
     this.tilesize = this.Height > this.Width ? this.Width / 16 : this.Height / 16;
     this.line = 0;
     this.linewidth = 16;
     this.selectedcolor = 0;
     this.selectrect = new Rectangle(0, 0, this.tilesize * this.linewidth, this.tilesize);
     this.fullpalette = dumplib.Gfx.GetPalette.New_8bit();
     this.subpalette = dumplib.Gfx.GetPalette.New_4bit(true);
 }
Exemple #19
0
        public Bitmap(int width, int height, int stride, PixelFormat pixelFormat, IntPtr scan0)
        {
            _width = width;
            _height = height;
            _stride = stride;
            _pixelFormat = pixelFormat;

            _scan0 = scan0;
            _freeScan0 = false;

            if (pixelFormat.IsIndexed())
                Palette = new ColorPalette(new Color[pixelFormat.GetColorCount()]);
        }
 /// <summary>
 /// Конвертация Bitmap в другой формат Bitmap.
 /// </summary>
 /// <param name="source">Источник для конвертации.</param>
 /// <param name="destinationFormat">Новый формат.</param>
 /// <param name="destinationPalette">
 /// Палитра для нового формата, если конечно она нужна для нового формата, иначе передать null.
 /// </param>
 /// <returns>Bitmap в новом формате.</returns>
 public static Bitmap ConvertTo(
     this Bitmap source,
     System.Drawing.Imaging.PixelFormat destinationFormat,
     ColorPalette destinationPalette)
 {
     var result =
         new Bitmap(source.Width, source.Height, destinationFormat);
     if (destinationPalette != null)
         result.Palette = destinationPalette;
     using (Graphics g = Graphics.FromImage(result))
         g.DrawImage(source, 0, 0);
     return result;
 }
Exemple #21
0
        public Bitmap(int width, int height, PixelFormat pixelFormat)
        {
            _width = width;
            _height = height;
            _stride = GetStride(width, pixelFormat);
            _pixelFormat = pixelFormat;

            _scan0 = Marshal.AllocHGlobal(_stride * height);
            _freeScan0 = true;

            if (pixelFormat.IsIndexed())
                Palette = new ColorPalette(new Color[pixelFormat.GetColorCount()]);
        }
Exemple #22
0
        /// <summary> Retrieve the palette for the quantized image. </summary>
        /// <param name="original"> Any old palette, this is overrwritten. </param>
        /// <returns> The new color palette. </returns>
        protected override ColorPalette GetPalette( ColorPalette original ) {
            // First off convert the octree to _maxColors colors
            ArrayList palette = octree.Palletize( maxColors - 1 );

            // Then convert the palette based on those colors
            for( int index = 0; index < palette.Count; index++ )
                original.Entries[index] = (Color)palette[index];

            // Add the transparent color
            original.Entries[maxColors] = Color.FromArgb( 0, 0, 0, 0 );

            return original;
        }
Exemple #23
0
        private System.Drawing.Bitmap CreateBitmap(int width, int height, int bitsPerPixel, uint[] buf)
        {
            System.Drawing.Bitmap bmp;
            System.Drawing.Imaging.PixelFormat pixelFormat;

            System.Drawing.Color[] colors = null;

            switch (bitsPerPixel)
            {
            case 1:
                pixelFormat = System.Drawing.Imaging.PixelFormat.Format1bppIndexed;
                colors      = new System.Drawing.Color[] { System.Drawing.Color.White, System.Drawing.Color.Black };
                break;

            case 4:
            case 8:
                //Not tested
                int cColors = 1 << bitsPerPixel;

                pixelFormat = (bitsPerPixel == 4) ? System.Drawing.Imaging.PixelFormat.Format4bppIndexed : System.Drawing.Imaging.PixelFormat.Format8bppIndexed;

                colors = new System.Drawing.Color[cColors];

                for (int i = 0; i < cColors; i++)
                {
                    int intensity = 256 / cColors * i;
                    colors[i] = System.Drawing.Color.FromArgb(intensity, intensity, intensity);
                }

                break;

            case 16:
                pixelFormat = System.Drawing.Imaging.PixelFormat.Format16bppRgb565;
                break;

            default:
                throw new Exception("The bit depth specified, " + bitsPerPixel + ", is not supported.");
            }

            bmp = new System.Drawing.Bitmap(width, height, pixelFormat);

            if (colors != null)
            {
                System.Drawing.Imaging.ColorPalette palette = bmp.Palette;
                colors.CopyTo(palette.Entries, 0);
                bmp.Palette = palette;
            }

            return(bmp);
        }
        /// <summary>
        /// Create palette form from ColorPalette.
        /// </summary>
        /// <param name="colPal">Color palette.</param>
        public PaletteForm(bool isTransparent, string name, ColorPalette colPal, UpdatePaletteDelegate palDelegate)
        {
            InitializeComponent();

            this.isTransparentTexture = isTransparent;
            this.Text += name;

            //Backup actual color palette
            originalColorsPalette = new Color[colPal.Entries.Length];
            colPal.Entries.CopyTo(originalColorsPalette, 0);

            //Set color palette
            palette = colPal;
            updatePalette = palDelegate;
        }
 /// <summary>
 /// Retrieve the palette for the quantized image
 /// </summary>
 /// <param name="original">Any old palette, this is overrwritten</param>
 /// <returns>The new color palette</returns>
 protected override ColorPalette GetPalette(ColorPalette original)
 {
     // First off convert the octree to _maxColors colors
     List<Color> palette = this._octree.Palletize(this._maxColors - 1);
     // Then convert the palette based on those colors
     for (int index = 0; index < palette.Count; index++) {
         original.Entries[index] = palette[index];
     }
     for (int i = palette.Count; i < original.Entries.Length; ++i) {
         original.Entries[i] = Color.FromArgb(255, 0, 0, 0);
     }
     // Add the transparent color
     original.Entries[this._maxColors] = Color.FromArgb(0, 0, 0, 0);
     return original;
 }
 /// <summary>
 /// Initializes the static <see cref="PgmFormatReader"/> class.
 /// </summary>
 static PgmFormatReader()
 {
     
     // We initialize the palette to 256 colors (grayscale)
     // PGM files are always grayscale and we will always represent them in 
     // 256 shades of gray.
     using (var dummyBitmap = new Bitmap(1, 1, PixelFormat.Format8bppIndexed))
     {
         GrayscalePalette = dummyBitmap.Palette;
         for (int i = 0; i < 256; i++)
         {
             GrayscalePalette.Entries[i] = Color.FromArgb(i, i, i);
         }
     }
 }
Exemple #27
0
        /// <summary>
        /// Converts the entries in a BitmapPalette to ColorPalette entries.
        /// </summary>
        /// <param name="destPalette">ColorPalette destination palette.</param>
        /// <param name="bitmapPalette">BitmapPalette source palette.</param>
        private static void ConvertColorPalette(DrawingColorPalette destPalette, BitmapPalette bitmapPalette)
        {
            DrawingColor[] destEntries   = destPalette.Entries;
            IList <Color>  sourceEntries = bitmapPalette.Colors;

            if (destEntries.Length < sourceEntries.Count)
            {
                throw new ArgumentException("Destination palette has less entries than the source palette");
            }

            for (int i = 0, count = sourceEntries.Count; i < count; ++i)
            {
                destEntries[i] = sourceEntries[i].ToDrawingColor();
            }
        }
Exemple #28
0
        /// <summary>
        /// Retrieve the palette for the quantized image.
        /// </summary>
        /// <param name="original">
        /// Any old palette, this is overrwritten.
        /// </param>
        /// <returns>
        /// The new color palette.
        /// </returns>
        protected override System.Drawing.Imaging.ColorPalette GetPalette(System.Drawing.Imaging.ColorPalette original)
        {
            // First off convert the octree to maxColors colors
            ArrayList palette = this.octree.Palletize(this.maxColors - 1);

            // Then convert the palette based on those colors
            for (int index = 0; index < palette.Count; index++)
            {
                original.Entries[index] = (Color)palette[index];
            }

            // Add the transparent color
            original.Entries[this.maxColors] = Color.FromArgb(0, 0, 0, 0);

            return(original);
        }
Exemple #29
0
        /// <summary>
        /// Returns Similar color 
        /// </summary>
        /// <param name="palette"></param>
        /// <param name="color"></param>
        /// <returns></returns>
        private static byte GetSimilarColor(ColorPalette palette, Color color)
        {
            byte minDiff = byte.MaxValue;
            byte index = 0;

            for (int i = 0; i < palette.Entries.Length - 1; i++) {

                byte currentDiff = GetMaxDiff(color, palette.Entries[i]);

                if (currentDiff < minDiff) {
                    minDiff = currentDiff;
                    index = (byte)i;
                }
            }

            return index;
        }
Exemple #30
0
 /// <summary>Converts a Bitmap to PixelFormat.Format8bppIndexed using the given palette.</summary>
 /// <remarks>Primary overload.</remarks>
 /// <param name="image">The image to be converted.</param>
 /// <param name="palette">The palette to be used.</param>
 /// <returns>A Bitmap with PixelFormat.Format8bppIndexer.</returns>
 public static Bitmap ConvertTo8bpp(Bitmap image, ColorPalette palette)
 {
     image = new Bitmap(image);	// convert to 32bppRGB
     Bitmap new8bit = new Bitmap(image.Width, image.Height, PixelFormat.Format8bppIndexed);
     BitmapData bd32 = GetBitmapData(image);
     byte[] pix32 = new byte[bd32.Stride * bd32.Height];
     CopyImageToBytes(bd32, pix32);	// 32bppImage to Bytes
     BitmapData bd8 = GetBitmapData(new8bit);
     byte[] pix8 = new byte[bd8.Stride * bd8.Height];
     for (int y = 0; y < image.Height; y++)
         for (int x = 0, pos32 = y*bd32.Stride, pos8 = y*bd8.Stride; x < image.Width; x++)
             pix8[pos8+x] = PaletteIndex(pix32[pos32+x*4+2], pix32[pos32+x*4+1], pix32[pos32+x*4], palette);
     CopyBytesToImage(pix8, bd8);	// Bytes to 8bppImage
     image.UnlockBits(bd32);
     new8bit.UnlockBits(bd8);
     new8bit.Palette = palette;
     return new8bit;
 }
        public void CreatePalettedTex(int cluTid, byte[] buffer)
        {
            _palBuffer = buffer;
            Bitmap bmpPalette = new Bitmap(_width, _height, PixelFormat.Format8bppIndexed);
            _cp = bmpPalette.Palette;
            ushort cluTs = BitConverter.ToUInt16(_palBuffer, 18);
            if (cluTid > cluTs)
                throw new Exception("Given clut is bigger than data!");
            int startBuffer = 20+ (cluTid*512);
            for(int i = 0; i!= 255; i++)
            {
                byte[] cluTcolor = new byte[2];
                Buffer.BlockCopy(_palBuffer, startBuffer, cluTcolor, 0, 2);
                BitArray ba = new BitArray(cluTcolor);

                BitArray B = new BitArray(5);
                BitArray R = new BitArray(5);
                BitArray G = new BitArray(5);
                BitArray a = new BitArray(1);
                B[0] = ba[10]; B[1] = ba[11]; B[2] = ba[12]; B[3] = ba[13]; B[4] = ba[14]; //R
                R[0] = ba[0]; R[1] = ba[1]; R[2] = ba[2]; R[3] = ba[3]; R[4] = ba[4]; //G
                G[0] = ba[5]; G[1] = ba[6]; G[2] = ba[7]; G[3] = ba[8]; G[4] = ba[9]; //B
                a[0] = ba[15];
                int[] b_ = new int[1]; B.CopyTo(b_,0);
                int[] r_ = new int[1]; R.CopyTo(r_, 0);
                int[] g_ = new int[1]; G.CopyTo(g_, 0);
                int[] aa = new int[1]; a.CopyTo(aa, 0);
                var alpha = aa[0] == 0 ? 0 : 255;

                double b = Math.Round(b_[0] * ColorReal);
                double r = Math.Round(r_[0] * ColorReal);
                double g = Math.Round(g_[0] * ColorReal);

                if (b > 255)
                    b--;
                if (r > 255)
                    r--;
                if (g > 255)
                    g--;

                _cp.Entries[i] = Color.FromArgb(alpha,int.Parse(b.ToString(CultureInfo.InvariantCulture)),int.Parse(g.ToString(CultureInfo.InvariantCulture)),int.Parse(r.ToString(CultureInfo.InvariantCulture)));
                startBuffer += 2;
            }
        }
        void SetzeWerte()
        {
            colorPalette = Bild.Palette;
            pixelFormat  = Bild.PixelFormat;
            width        = Bild.Width;
            height       = Bild.Height;
            rect         = new Rectangle(0, 0, width, height);
            System.Drawing.Imaging.BitmapData bmpData =
                Bild.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadOnly,
                              Bild.PixelFormat);
            IntPtr ptr = bmpData.Scan0;

            stride    = bmpData.Stride;
            bytes     = stride * height;
            bildDaten = new byte[bytes];
            System.Runtime.InteropServices.Marshal.Copy(ptr, bildDaten, 0, bytes);
            Bild.UnlockBits(bmpData);
            color = new Color[width, height];
            switch (pixelFormat)
            {
            case System.Drawing.Imaging.PixelFormat.Format32bppArgb:
                Format32BppArgb();
                break;

            case System.Drawing.Imaging.PixelFormat.Format24bppRgb:
                Format24BppRgb();
                break;

            case System.Drawing.Imaging.PixelFormat.Format8bppIndexed:
                Format8BppIndexed();
                indexed = true;
                break;

            case System.Drawing.Imaging.PixelFormat.Format4bppIndexed:
                Format4BppIndexed();
                indexed = true;
                break;

            case System.Drawing.Imaging.PixelFormat.Format1bppIndexed:
                Format1BppIndexed();
                indexed = true;
                break;
            }
        }
Exemple #33
0
        public PixelDataProviderGDI(int width, int height, int numChannels)
        {
            PixelFormat pf = PixelFormat.Format8bppIndexed;

            switch (numChannels)
            {
            case 0:
                pf = this._bmp.PixelFormat;
                break;

            case 1:
                pf = PixelFormat.Format8bppIndexed;
                break;

            case 3:
                pf = PixelFormat.Format24bppRgb;
                break;

            case 4:
                pf = PixelFormat.Format32bppArgb;
                break;

            case 6:
                pf = PixelFormat.Format48bppRgb;
                break;

            case 8:
                pf = PixelFormat.Format64bppArgb;
                break;
            }
            this._bmp = new Bitmap(width, height, pf);
            if (numChannels == 1)
            {
                if (this._bmp.Palette.Entries.Length > 0) //default: grayscale
                {
                    System.Drawing.Imaging.ColorPalette pal = this._bmp.Palette;
                    for (int i = 0; i < 255; i++)
                    {
                        pal.Entries[i] = System.Drawing.Color.FromArgb(i, i, i);
                    }
                    this._bmp.Palette = pal;
                }
            }
        }
        public Bitmap BitmapFromBytes(byte[] bytes, Size size, PixelFormat format = PixelFormat.Format8bppIndexed)
        {
            // create a bitmap given a byte array of raw data
            Bitmap     bmp     = new Bitmap(size.Width, size.Height, format);
            Rectangle  rect    = new Rectangle(0, 0, bmp.Width, bmp.Height);
            BitmapData bmpData = bmp.LockBits(rect, ImageLockMode.ReadWrite, bmp.PixelFormat);

            Marshal.Copy(bytes, 0, bmpData.Scan0, bytes.Length);
            bmp.UnlockBits(bmpData);

            // Create a grayscale palette (though any LUT could be used)
            System.Drawing.Imaging.ColorPalette pal = bmp.Palette;
            for (int i = 0; i < 256; i++)
            {
                pal.Entries[i] = System.Drawing.Color.FromArgb(255, i, i, i);
            }
            bmp.Palette = pal;

            return(bmp);
        }
Exemple #35
0
        protected override ColorPalette GetPalette(ColorPalette original)
        {
            ArrayList palette = new ArrayList();

            // NOTE: I was considering either Lambda, or For loop (which should be the fastest),
            // NOTE: but I used the ForEach loop for the sake of readability. Feel free to convert it.
            /*foreach (UniformColorSlot redSlot in redSlots)
                foreach (UniformColorSlot greenSlot in greenSlots)
                    foreach (UniformColorSlot blueSlot in blueSlots)
                    {
                        Int32 red = redSlot.GetAverage();
                        Int32 green = greenSlot.GetAverage();
                        Int32 blue = blueSlot.GetAverage();

                        Color color = Color.FromArgb(255, red, green, blue);
                        palette.Add(color);
                    }
            */
            int rAvg = 0;
            int gAvg = 0;
            for (int i = 0; i < this.redSlots.Length; i++)
            {
                rAvg = this.redSlots[i].GetAverage();
                for (int j = 0; j < this.greenSlots.Length; j++)
                {
                    gAvg = this.greenSlots[j].GetAverage();
                    for (int k = 0; k < this.blueSlots.Length; k++)
                    {
                        palette.Add(Color.FromArgb(255, rAvg, gAvg, this.blueSlots[k].GetAverage()));
                    }
                }
            }
            // Then convert the palette based on those colors
            for (int index = 0; index < palette.Count; index++)
                original.Entries[index] = (Color)palette[index];

            // Add the transparent color
            //original.Entries[_maxColors] = Color.FromArgb(0, 0, 0, 0);

            return original;
        }
        /// <summary>
        /// Convert the color pallette to four lookup tables
        /// </summary>
        /// <param name="pallette">The color pallette to transform</param>
        /// <param name="bTable">Lookup table for the B channel</param>
        /// <param name="gTable">Lookup table for the G channel</param>
        /// <param name="rTable">Lookup table for the R channel</param>
        /// <param name="aTable">Lookup table for the A channel</param>
        public static void ColorPaletteToLookupTable(ColorPalette pallette, out Matrix<Byte> bTable, out Matrix<Byte> gTable, out Matrix<Byte> rTable, out Matrix<Byte> aTable)
        {
            bTable = new Matrix<byte>(256, 1);
             gTable = new Matrix<byte>(256, 1);
             rTable = new Matrix<byte>(256, 1);
             aTable = new Matrix<byte>(256, 1);
             byte[,] bData = bTable.Data;
             byte[,] gData = gTable.Data;
             byte[,] rData = rTable.Data;
             byte[,] aData = aTable.Data;

             Color[] colors = pallette.Entries;
             for (int i = 0; i < colors.Length; i++)
             {
            Color c = colors[i];
            bData[i, 0] = c.B;
            gData[i, 0] = c.G;
            rData[i, 0] = c.R;
            aData[i, 0] = c.A;
             }
        }
Exemple #37
0
 public ColorsForm(ref ColorPalette palette, int numberOfColors)
 {
     InitializeComponent();
     Height = 316;
     _palette = palette;
     _numberOfColors = numberOfColors;
     for (int y=0, i=0;y<16;y++)
         for (int x=0;(x<16 && i<_numberOfColors);x++, i++)
         {
             pnlColors[i] = new Panel();
             pnlColors[i].Tag = i;
             pnlColors[i].Click += new EventHandler(pnlColors_Click);
             pnlColors[i].MouseEnter += new EventHandler(pnlColors_MouseEnter);
             pnlColors[i].Size = new Size(16, 16);
             pnlColors[i].Left = x*16 + 20;
             pnlColors[i].Top = y*16 + 20;
             pnlColors[i].BackColor = _palette.Entries[i];
             pnlColors[i].BorderStyle = BorderStyle.FixedSingle;
             this.Controls.Add(pnlColors[i]);
         }
     lblCount.Text = "Color Count: " + _numberOfColors;
 }
Exemple #38
0
 public BattleForm(Settings config)
 {
     InitializeComponent();
     this.Height = 326;
     if (!config.TieInstalled)
     {
         MessageBox.Show("TIE95 installation not found, Battle function not available", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
         this.Close();
         return;
     }
     else
     {
         _installPath = config.TiePath;
         // dummy bitmap to create a 256 color palette
         //palette definition
         // start with EMPIRE.PLTTstandard
         Pltt standard = (Pltt)(new LfdFile(_installPath + "\\RESOURCE\\EMPIRE.LFD").Resources["PLTTstandard"]);
         // then open up TOURDESK for the rest
         LfdFile tourdesk = new LfdFile(_installPath + "\\RESOURCE\\TOURDESK.LFD");
         Pltt toddesk = (Pltt)tourdesk.Resources["PLTTtoddesk"];
         _systemPalette = Pltt.ConvertToPalette(new Pltt[]{standard, toddesk});
         Delt galaxy = (Delt)tourdesk.Resources["DELTgalaxy"];
         galaxy.Palette = _systemPalette;
         _galaxyImage = galaxy.Image;
         picGalaxy.Image = _galaxyImage;
         picGalaxy.Size = _galaxyImage.Size;
         numFrameLeft.Maximum = _galaxyImage.Width-1;
         numFrameTop.Maximum = _galaxyImage.Height-1;
     }
     _battlePath = _installPath + "\\RESOURCE\\Battle1.lfd";
     opnMission.InitialDirectory = _installPath + "\\MISSION";
     try { loadFile(_battlePath); }
     catch(Exception x)
     {
         MessageBox.Show(x.Message + " Battle function not available", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
         return;
     }
 }
Exemple #39
0
				static IndexedColorDepths()
				{
					Bitmap bitmap;
					int index;

					bitmap = new Bitmap(1, 1, PixelFormat.Format4bppIndexed);
					Palette4Bit = bitmap.Palette;
					bitmap.Dispose();

					bitmap = new Bitmap(1, 1, PixelFormat.Format8bppIndexed);
					Palette8Bit = bitmap.Palette;
					bitmap.Dispose();

					squares = new int[511];
					for (index = 0; index < 256; index++)
						squares[255 + index] = squares[255 - index] = index * index;
				}
Exemple #40
0
    IEnumerator ConvertActionEnum()
    {
        switch (GetConversionType())
        {
        case 0:
            if (Option2 == 0)
            {
                string Result = "const uint16_t " + PrepareNameForCode(PlayerPrefs.GetString("S_1")) + "_Array[] = {\n\t";

                WWW www = new WWW("file://" + PlayerPrefs.GetString("fileDirectory"));
                yield return(new WaitUntil(() => www.isDone));

                Texture2D tx = www.texture;

                if (PlayerPrefs.GetInt("S_2") == 1 && CreateATileFile.isOn)
                {
                    string tiledir = PlayerPrefs.GetString("projectDirectory") + Path.DirectorySeparatorChar + PrepareNameForCode(PlayerPrefs.GetString("S_1")) + ".gtl";                     //Gamebuino Tile
                    File.Create(tiledir).Dispose();
                    using (StreamWriter sw = File.CreateText(tiledir)) {
                        sw.WriteLine("@" + PlayerPrefs.GetString("fileDirectory"));                             //Image
                        sw.WriteLine(PrepareNameForCode(PlayerPrefs.GetString("S_1")));                         //Name
                    }
                }

                Result += tx.width + ", " + tx.height + ", 1, 0, 0x0801, 0,\n\t";

                List <Color32> col = new List <Color32>();
                for (int y = tx.height - 1; y >= 0; y--)
                {
                    for (int x = 0; x < Mathf.CeilToInt(tx.width / 2f) * 2; x++)
                    {
                        col.Add(tx.GetPixel(x, y));
                    }
                }

                for (int x = 0; x < col.Count; x++)
                {
                    if (col[x].a < 127f)
                    {
                        col[x] = new Color32(8, 0, 8, 0);
                    }
                    //Result += col[x].r*col[x].g*col[x].b;
                    Result += "0x" + RGB16(col[x].r, col[x].g, col[x].b).ToString("x");
                    Result += ",";
                }

                if (Result.EndsWith(","))
                {
                    Result.Remove(Result.Length - 1);
                }

                Result += "\n};\n";
                Result += "Image " + PrepareNameForCode(PlayerPrefs.GetString("S_1")) + " = Image(" + PrepareNameForCode(PlayerPrefs.GetString("S_1")) + "_Array);";

                TextResult[0].text = Result;
                ResultCode         = Result;
            }
            else if (Option2 == 1)
            {
                if (string.IsNullOrEmpty(PlayerPrefs.GetString("paletteDirectory")))
                {
                    yield break;
                }

                UnityEngine.Color[] CurrentPalette = new UnityEngine.Color[16];
                bool[] PaletteColorIsUsed          = new bool[16];

                string[] t = File.ReadAllLines(PlayerPrefs.GetString("paletteDirectory"));
                for (int i = 0; i < Mathf.Min(t.Length - 1, 16); i++)
                {
                    PaletteColorIsUsed[i] = false;
                    ColorUtility.TryParseHtmlString("#" + t[i + 1], out CurrentPalette[i]);
                }

                string Result = "const uint8_t " + PrepareNameForCode(PlayerPrefs.GetString("S_1")) + "_Array[] = {\n";

                WWW www = new WWW("file://" + PlayerPrefs.GetString("fileDirectory"));
                yield return(new WaitUntil(() => www.isDone));

                Texture2D tx = www.texture;

                if (PlayerPrefs.GetInt("S_2") == 1 && CreateATileFile.isOn)
                {
                    string tiledir = PlayerPrefs.GetString("projectDirectory") + Path.DirectorySeparatorChar + PrepareNameForCode(PlayerPrefs.GetString("S_1")) + ".gtl";                     //Gamebuino Tile
                    File.Create(tiledir).Dispose();
                    using (StreamWriter sw = File.CreateText(tiledir)) {
                        sw.WriteLine("@" + PlayerPrefs.GetString("fileDirectory"));                             //Image
                        sw.WriteLine(PrepareNameForCode(PlayerPrefs.GetString("S_1")));                         //Name
                    }
                }

                Result += "\t" + tx.width + ", " + tx.height + ", 1, 0, 0, transparent, 1,\n\t";

                List <Color32> col = new List <Color32>();
                for (int y = tx.height - 1; y >= 0; y--)
                {
                    for (int x = 0; x < Mathf.CeilToInt(tx.width / 2f) * 2; x++)
                    {
                        col.Add(tx.GetPixel(x, y));
                    }
                }

                for (int x = 0; x < col.Count; x += 2)
                {
                    Result += "0x";
                    if (col[x].a < 127f)
                    {
                        Result += "transparent";
                    }
                    else
                    {
                        int closest = FindClosestColorInPalette(col[x], CurrentPalette);
                        PaletteColorIsUsed[closest] = true;
                        Result += closest.ToString("x1");
                    }
                    if (x + 1 < col.Count)
                    {
                        if (col[x + 1].a < 127f)
                        {
                            Result += "transparent";
                        }
                        else
                        {
                            int closest = FindClosestColorInPalette(col[x + 1], CurrentPalette);
                            PaletteColorIsUsed[closest] = true;
                            Result += closest.ToString("x1");
                        }
                    }
                    else
                    {
                        Result += "0";
                    }
                    //Result += "0x" + RGB16(col[x].r,col[x].g,col[x].b).ToString("x");
                    Result += ",";
                }

                int toReplace = 0;

                if ((Result.Length - Result.Replace("transparent", string.Empty).Length) / ("transparent".Length) > 1)
                {
                    if (!PaletteColorIsUsed.ToList().Contains(false))
                    {
                        ErrorMessage.gameObject.SetActive(true);
                        ErrorMessage.GetChild(1).GetComponent <Text>().text = "All colors are used in one indexed image, leaving no room for transparency. Please, use only 15 colors per image.";
                    }
                    else
                    {
                        toReplace = PaletteColorIsUsed.ToList().IndexOf(false);
                    }
                }
                Result = Result.Replace("transparent", toReplace.ToString("x1"));

                if (Result.EndsWith(","))
                {
                    Result.Remove(Result.Length - 1);
                }

                Result += "\n};\n";
                Result += "Image " + PrepareNameForCode(PlayerPrefs.GetString("S_1")) + " = Image(" + PrepareNameForCode(PlayerPrefs.GetString("S_1")) + "_Array);";

                TextResult[0].text = Result;
                ResultCode         = Result;
            }
            break;

        case 2:
        case 4:
            string fdirectory = "";
            if (GetConversionType() == 2)
            {
                fdirectory = PlayerPrefs.GetString("projectDirectory") + Path.DirectorySeparatorChar + PrepareNameForCode(PlayerPrefs.GetString("S_1")) + ".bmp";
            }
            else if (GetConversionType() == 4)
            {
                fdirectory = Directory.GetParent(PlayerPrefs.GetString("fileDirectory")).FullName + PrepareNameForCode(PlayerPrefs.GetString("S_1")) + ".bmp";
            }

            if (Option2 == 2)
            {
                //SEMI BROKEN, FIX LATER

                Bitmap bitmap = new Bitmap(PlayerPrefs.GetString("fileDirectory"));

                if (PlayerPrefs.GetInt("S_2") == 1 && CreateATileFile.isOn)
                {
                    string tiledir = PlayerPrefs.GetString("projectDirectory") + Path.DirectorySeparatorChar + PrepareNameForCode(PlayerPrefs.GetString("S_1")) + ".gtl";                     //Gamebuino Tile
                    File.Create(tiledir).Dispose();
                    using (StreamWriter sw = File.CreateText(tiledir)) {
                        sw.WriteLine("@" + PlayerPrefs.GetString("fileDirectory"));                             //Image
                        sw.WriteLine(PrepareNameForCode(PlayerPrefs.GetString("S_1")));                         //Name
                    }
                }

                if (!string.IsNullOrEmpty(PlayerPrefs.GetString("projectDirectory")))
                {
                    UnityEngine.Color[] CurrentPalette = new UnityEngine.Color[16];
                    bool[] PaletteColorIsUsed          = new bool[16];

                    string[] t = File.ReadAllLines(PlayerPrefs.GetString("paletteDirectory"));
                    for (int i = 0; i < Mathf.Min(t.Length - 1, 16); i++)
                    {
                        PaletteColorIsUsed[i] = false;
                        ColorUtility.TryParseHtmlString("#" + t[i + 1], out CurrentPalette[i]);
                    }

                    Bitmap clone = new Bitmap(bitmap.Width, bitmap.Height, System.Drawing.Imaging.PixelFormat.Format8bppIndexed);

                    System.Drawing.Imaging.ColorPalette palette = bitmap.Palette;
                    System.Drawing.Color[] entries = palette.Entries;
                    for (int i = 0; i < CurrentPalette.Length; i++)
                    {
                        entries[i] = System.Drawing.Color.FromArgb((byte)(CurrentPalette[i].r * 255), (byte)(CurrentPalette[i].g * 255), (byte)(CurrentPalette[i].b * 255));
                    }
                    bitmap.Palette = palette;

                    using (System.Drawing.Graphics gr = System.Drawing.Graphics.FromImage(clone)) {
                        gr.DrawImage(bitmap, new Rectangle(0, 0, clone.Width, clone.Height));
                    }
                    clone.Save(fdirectory);
                }
            }
            else if (Option2 == 3)
            {
                Bitmap bitmap = new Bitmap(PlayerPrefs.GetString("fileDirectory"));

                if (PlayerPrefs.GetInt("S_2") == 1 && CreateATileFile.isOn)
                {
                    string tiledir = PlayerPrefs.GetString("projectDirectory") + Path.DirectorySeparatorChar + PrepareNameForCode(PlayerPrefs.GetString("S_1")) + ".gtl";                     //Gamebuino Tile
                    File.Create(tiledir).Dispose();
                    using (StreamWriter sw = File.CreateText(tiledir)) {
                        sw.WriteLine("@" + PlayerPrefs.GetString("fileDirectory"));                             //Image
                        sw.WriteLine(PrepareNameForCode(PlayerPrefs.GetString("S_1")));                         //Name
                    }
                }

                if (!string.IsNullOrEmpty(PlayerPrefs.GetString("projectDirectory")))
                {
                    Bitmap clone = new Bitmap(bitmap.Width, bitmap.Height, System.Drawing.Imaging.PixelFormat.Format16bppRgb565);

                    using (System.Drawing.Graphics gr = System.Drawing.Graphics.FromImage(clone)) {
                        gr.DrawImage(bitmap, new Rectangle(0, 0, clone.Width, clone.Height));
                    }
                    clone.Save(fdirectory);
                }
            }
            break;

        case 1:
            if (Option2 == 0)
            {
                string[] t = File.ReadAllLines(Application.persistentDataPath + Path.DirectorySeparatorChar + "tempcut.cut");

                WWW www = new WWW("file://" + PlayerPrefs.GetString("fileDirectory"));
                yield return(new WaitUntil(() => www.isDone));

                Texture2D tx = www.texture;

                string Result = "";
                for (int i = 0; i < t.Length; i++)
                {
                    string[] Data = t[i].Split(';');

                    Result += "const uint16_t " + Data[4].ToString() + "_Array[] = {\n\t";
                    Result += Data[2].ToString() + ", " + Data[3].ToString() + ", 1, 0, 0x0801, 0,\n\t";

                    if (PlayerPrefs.GetInt("S_2") == 1 && CreateATileFile.isOn)
                    {
                        string tiledir = PlayerPrefs.GetString("projectDirectory") + Path.DirectorySeparatorChar + Data[4] + ".gtl";                         //Gamebuino Tile
                        File.Create(tiledir).Dispose();
                        using (StreamWriter sw = File.CreateText(tiledir)) {
                            sw.WriteLine("@" + PlayerPrefs.GetString("fileDirectory"));                                         //Image
                            sw.WriteLine(Data[4]);                                                                              //Name
                            sw.WriteLine(t[i]);
                        }
                    }

                    List <Color32> col = new List <Color32>();
                    for (int y = int.Parse(Data[1]) + 1; y < int.Parse(Data[1]) + int.Parse(Data[3]) + 1; y++)
                    {
                        for (int x = int.Parse(Data[0]); x < int.Parse(Data[0]) + int.Parse(Data[2]); x++)
                        {
                            col.Add(tx.GetPixel(x, tx.height - y));
                        }
                    }

                    for (int x = 0; x < col.Count; x++)
                    {
                        if (col[x].a < 256 / 2)
                        {
                            col[x] = new Color32(8, 0, 8, 0);
                        }
                        //Result += col[x].r*col[x].g*col[x].b;
                        Result += "0x" + RGB16((byte)(col[x].r), (byte)(col[x].g), (byte)(col[x].b)).ToString("x");
                        Result += ",";
                    }

                    if (Result.EndsWith(","))
                    {
                        Result.Remove(Result.Length - 1);
                    }

                    Result += "\n};\n";
                    Result += "Image " + Data[4] + " = Image(" + Data[4] + "_Array);\n\n";
                }
                TextResult[1].text = Result;
                ResultCode         = Result;
            }
            else
            {
                if (string.IsNullOrEmpty(PlayerPrefs.GetString("paletteDirectory")))
                {
                    yield break;
                }
                string[] t = File.ReadAllLines(Application.persistentDataPath + Path.DirectorySeparatorChar + "tempcut.cut");

                UnityEngine.Color[] CurrentPalette = new UnityEngine.Color[16];
                bool[] PaletteColorIsUsed          = new bool[16];

                string[] p = File.ReadAllLines(PlayerPrefs.GetString("paletteDirectory"));
                for (int i = 0; i < Mathf.Min(p.Length - 1, 16); i++)
                {
                    PaletteColorIsUsed[i] = false;
                    ColorUtility.TryParseHtmlString("#" + p[i + 1], out CurrentPalette[i]);
                }
                JustAFuckingPalette = CurrentPalette;

                WWW www = new WWW("file://" + PlayerPrefs.GetString("fileDirectory"));
                yield return(new WaitUntil(() => www.isDone));

                Texture2D tx = www.texture;
                tx.wrapMode = TextureWrapMode.Repeat;

                string Result = "";
                for (int i = 0; i < t.Length; i++)
                {
                    string[] Data = t[i].Split(';');

                    Result += "const uint8_t " + Data[4] + "_Array[] = {\n";
                    Result += "\t" + int.Parse(Data[2]) + ", " + int.Parse(Data[3]) + ", 1, 0, 0, transparent, 1,\n\t";

                    if (PlayerPrefs.GetInt("S_2") == 1 && CreateATileFile.isOn)
                    {
                        string tiledir = PlayerPrefs.GetString("projectDirectory") + Path.DirectorySeparatorChar + Data[4] + ".gtl";                         //Gamebuino Tile
                        File.Create(tiledir).Dispose();
                        using (StreamWriter sw = File.CreateText(tiledir)) {
                            sw.WriteLine(PlayerPrefs.GetString("fileDirectory"));                                               //Image
                            sw.WriteLine(Data[4]);                                                                              //Name
                            sw.WriteLine(t[i]);
                        }
                    }

                    List <Color32> col = new List <Color32>();
                    for (int y = int.Parse(Data[1]) + 1; y < int.Parse(Data[1]) + int.Parse(Data[3]) + 1; y++)
                    {
                        for (int x = int.Parse(Data[0]); x < int.Parse(Data[0]) + Mathf.CeilToInt(int.Parse(Data[2]) / 2f) * 2; x++)
                        {
                            col.Add(tx.GetPixel(x, tx.height - y));
                        }
                    }

                    for (int x = 0; x < col.Count; x += 2)
                    {
                        Result += "0x";
                        if (col[x].a < 127f)
                        {
                            Result += "transparent";
                        }
                        else
                        {
                            int closest = FindClosestColorInPalette(col[x], CurrentPalette);
                            PaletteColorIsUsed[closest] = true;
                            Result += closest.ToString("x1");
                        }
                        if (x + 1 < col.Count)
                        {
                            if (col[x + 1].a < 127f)
                            {
                                Result += "transparent";
                            }
                            else
                            {
                                int closest = FindClosestColorInPalette(col[x + 1], CurrentPalette);
                                PaletteColorIsUsed[closest] = true;
                                Result += closest.ToString("x1");
                            }
                        }
                        else
                        {
                            Result += "0";
                        }
                        //Result += "0x" + RGB16(col[x].r,col[x].g,col[x].b).ToString("x");
                        Result += ",";
                    }

                    int toReplace = 0;

                    if ((Result.Length - Result.Replace("transparent", string.Empty).Length) / ("transparent".Length) > 1)
                    {
                        if (!PaletteColorIsUsed.ToList().Contains(false))
                        {
                            ErrorMessage.gameObject.SetActive(true);
                            ErrorMessage.GetChild(1).GetComponent <Text>().text = "All colors are used in one indexed image, leaving no room for transparency. Please, use only 15 colors per image.";
                        }
                        else
                        {
                            toReplace = PaletteColorIsUsed.ToList().IndexOf(false);
                        }
                    }
                    Result = Result.Replace("transparent", toReplace.ToString());

                    if (Result.EndsWith(","))
                    {
                        Result.Remove(Result.Length - 1);
                    }

                    Result += "\n};\n";
                    Result += "Image " + Data[4] + " = Image(" + Data[4] + "_Array);\n";
                }

                TextResult[1].text = Result;
                ResultCode         = Result;
            }
            break;

        case 6:
            string[] tP = File.ReadAllLines(Application.persistentDataPath + Path.DirectorySeparatorChar + "tempcut.cut");

            WWW wwwP = new WWW("file://" + PlayerPrefs.GetString("fileDirectory"));
            yield return(new WaitUntil(() => wwwP.isDone));

            Texture2D txP = wwwP.texture;

            string   ResultP = "";
            string[] DataP   = tP[0].Split(';');
            ResultP += "const uint16_t " + DataP[4].ToString() + "_Array[] = {\n\t";
            ResultP += DataP[2].ToString() + ", " + DataP[3].ToString() + ", " + tP.Length + ", 0, 0, 0x0801, 0,\n";

            for (int i = 0; i < tP.Length; i++)
            {
                ResultP += "\t";
                string[] Data = tP[i].Split(';');

                if (PlayerPrefs.GetInt("S_2") == 1 && CreateATileFile.isOn)
                {
                    string tiledir = PlayerPrefs.GetString("projectDirectory") + Path.DirectorySeparatorChar + Data[4] + ".gtl";                     //Gamebuino Tile
                    File.Create(tiledir).Dispose();
                    using (StreamWriter sw = File.CreateText(tiledir)) {
                        sw.WriteLine("@" + PlayerPrefs.GetString("fileDirectory"));                                     //Image
                        sw.WriteLine(Data[4]);                                                                          //Name
                        sw.WriteLine(tP[i]);
                    }
                }

                List <Color32> col = new List <Color32>();
                for (int y = int.Parse(Data[1]) + 1; y < int.Parse(Data[1]) + int.Parse(Data[3]) + 1; y++)
                {
                    for (int x = int.Parse(Data[0]); x < int.Parse(Data[0]) + int.Parse(Data[2]); x++)
                    {
                        col.Add(txP.GetPixel(x, txP.height - y));
                    }
                }

                for (int x = 0; x < col.Count; x++)
                {
                    if (col[x].a < 256 / 2)
                    {
                        col[x] = new Color32(8, 0, 8, 0);
                    }
                    //Result += col[x].r*col[x].g*col[x].b;
                    ResultP += "0x" + RGB16((byte)(col[x].r), (byte)(col[x].g), (byte)(col[x].b)).ToString("x");
                    ResultP += ",";
                }

                if (ResultP.EndsWith(","))
                {
                    ResultP.Remove(ResultP.Length - 1);
                }
                ResultP += "\n";
            }
            ResultP           += "};\n";
            ResultP           += "Image " + DataP[4] + " = Image(" + DataP[4] + "_Array);\n\n";
            TextResult[1].text = ResultP;
            ResultCode         = ResultP;
            break;

        case 7:
            if (string.IsNullOrEmpty(PlayerPrefs.GetString("paletteDirectory")))
            {
                yield break;
            }
            string[] tS = File.ReadAllLines(Application.persistentDataPath + Path.DirectorySeparatorChar + "tempcut.cut");

            UnityEngine.Color[] CurrentPaletteS = new UnityEngine.Color[16];
            bool[] PaletteColorIsUsedS          = new bool[16];

            string[] pS = File.ReadAllLines(PlayerPrefs.GetString("paletteDirectory"));
            for (int i = 0; i < Mathf.Min(pS.Length - 1, 16); i++)
            {
                PaletteColorIsUsedS[i] = false;
                ColorUtility.TryParseHtmlString("#" + pS[i + 1], out CurrentPaletteS[i]);
            }
            JustAFuckingPalette = CurrentPaletteS;

            WWW wwwS = new WWW("file://" + PlayerPrefs.GetString("fileDirectory"));
            yield return(new WaitUntil(() => wwwS.isDone));

            Texture2D txS = wwwS.texture;
            txS.wrapMode = TextureWrapMode.Repeat;

            string   ResultS = "";
            string[] DataS   = tS[0].Split(';');
            ResultS += "const uint8_t " + DataS[4] + "_Array[] = {\n";
            ResultS += "\t" + int.Parse(DataS[2]) + ", " + int.Parse(DataS[3]) + ", " + tS.Length + ", 0, transparent, 1,\n";

            for (int i = 0; i < tS.Length; i++)
            {
                ResultS += "\t";
                string[] Data = tS[i].Split(';');

                if (PlayerPrefs.GetInt("S_2") == 1 && CreateATileFile.isOn)
                {
                    string tiledir = PlayerPrefs.GetString("projectDirectory") + Path.DirectorySeparatorChar + Data[4] + ".gtl";                     //Gamebuino Tile
                    File.Create(tiledir).Dispose();
                    using (StreamWriter sw = File.CreateText(tiledir)) {
                        sw.WriteLine(PlayerPrefs.GetString("fileDirectory"));                                           //Image
                        sw.WriteLine(Data[4]);                                                                          //Name
                        sw.WriteLine(tS[i]);
                    }
                }

                List <Color32> col = new List <Color32>();
                for (int y = int.Parse(Data[1]) + 1; y < int.Parse(Data[1]) + int.Parse(Data[3]) + 1; y++)
                {
                    for (int x = int.Parse(Data[0]); x < int.Parse(Data[0]) + Mathf.CeilToInt(int.Parse(Data[2]) / 2f) * 2; x++)
                    {
                        col.Add(txS.GetPixel(x, txS.height - y));
                    }
                }

                for (int x = 0; x < col.Count; x += 2)
                {
                    ResultS += "0x";
                    if (col[x].a < 127f)
                    {
                        ResultS += "transparent";
                    }
                    else
                    {
                        int closest = FindClosestColorInPalette(col[x], CurrentPaletteS);
                        PaletteColorIsUsedS[closest] = true;
                        ResultS += closest.ToString("x1");
                    }
                    if (x + 1 < col.Count)
                    {
                        if (col[x + 1].a < 127f)
                        {
                            ResultS += "transparent";
                        }
                        else
                        {
                            int closest = FindClosestColorInPalette(col[x + 1], CurrentPaletteS);
                            PaletteColorIsUsedS[closest] = true;
                            ResultS += closest.ToString("x1");
                        }
                    }
                    else
                    {
                        ResultS += "0";
                    }
                    //Result += "0x" + RGB16(col[x].r,col[x].g,col[x].b).ToString("x");
                    ResultS += ",";
                }

                ResultS += "\n";
            }
            int toReplaceS = 0;

            if ((ResultS.Length - ResultS.Replace("transparent", string.Empty).Length) / ("transparent".Length) > 1)
            {
                if (!PaletteColorIsUsedS.ToList().Contains(false))
                {
                    ErrorMessage.gameObject.SetActive(true);
                    ErrorMessage.GetChild(1).GetComponent <Text>().text = "All colors are used in one indexed image, leaving no room for transparency. Please, use only 15 colors per image.";
                }
                else
                {
                    toReplaceS = PaletteColorIsUsedS.ToList().IndexOf(false);
                }
            }
            ResultS = ResultS.Replace("transparent", toReplaceS.ToString());

            if (ResultS.EndsWith(","))
            {
                ResultS.Remove(ResultS.Length - 1);
            }

            ResultS += "};\n";
            ResultS += "Image " + DataS[4] + " = Image(" + DataS[4] + "_Array);\n";

            TextResult[1].text = ResultS;
            ResultCode         = ResultS;
            break;

        default:
            break;
        }
    }
Exemple #41
0
        public static Bitmap CreateBitmap(string systemPicture, string text, int width, int height, bool addIcon = false, int iconLeft = -1, int iconTop = -1)
        {
            Bitmap bmpBase   = null;
            Bitmap bmpIcon   = null;
            Bitmap colShadow = null;
            Bitmap colLetter = null;
            Bitmap mask      = null;

            try
            {
                int w = width;
                int h = height;

                // システム画像を読み込む
                string path = System.IO.Path.Combine(systemPicture);
                bmpBase = new Bitmap(path);

                // アイコン画像を読み込む
                if (addIcon == true && iconLeft >= 0 && iconTop >= 0)
                {
                    path = System.IO.Path.Combine(System.Environment.CurrentDirectory, @"Icons.png");
                    FileInfo fiIcon = new FileInfo(path);
                    if (fiIcon.Exists == true)
                    {
                        Rectangle r           = new Rectangle(iconLeft, iconTop, 12, 12);
                        Bitmap    bmpIconBase = new Bitmap(path);
                        bmpIcon = bmpIconBase.Clone(r, bmpIconBase.PixelFormat);
                        bmpIconBase.Dispose();
                    }
                }

                // 影の色範囲を切り抜く
                Rectangle rect = new Rectangle(16, 32, 16, 16);
                colShadow = bmpBase.Clone(rect, bmpBase.PixelFormat);

                // 文字の色範囲を切り抜く
                rect      = new Rectangle(0, 48, 16, 16);
                colLetter = bmpBase.Clone(rect, bmpBase.PixelFormat);

                // maskの生成
                mask = new Bitmap(w, h);
                Graphics g = Graphics.FromImage(mask);

                //フォントオブジェクトの作成
                Font fnt = new Font("MS ゴシック", 12, GraphicsUnit.Pixel);
                //文字列を位置(0,0)、青色で表示
                //1文字ずつ12pxずつずらして描画する
                int xp = -2; // 2pxくらいずらして置かないと左に隙間ができます
                if (addIcon)
                {
                    xp += WidthIcon + IconLeft + IconRight;
                }
                Encoding sjisEnc = Encoding.GetEncoding("Shift_JIS");
                for (int i = 0; i < text.Length; i++)
                {
                    string chr = text[i].ToString();
                    g.DrawString(chr, fnt, System.Drawing.Brushes.White, xp, DrawTop);

                    int num = sjisEnc.GetByteCount(chr);
                    if (num == 2)
                    {
                        xp += WidthZenkaku;
                    }
                    else
                    {
                        xp += WidthHankaku;
                    }
                }

                //リソースを解放する
                fnt.Dispose();
                g.Dispose();


                // 出力用
                Bitmap ibmp = new Bitmap(w, h, System.Drawing.Imaging.PixelFormat.Format8bppIndexed);

                // パレット作成
                System.Drawing.Imaging.ColorPalette palette = bmpBase.Palette;
                List <Color> colors = new List <Color>();
                colors.Add(palette.Entries[0]);
                MergeColorsDistinct(ref colors, GetColorsFromImage(colShadow));
                MergeColorsDistinct(ref colors, GetColorsFromImage(colLetter));
                if (bmpIcon != null)
                {
                    MergeColorsDistinct(ref colors, GetColorsFromImage(bmpIcon));
                }

                var pal = ibmp.Palette;
                for (var i = 0; i < colors.Count; i++)
                {
                    pal.Entries[i] = colors[i];
                }
                ibmp.Palette = pal;


                // 配列から画像生成
                byte[] data = new byte[w * h];

                // 背景色で塗りつぶし
                for (int y = 0; y < h; y++)
                {
                    for (int x = 0; x < w; x++)
                    {
                        data[y * w + x] = 0x00;
                    }
                }

                // 影を塗る
                for (int y = 0; y < h; y++)
                {
                    // yの高さで色を選出
                    Color pcol  = colShadow.GetPixel(0, y);
                    int   index = colors.IndexOf(pcol);
                    byte  b     = BitConverter.GetBytes(index)[0];
                    for (int x = 0; x < w; x++)
                    {
                        if (x == w - 1 || y == h - 1)
                        {
                            continue;
                        }

                        Color color = mask.GetPixel(x, y);

                        // 閾値より大きい?
                        float fTemp = color.GetBrightness();
                        if (fTemp > 0.5)
                        {
                            data[(y + 1) * w + (x + 1)] = b;
                        }
                    }
                }

                // 文字を塗る
                for (int y = 0; y < h; y++)
                {
                    // yの高さで色を選出
                    Color pcol  = colLetter.GetPixel(0, y);
                    int   index = colors.IndexOf(pcol);
                    byte  b     = BitConverter.GetBytes(index)[0];
                    for (int x = 0; x < w; x++)
                    {
                        Color color = mask.GetPixel(x, y);

                        // 閾値より大きい?
                        float fTemp = color.GetBrightness();
                        if (fTemp > 0.5)
                        {
                            data[y * w + x] = b;
                        }
                    }
                }

                if (bmpIcon != null)
                {
                    palette = bmpIcon.Palette;
                    Color iconBack = palette.Entries[0];
                    // アイコンを描画する
                    for (int y = 0; y < bmpIcon.Size.Height; y++)
                    {
                        for (int x = 0; x < bmpIcon.Size.Width; x++)
                        {
                            Color pcol = bmpIcon.GetPixel(x, y);
                            if (pcol != iconBack)
                            {
                                int  index = colors.IndexOf(pcol);
                                byte b     = BitConverter.GetBytes(index)[0];
                                data[(y + DrawTop) * w + x + IconLeft] = b;
                            }
                        }
                    }
                    bmpIcon.Dispose();
                }

                rect = new Rectangle(0, 0, ibmp.Width, ibmp.Height);
                System.Drawing.Imaging.BitmapData bmpData =
                    ibmp.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite,
                                  PixelFormat.Format8bppIndexed);

                // Bitmapの先頭アドレスを取得
                IntPtr ptr = bmpData.Scan0;
                Marshal.Copy(data, 0, ptr, data.Length);

                ibmp.UnlockBits(bmpData);

                return(ibmp);
            }
            catch
            {
                throw;
            }
            finally
            {
                if (bmpBase != null)
                {
                    bmpBase.Dispose();
                }
                if (bmpIcon != null)
                {
                    bmpIcon.Dispose();
                }
                if (colShadow != null)
                {
                    colShadow.Dispose();
                }
                if (colLetter != null)
                {
                    colLetter.Dispose();
                }
                if (mask != null)
                {
                    mask.Dispose();
                }
            }
        }
Exemple #42
0
 private static void ConvertColorPalette(ColorPalette destPalette, BitmapPalette bitmapPalette)
 {
     System.Drawing.Color[] entries = destPalette.Entries;
     IList<System.Windows.Media.Color> colors = bitmapPalette.Colors;
     if (entries.Length < colors.Count)
         throw new ArgumentException("Destination palette has less entries than the source palette");
     int index = 0;
     for (int count = colors.Count; index < count; ++index)
         entries[index] = DataObjectExtensions.ToDrawingColor(colors[index]);
 }
Exemple #43
0
 public void GetAdjustedPalette(ColorPalette palette, ColorAdjustType type)
 {
     throw null;
 }
Exemple #44
0
        public static Bitmap LightToGrayScaleBitmap(byte[] b, int width, int height, int strength = 1)
        {
            if (b == null)
            {
                return(null);
            }
            if (strength < 1 || strength > 4)
            {
                throw new NotSupportedException();
            }

            // Create a palette based bitmap
            Bitmap     returnBitmap = new Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format8bppIndexed);
            BitmapData bmpData      = returnBitmap.LockBits(new Rectangle(0, 0, returnBitmap.Width, returnBitmap.Height), ImageLockMode.WriteOnly, returnBitmap.PixelFormat);

            // Currently we do not support bitmaps with a negative stride
            if (bmpData.Stride <= 0)
            {
                throw new NotSupportedException();
            }

            // Copy the RGB values into the array.
            long scan0 = bmpData.Scan0.ToInt64();

            if (bmpData.Stride != bmpData.Width)
            {
                for (int y = 0; y < bmpData.Height; y++)
                {
                    Marshal.Copy(b, y * bmpData.Width, new IntPtr(scan0 + y * bmpData.Stride), bmpData.Width);
                }
            }
            else
            {
                Marshal.Copy(b, 0, bmpData.Scan0, b.Length);
            }

            // Release the raw bitmap
            returnBitmap.UnlockBits(bmpData);

            // Get the palette
            System.Drawing.Imaging.ColorPalette pal = returnBitmap.Palette;

            // Modify the palette, converting the lightmap to a grayscale
            for (int j = -31; j <= 31; j++)
            {
                byte i         = unchecked ((byte)j);
                byte grayscale = grayscale = (byte)(128 + j * strength);

                /*
                 * if (i >= 0)
                 * grayscale = (byte)( 255 - ((31 - i) * 255 / 31));
                 * else
                 * grayscale = (byte)(-i * 255 / 31);
                 */
                pal.Entries[i] = System.Drawing.Color.FromArgb(grayscale, grayscale, grayscale);
            }

            // Fill the remaining colours with RED to see any errors clearly
            for (int i = 32; i <= unchecked ((byte)-32); i++)
            {
                pal.Entries[i] = System.Drawing.Color.FromArgb(255, 0, 0);
            }

            // Apply the new palette!
            returnBitmap.Palette = pal;

            return(returnBitmap);
        }
Exemple #45
0
 /// <summary>
 /// Retrieve the palette for the quantized image.
 /// </summary>
 /// <param name="original">
 /// Any old palette, this is overrwritten.
 /// </param>
 /// <returns>
 /// The new color palette.
 /// </returns>
 protected abstract System.Drawing.Imaging.ColorPalette GetPalette(System.Drawing.Imaging.ColorPalette original);
Exemple #46
0
 public static void SetFlags(this ColorPalette pal, ColorPaletteFlags flags)
 {
     typeof(ColorPalette).GetField("flags", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(pal, (int)flags);
 }
Exemple #47
0
        public System.Drawing.Bitmap BuildPageImage(bool rebuild = false)
        {
            const int subsample = 1;

            int       width  = _Page.Width / subsample;
            int       height = _Page.Height / subsample;
            GMap      map    = null;
            Rectangle rect   = new Rectangle(0, 0, width, height);
            Bitmap    retVal = null;

            if (rebuild || _Image == null)
            {
                map = _Page.GetMap(new GRect(0, 0, width, height), subsample, null);
                if (map == null)
                {
                    return(new Bitmap(width, height));
                }

                if (map.BytesPerPixel == 3)
                {
                    const PixelFormat format = PixelFormat.Format24bppRgb;
                    retVal = DjvuImage.ImageFromMap(map, rect, format);
                }
                else if (map.BytesPerPixel == 1)
                {
                    const PixelFormat format = PixelFormat.Format8bppIndexed;
                    retVal = DjvuImage.ImageFromMap(map, rect, format);
                }
            }
            else
            {
                retVal = _Image;
            }

            if (map.BytesPerPixel == 3 && IsInverted)
            {
                retVal = DjvuImage.InvertColor(retVal);
            }
            else if (map.BytesPerPixel == 1)
            {
                System.Drawing.Imaging.ColorPalette palette = retVal.Palette;

                if (!IsInverted)
                {
                    for (int i = 0; i < 256; i++)
                    {
                        palette.Entries[i] = Color.FromArgb(i, i, i);
                    }

                    retVal.Palette = palette;
                }
                else
                {
                    int j = 0;
                    for (int i = 0; i < 256; i++)
                    {
                        j = 255 - i;
                        palette.Entries[i] = Color.FromArgb(j, j, j);
                    }
                    retVal.Palette = palette;
                }
            }

            return(retVal);

            //int[] pixels = new int[width * height];

            //map.FillRgbPixels(0, 0, width, height, pixels, 0, width);
            //var image = ConvertDataToImage(pixels);

            //if (IsInverted == true)
            //    image = InvertImage(image);

            //return image;
        }
		/// <summary>
		/// Retrieve the palette for the quantized image
		/// </summary>
		/// <param name="original">Any old palette, this is overrwritten</param>
		/// <returns>The new color palette</returns>
		protected abstract ColorPalette GetPalette ( ColorPalette original ) ;
Exemple #49
0
        private void onIamgeGrabbed(object sender, Basler.Pylon.ImageGrabbedEventArgs e)
        {
            try
            {
                // Get the grab result.
                IGrabResult grabResult = e.GrabResult;

                if (!grabResult.GrabSucceeded)
                {
                    BitmapGrabbed?.Invoke(null, false);
                    return;
                }

                // Check if the image can be displayed.
                if (!grabResult.IsValid)
                {
                    BitmapGrabbed?.Invoke(null, false);
                    return;
                }
                lock (this)
                {
                    newBmp = new Bitmap(grabResult.Width, grabResult.Height, PixelFormat.Format8bppIndexed);
                    // Lock the bits of the bitmap.
                    BitmapData bmpData = newBmp.LockBits(new Rectangle(0, 0, newBmp.Width, newBmp.Height), ImageLockMode.ReadWrite, newBmp.PixelFormat);
                    // Place the pointer to the buffer of the bitmap.
                    converter.OutputPixelFormat = PixelType.Mono8;
                    IntPtr ptrBmp = bmpData.Scan0;
                    converter.Convert(ptrBmp, bmpData.Stride * newBmp.Height, grabResult);
                    //palette
                    System.Drawing.Imaging.ColorPalette palette = newBmp.Palette;
                    for (int i = 0; i < 256; ++i)
                    {
                        palette.Entries[i] = Color.FromArgb(255, i, i, i);
                    }
                    newBmp.Palette = palette;
                    //convert to bytes data
                    newBytes = new byte[bmpData.Stride * newBmp.Height];
                    Marshal.Copy(ptrBmp, newBytes, 0, newBytes.Length);
                    //reverse y
                    if (this.reverseY)
                    {
                        newBytes = this.bytesReverseY(newBytes, bmpData.Stride, newBmp.Height);
                    }
                    //copy to ptr
                    Marshal.Copy(newBytes, 0, ptrBmp, newBytes.Length);
                    newBmp.UnlockBits(bmpData);

                    this.CurrentBytes = this.newBytes;
                    this.LastBmp      = this.CurrentBmp;
                    this.CurrentBmp   = this.newBmp;
                }
                BmpGrabedEvnet.Set();
                this.TriggerSts.Update(true);
                BitmapGrabbed?.Invoke(CurrentBmp, true);
                BytesSaveBuffer?.Invoke(CurrentBytes);
                // Reduce the number of displayed images to a reasonable amount
                // if the camera is acquiring images very fast.
                this.currDisplayedTime = DateTime.Now;
                if (this.currDisplayedTime - this.lastDisplayedTime > TimeSpan.FromMilliseconds(70))
                {
                    this.BitmapDisplayed?.Invoke(this.CurrentBmp);
                    this.lastDisplayedTime = this.currDisplayedTime;
                    // the LastBmp can be dispose after BitmapDisplayed invoke execute.
                    this.LastBmp.Dispose();
                }
            }
            catch (Exception)
            {
                BitmapGrabbed?.Invoke(null, false);
            }
        }