Inheritance: MonoBehaviour
コード例 #1
0
ファイル: ColorGrid.cs プロジェクト: samarjeet27/ynotesamples
 protected ColorGrid(ColorCollection colors, ColorCollection customColors, ColorPalette palette)
 {
     _cellBackground = Resources.cellbackground;
     _cellBackgroundBrush = new TextureBrush(_cellBackground, WrapMode.Tile);
     SetStyle(
         ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | ControlStyles.OptimizedDoubleBuffer |
         ControlStyles.Selectable | ControlStyles.StandardClick | ControlStyles.StandardDoubleClick |
         ControlStyles.SupportsTransparentBackColor, true);
     HotIndex = InvalidIndex;
     ColorRegions = new Dictionary<int, Rectangle>();
     if (Palette != ColorPalette.None)
         Colors = colors;
     else
         Palette = palette;
     CustomColors = customColors;
     ShowCustomColors = true;
     CellSize = new Size(12, 12);
     Spacing = new Size(3, 3);
     Columns = 16;
     AutoSize = true;
     Padding = new Padding(5);
     AutoAddColors = true;
     CellBorderColor = SystemColors.ButtonShadow;
     ShowToolTips = true;
     SeparatorHeight = 8;
     EditMode = ColorEditingMode.CustomOnly;
     Color = Color.Black;
     CellBorderStyle = ColorCellBorderStyle.FixedSingle;
     SelectedCellStyle = ColorGridSelectedCellStyle.Zoomed;
 }
コード例 #2
0
    void SwapColors_Original(ColorPalette palette)
    {
        if (palette.cachedTexture == null)
        {
            Texture2D texture = spriteRenderer.sprite.texture;

            var w = texture.width;
            var h = texture.height;

            var cloneTexture = new Texture2D(w, h);
            cloneTexture.wrapMode = TextureWrapMode.Clamp;
            cloneTexture.filterMode = FilterMode.Point;

            var colors = texture.GetPixels();

            for (int i = 0; i < colors.Length; i++)
            {
                colors[i] = palette.GetColor(colors[i]);
            }

            cloneTexture.SetPixels(colors);
            cloneTexture.Apply();

            palette.cachedTexture = cloneTexture;
        }

        block = new MaterialPropertyBlock();
        block.AddTexture("_MainTex", palette.cachedTexture);
    }
 public QuantizeColorEffect(IImageProvider source, ref Dictionary<uint, uint> assignedColorCache,
         List<uint> targetColors = null, ColorPalette colorPalette = ColorPalette.Color16)
     : base(source)
 {
     m_ColorPalette = colorPalette;
     TargetColors = (targetColors == null) ? TargetColors : targetColors; // Initialize TargetColors
     m_Cache = (assignedColorCache != null); // If color cache object passed in, then we will cache
     m_AssignedColorCache = assignedColorCache;
 }
コード例 #4
0
        /// <summary>
        /// Initializes a new instance of the <see cref="PixelPaletteGraphicsAdapter"/> class.
        /// </summary>
        /// <param name="pixelPaletteGraphicsDevice">The pixel palette graphics device.</param>
        public PixelPaletteGraphicsAdapter(IPixelPaletteGraphicsDevice pixelPaletteGraphicsDevice)
        {
            this.pixelPaletteGraphicsDevice = pixelPaletteGraphicsDevice;

            if (pixelPaletteGraphicsDevice.PaletteSize == 256)
                this.colorPalette = ColorPalette.CreateNetscape256ColorPalette();
            else
                this.colorPalette = ColorPalette.CreateStandard16ColorPalette();
        }
コード例 #5
0
        public IEnumerable<RenderedBitmap> Render(EpfImage image, ColorPalette palette)
        {
            if (image == null)
            throw new ArgumentNullException("image");

              if (palette == null)
            throw new ArgumentNullException("palette");

              foreach (var frame in image.Frames)
            yield return Render(frame, palette);
        }
コード例 #6
0
        public RenderedBitmap Render(EpfFrame frame, ColorPalette palette)
        {
            if (frame == null)
            throw new ArgumentNullException("frame");

              if (palette == null)
            throw new ArgumentNullException("palette");

              palette = palette.MakeGrayscale();
              var format = PixelFormats.Bgra32;

              var width = frame.Width;
              var height = frame.Height;
              var stride = (width * 4) + (width % 4);

              var bits = new byte[height * stride];

              for (int x = 0; x < width; x++)
            for (int y = 0; y < height; y++)
            {
              var fixedX = x;
              var fixedY = y;

              var threshold = 12;

              if (fixedX < threshold)
              {
            if (width >= threshold)
              fixedX = width - (threshold - fixedX);

            if (fixedY > 0)
              fixedY--;
              }
              else
            fixedX -= threshold;

              var pixel = frame.RawData[x + y * width];

              if (pixel > 0)
            SetPixel(bits, fixedX, fixedY, stride, palette[pixel]);
              else
            SetPixel(bits, fixedX, fixedY, stride, Colors.Transparent);
            }

              var bitmap = new RenderedBitmap(width, height, stride, format, bits);
              return bitmap;
        }
コード例 #7
0
 /// <summary>
 /// Converts ColorPalette enum value to a Color.
 /// </summary>
 /// <param name="enumValue">Enum value.</param>
 public static Color EnumToColor(ColorPalette enumValue)
 {
     switch (enumValue) {
         case ColorPalette.happyLittleAccident:
             return HappyLittleAccident();
         case ColorPalette.alizarinCrimson:
             return alizarinCrimson;
         case ColorPalette.brightRed:
             return brightRed;
         case ColorPalette.permanentRed:
             return permanentRed;
         case ColorPalette.cadmiumYellow:
             return cadmiumYellow;
         case ColorPalette.darkSienna:
             return darkSienna;
         case ColorPalette.indianYellow:
             return indianYellow;
         case ColorPalette.midnightBlack:
             return midnightBlack;
         case ColorPalette.phthaloBlue:
             return phthaloBlue;
         case ColorPalette.phthaloGreen:
             return phthaloGreen;
         case ColorPalette.prussianBlue:
             return prussianBlue;
         case ColorPalette.sapGreen:
             return sapGreen;
         case ColorPalette.titaniumWhite:
             return titaniumWhite;
         case ColorPalette.vanDykeBrown:
             return vanDykeBrown;
         case ColorPalette.yellowOchre:
             return yellowOchre;
         default:
             return HappyLittleAccident();
     }
 }
コード例 #8
0
        protected override void Initialize()
        {
            Answer.CheckAttributes |= GameAnswerCheckAttributes.MultiOption | GameAnswerCheckAttributes.IgnoreSpaces;

            switch (CurrentDifficulty)
            {
            case GameDifficulty.Easy:
                columns = rows = 5;
                break;

            case GameDifficulty.Medium:
                columns = rows = 6;
                break;

            case GameDifficulty.Master:
                columns = rows = 7;
                break;
            }

            squares         = columns * rows;
            rect_w          = 0.3 / rows;
            rect_h          = 0.3 / columns;
            squares_colours = new SquareColor [squares * answers];
            color_sheme     = random.Next(2);
            palette         = new ColorPalette();

            for (int i = 0; i < squares; i++)
            {
                squares_colours[i] = (SquareColor)random.Next((int)SquareColor.Length);
            }

            Randomize(squares_colours, 0, squares);
            Randomize(squares_colours, 0, squares * 2);
            Randomize(squares_colours, 0, squares * 3);

            answers_order = new ArrayListIndicesRandom(answers);
            answers_order.Initialize();

            for (int i = 0; i < answers_order.Count; i++)
            {
                if (answers_order[i] == 0)
                {
                    Answer.SetMultiOptionAnswer(i, Answer.GetFigureName(i));
                    break;
                }
            }

            base.Initialize();

            HorizontalContainer container = new HorizontalContainer(DrawAreaX, DrawAreaY, 0.8, 0.4);

            AddWidget(container);

            for (int i = 0; i < answers_order.Count; i++)
            {
                if (i == 2)
                {
                    container = new HorizontalContainer(DrawAreaX, DrawAreaY + 0.45, 0.8, 0.4);
                    AddWidget(container);
                }

                DrawableArea drawable_area = new DrawableArea(0.4, 0.4);
                container.AddChild(drawable_area);
                drawable_area.SelectedArea = new Rectangle(0.05, 0, 0.3, 0.3);
                drawable_area.Data         = i;
                drawable_area.DataEx       = Answer.GetMultiOption(i);

                drawable_area.DrawEventHandler += delegate(object sender, DrawEventArgs e)
                {
                    int n = (int)e.Data;

                    palette.Alpha = alpha;
                    DrawSquare(e.Context, 0.05, 0, squares_colours, squares * answers_order[n]);
                    e.Context.MoveTo(0.05, 0 + block_space - 0.02);
                    e.Context.ShowPangoText(Answer.GetFigureName(n));
                    e.Context.Stroke();
                };
            }
        }
コード例 #9
0
        /// <summary>
        /// Perform color dithering for the specified image.
        /// </summary>
        ///
        /// <param name="sourceImage">Source image to do color dithering for.</param>
        ///
        /// <returns>Returns color dithered image. See <see cref="ColorTable"/> for information about format of
        /// the result image.</returns>
        ///
        /// <exception cref="UnsupportedImageFormatException">Unsupported pixel format of the source image. It must 24 or 32 bpp color image.</exception>
        ///
        public unsafe Bitmap Apply(UnmanagedImage sourceImage)
        {
            if ((sourceImage.PixelFormat != PixelFormat.Format24bppRgb) &&
                (sourceImage.PixelFormat != PixelFormat.Format32bppRgb) &&
                (sourceImage.PixelFormat != PixelFormat.Format32bppArgb) &&
                (sourceImage.PixelFormat != PixelFormat.Format32bppPArgb))
            {
                throw new UnsupportedImageFormatException("Unsupported pixel format of the source image.");
            }

            cache.Clear( );

            // get image size
            int width     = sourceImage.Width;
            int height    = sourceImage.Height;
            int stride    = sourceImage.Stride;
            int pixelSize = Bitmap.GetPixelFormatSize(sourceImage.PixelFormat) / 8;

            int offset = stride - width * pixelSize;

            // create destination image
            Bitmap destImage = new Bitmap(width, height, (colorTable.Length > 16) ?
                                          PixelFormat.Format8bppIndexed : PixelFormat.Format4bppIndexed);
            // and init its palette
            ColorPalette cp = destImage.Palette;

            for (int i = 0, n = colorTable.Length; i < n; i++)
            {
                cp.Entries[i] = colorTable[i];
            }
            destImage.Palette = cp;

            // lock destination image
            BitmapData destData = destImage.LockBits(new Rectangle(0, 0, width, height),
                                                     ImageLockMode.ReadWrite, destImage.PixelFormat);

            // pixel values
            int r, g, b, toAdd;
            int rows = matrix.GetLength(0);
            int cols = matrix.GetLength(1);


            // do the job
            byte *ptr     = (byte *)sourceImage.ImageData.ToPointer( );
            byte *dstBase = (byte *)destData.Scan0.ToPointer( );
            byte  colorIndex;

            bool is8bpp = (colorTable.Length > 16);

            // for each line
            for (int y = 0; y < height; y++)
            {
                byte *dst = dstBase + y * destData.Stride;

                // for each pixels
                for (int x = 0; x < width; x++, ptr += pixelSize)
                {
                    toAdd = matrix[(y % rows), (x % cols)];
                    r     = ptr[RGB.R] + toAdd;
                    g     = ptr[RGB.G] + toAdd;
                    b     = ptr[RGB.B] + toAdd;

                    if (r > 255)
                    {
                        r = 255;
                    }
                    if (g > 255)
                    {
                        g = 255;
                    }
                    if (b > 255)
                    {
                        b = 255;
                    }

                    // get color from palette, which is the closest to current pixel's value
                    Color closestColor = GetClosestColor(r, g, b, out colorIndex);

                    // write color index as pixel's value to destination image
                    if (is8bpp)
                    {
                        *dst = colorIndex;
                        dst++;
                    }
                    else
                    {
                        if (x % 2 == 0)
                        {
                            *dst |= (byte)(colorIndex << 4);
                        }
                        else
                        {
                            *dst |= (colorIndex);
                            dst++;
                        }
                    }
                }
            }

            destImage.UnlockBits(destData);

            return(destImage);
        }
コード例 #10
0
 public IndexedBitmap(ColorPalette pal)
 {
     this.Bitmap         = new Bitmap(1, 1, PixelFormat.Format8bppIndexed);
     this.Bitmap.Palette = pal;
 }
コード例 #11
0
        public Bitmap PaletteMatch(ColorPalette parent, Bitmap child, bool[] used = null)
        {
            if (parent.Entries == child.Palette.Entries)
            {
                return(child);
            }
            if (used == null)
            {
                used = new bool[parent.Entries.Length];
                for (int i = 0; i < parent.Entries.Length; i++)
                {
                    used[i] = true;
                }
            }
            Bitmap       image        = ShrinkPalette(child);
            Bitmap       temp         = new Bitmap(1, 1, child.PixelFormat);
            ColorPalette childPalette = image.Palette;
            ColorPalette newPalette   = temp.Palette;
            int          size         = PaletteSize(image);

            byte[] array    = GetArray(image);
            byte[] indexof  = new byte[size];
            bool[] NotFound = new bool[size];
            for (int i = 0; i < size; i++)
            {
                NotFound[i] = true;
            }
            for (int i = 0; i < size; i++)
            {
                for (int j = 0; j < parent.Entries.Length; j++)
                {
                    if (parent.Entries[j] == childPalette.Entries[i])
                    {
                        indexof[i]  = (byte)j;
                        NotFound[i] = false;
                        break;
                    }
                }
            }
            int maxsize = 0;

            for (int i = 0; i < parent.Entries.Length; i++)
            {
                if (used[i])
                {
                    newPalette.Entries[i] = parent.Entries[i];
                    maxsize++;
                }
            }
            for (int i = 0; i < size; i++)
            {
                if (NotFound[i])
                {
                    maxsize++;
                }
            }
            for (int i = 0; i < maxsize; i++)
            {
                if ((i < used.Length) && (used[i]))
                {
                    continue;
                }
                for (int j = 0; j < size; j++)
                {
                    if (NotFound[j])
                    {
                        indexof[j]            = (byte)i;
                        newPalette.Entries[i] = childPalette.Entries[j];
                        NotFound[j]           = false;
                        break;
                    }
                }
            }
            byte[] newArray = new byte[array.Length];
            for (int i = 0; i < array.Length; i++)
            {
                newArray[i] = indexof[array[i]];
            }
            image         = MakeImage(child.Width, child.Height, newArray, child.PixelFormat);
            image.Palette = newPalette;
            return(image);
        }
コード例 #12
0
 public ColorGrid(ColorPalette palette)
     : this(null, new ColorCollection(Enumerable.Repeat(Color.White, 16)), palette)
 {
 }
コード例 #13
0
 // Setup colors
 public override void SetupColors(ColorPalette c)
 {
     base.SetupColors(c);
 }
コード例 #14
0
        private unsafe Bitmap ApplyMaskDuplicatingEdges(Bitmap originalImage, int[,] mask, ScalingMethod scalingMethod)
        {
            int depth      = 1;
            int maskHeight = mask.GetLength(0);
            int maskWidth  = mask.GetLength(1);

            Bitmap finalImage = new Bitmap(
                originalImage.Width,
                originalImage.Height,
                originalImage.PixelFormat);
            Bitmap unwrappedImage = new Bitmap(
                originalImage.Width + (maskWidth - 1),
                originalImage.Height + (maskHeight - 1),
                originalImage.PixelFormat);

            if (depth == 1)
            {
                ColorPalette finalPalette = finalImage.Palette;
                for (int i = 0; i < 256; ++i)
                {
                    finalPalette.Entries[i] = Color.FromArgb(i, i, i);
                }
                finalImage.Palette     = finalPalette;
                unwrappedImage.Palette = finalPalette;
            }

            lock (imageLock)
            {
                BitmapData originalBitmapData = originalImage.LockBits(
                    new Rectangle(0, 0, originalImage.Width, originalImage.Height),
                    ImageLockMode.ReadOnly,
                    originalImage.PixelFormat);
                BitmapData unwrappedBitmapData = unwrappedImage.LockBits(
                    new Rectangle(0, 0, unwrappedImage.Width, unwrappedImage.Height),
                    ImageLockMode.ReadOnly,
                    unwrappedImage.PixelFormat);

                byte *originalBitmapPointer  = (byte *)originalBitmapData.Scan0.ToPointer();
                byte *unwrappedBitmapPointer = (byte *)unwrappedBitmapData.Scan0.ToPointer();

                byte originalBitmapRemain  = (byte)(originalBitmapData.Stride - originalBitmapData.Width);
                byte unwrappedBitmapRemain = (byte)(unwrappedBitmapData.Stride - unwrappedBitmapData.Width);

                unwrappedBitmapPointer += unwrappedBitmapData.Stride * (maskHeight / 2) + depth * (maskWidth / 2);

                int unwrappedPointerOffset = unwrappedBitmapRemain + maskWidth * depth - depth;

                int workspaceWidth  = originalBitmapData.Width;
                int workspaceHeight = originalBitmapData.Height;

                //initial copying
                for (int i = 0; i < workspaceHeight; ++i)
                {
                    for (int j = 0; j < workspaceWidth; ++j)
                    {
                        unwrappedBitmapPointer[0] = originalBitmapPointer[0];

                        originalBitmapPointer  += depth;
                        unwrappedBitmapPointer += depth;
                    }
                    originalBitmapPointer  += originalBitmapRemain;
                    unwrappedBitmapPointer += unwrappedPointerOffset;
                }

                unwrappedBitmapPointer = (byte *)unwrappedBitmapData.Scan0.ToPointer() + (maskWidth / 2) * depth;
                originalBitmapPointer  = (byte *)originalBitmapData.Scan0.ToPointer();
                //copy rows
                for (int i = 0; i < maskHeight / 2; ++i)
                {
                    for (int j = 0; j < workspaceWidth; ++j)
                    {
                        unwrappedBitmapPointer[0] = originalBitmapPointer[0];
                        originalBitmapPointer    += depth;
                        unwrappedBitmapPointer   += depth;
                    }
                    originalBitmapPointer  -= originalBitmapData.Width;
                    unwrappedBitmapPointer += unwrappedPointerOffset;
                }

                unwrappedBitmapPointer += unwrappedBitmapData.Stride * originalBitmapData.Height;
                originalBitmapPointer  += originalBitmapData.Stride * originalBitmapData.Height;
                originalBitmapPointer  -= originalBitmapData.Width;

                for (int i = 0; i < maskHeight / 2; ++i)
                {
                    for (int j = 0; j < workspaceWidth; ++j)
                    {
                        unwrappedBitmapPointer[0] = originalBitmapPointer[0];
                        originalBitmapPointer    += depth;
                        unwrappedBitmapPointer   += depth;
                    }
                    originalBitmapPointer  -= originalBitmapData.Width;
                    unwrappedBitmapPointer += unwrappedPointerOffset;
                }

                workspaceHeight        = unwrappedBitmapData.Height;
                unwrappedBitmapPointer = (byte *)unwrappedBitmapData.Scan0.ToPointer();
                originalBitmapPointer  = unwrappedBitmapPointer;

                //Copy columns

                for (int i = 0; i < workspaceHeight; ++i)
                {
                    originalBitmapPointer += (maskHeight / 2) * depth;
                    for (int j = 0; j < maskWidth / 2; ++j)
                    {
                        unwrappedBitmapPointer[0] = originalBitmapPointer[0];
                        unwrappedBitmapPointer   += depth;
                    }
                    originalBitmapPointer  += originalBitmapData.Width * depth - depth;
                    unwrappedBitmapPointer += originalBitmapData.Width * depth;

                    for (int j = 0; j < maskWidth / 2; ++j)
                    {
                        unwrappedBitmapPointer[0] = originalBitmapPointer[0];
                        unwrappedBitmapPointer   += depth;
                    }
                    originalBitmapPointer  += maskWidth / 2 + unwrappedBitmapRemain + depth;
                    unwrappedBitmapPointer += unwrappedBitmapRemain;
                }

                originalImage.UnlockBits(originalBitmapData);

                BitmapData finalBitmapData = finalImage.LockBits(
                    new Rectangle(0, 0, finalImage.Width, finalImage.Height),
                    ImageLockMode.ReadOnly,
                    finalImage.PixelFormat);

                byte *finalBitmapPointer = (byte *)finalBitmapData.Scan0.ToPointer();
                byte  finalBitmapRemain  = (byte)(finalBitmapData.Stride - finalBitmapData.Width);

                unwrappedBitmapPointer  = (byte *)unwrappedBitmapData.Scan0.ToPointer();
                unwrappedBitmapPointer += unwrappedBitmapData.Stride * (maskHeight / 2) + depth * (maskWidth / 2);

                int helpingPointerOffset      = unwrappedBitmapData.Stride - maskWidth * depth;
                int helpingPointerStartOffset = unwrappedBitmapData.Stride * (maskHeight / 2) + depth * (maskWidth / 2);

                workspaceWidth  = unwrappedBitmapData.Width - maskWidth + depth;
                workspaceHeight = unwrappedBitmapData.Height - maskHeight + depth;
                //set up helping pointer
                byte *helpingPointer;

                int[,] result = new int[workspaceHeight, workspaceWidth];

                int usedSum;
                int pixelSum;

                for (int i = 0; i < workspaceHeight; ++i)
                {
                    for (int j = 0; j < workspaceWidth; ++j)
                    {
                        helpingPointer  = unwrappedBitmapPointer;
                        helpingPointer -= helpingPointerStartOffset;

                        usedSum  = 0;
                        pixelSum = 0;

                        for (int k = 0; k < maskHeight; ++k)
                        {
                            for (int l = 0; l < maskWidth; ++l)
                            {
                                pixelSum += mask[k, l] * helpingPointer[0];
                                usedSum  += mask[k, l];

                                helpingPointer += depth;
                            }
                            helpingPointer += helpingPointerOffset;
                        }

                        result[i, j] = pixelSum / (usedSum == 0 ? 1 : usedSum);

                        unwrappedBitmapPointer += depth;
                    }
                    unwrappedBitmapPointer += unwrappedPointerOffset;
                }

                byte[,] rescaled;
                switch (scalingMethod)
                {
                case ScalingMethod.RangeRescale:
                    rescaled = RescaleStretch(result);
                    break;

                case ScalingMethod.Cutting:
                    rescaled = RescaleCut(result);
                    break;

                case ScalingMethod.Trivalent:
                    rescaled = RescaleTrivalent(result);
                    break;

                default:
                    throw new ArgumentException("Unknown rescaling method");
                }

                //apply rescaled pixels
                for (int i = 0; i < workspaceHeight; ++i)
                {
                    for (int j = 0; j < workspaceWidth; ++j)
                    {
                        finalBitmapPointer[0] = rescaled[i, j];
                        finalBitmapPointer   += depth;
                    }
                    finalBitmapPointer += finalBitmapRemain;
                }

                unwrappedImage.UnlockBits(unwrappedBitmapData);
                finalImage.UnlockBits(finalBitmapData);
            }

            return(finalImage);
        }
コード例 #15
0
ファイル: ColorPalette.cs プロジェクト: hj1980/Mosa
        /// <summary>
        /// Gets the Netscape 256 color palette.
        /// </summary>
        /// <returns></returns>
        public static ColorPalette CreateNetscape256ColorPalette()
        {
            ColorPalette palette = new ColorPalette(256);

            palette.SetColor(0, 255, 255, 255);
            palette.SetColor(1, 255, 255, 204);
            palette.SetColor(2, 255, 255, 153);
            palette.SetColor(3, 255, 255, 102);
            palette.SetColor(4, 255, 255, 51);
            palette.SetColor(5, 255, 255, 0);
            palette.SetColor(6, 255, 204, 255);
            palette.SetColor(7, 255, 204, 204);
            palette.SetColor(8, 255, 204, 153);
            palette.SetColor(9, 255, 204, 102);
            palette.SetColor(10, 255, 204, 51);
            palette.SetColor(11, 255, 204, 0);
            palette.SetColor(12, 255, 153, 255);
            palette.SetColor(13, 255, 153, 204);
            palette.SetColor(14, 255, 153, 153);
            palette.SetColor(15, 255, 153, 102);
            palette.SetColor(16, 255, 153, 51);
            palette.SetColor(17, 255, 153, 0);
            palette.SetColor(18, 255, 102, 255);
            palette.SetColor(19, 255, 102, 204);
            palette.SetColor(20, 255, 102, 153);
            palette.SetColor(21, 255, 102, 102);
            palette.SetColor(22, 255, 102, 51);
            palette.SetColor(23, 255, 102, 0);
            palette.SetColor(24, 255, 51, 255);
            palette.SetColor(25, 255, 51, 204);
            palette.SetColor(26, 255, 51, 153);
            palette.SetColor(27, 255, 51, 102);
            palette.SetColor(28, 255, 51, 51);
            palette.SetColor(29, 255, 51, 0);
            palette.SetColor(30, 255, 0, 255);
            palette.SetColor(31, 255, 0, 204);
            palette.SetColor(32, 255, 0, 153);
            palette.SetColor(33, 255, 0, 102);
            palette.SetColor(34, 255, 0, 51);
            palette.SetColor(35, 255, 0, 0);
            palette.SetColor(36, 204, 255, 255);
            palette.SetColor(37, 204, 255, 204);
            palette.SetColor(38, 204, 255, 153);
            palette.SetColor(39, 204, 255, 102);
            palette.SetColor(40, 204, 255, 51);
            palette.SetColor(41, 204, 255, 0);
            palette.SetColor(42, 204, 204, 255);
            palette.SetColor(43, 204, 204, 204);
            palette.SetColor(44, 204, 204, 153);
            palette.SetColor(45, 204, 204, 102);
            palette.SetColor(46, 204, 204, 51);
            palette.SetColor(47, 204, 204, 0);
            palette.SetColor(48, 204, 153, 255);
            palette.SetColor(49, 204, 153, 204);
            palette.SetColor(50, 204, 153, 153);
            palette.SetColor(51, 204, 153, 102);
            palette.SetColor(52, 204, 153, 51);
            palette.SetColor(53, 204, 153, 0);
            palette.SetColor(54, 204, 102, 255);
            palette.SetColor(55, 204, 102, 204);
            palette.SetColor(56, 204, 102, 153);
            palette.SetColor(57, 204, 102, 102);
            palette.SetColor(58, 204, 102, 51);
            palette.SetColor(59, 204, 102, 0);
            palette.SetColor(60, 204, 51, 255);
            palette.SetColor(61, 204, 51, 204);
            palette.SetColor(62, 204, 51, 153);
            palette.SetColor(63, 204, 51, 102);
            palette.SetColor(64, 204, 51, 51);
            palette.SetColor(65, 204, 51, 0);
            palette.SetColor(66, 204, 0, 255);
            palette.SetColor(67, 204, 0, 204);
            palette.SetColor(68, 204, 0, 153);
            palette.SetColor(69, 204, 0, 102);
            palette.SetColor(70, 204, 0, 51);
            palette.SetColor(71, 204, 0, 0);
            palette.SetColor(72, 153, 255, 255);
            palette.SetColor(73, 153, 255, 204);
            palette.SetColor(74, 153, 255, 153);
            palette.SetColor(75, 153, 255, 102);
            palette.SetColor(76, 153, 255, 51);
            palette.SetColor(77, 153, 255, 0);
            palette.SetColor(78, 153, 204, 255);
            palette.SetColor(79, 153, 204, 204);
            palette.SetColor(80, 153, 204, 153);
            palette.SetColor(81, 153, 204, 102);
            palette.SetColor(82, 153, 204, 51);
            palette.SetColor(83, 153, 204, 0);
            palette.SetColor(84, 153, 153, 255);
            palette.SetColor(85, 153, 153, 204);
            palette.SetColor(86, 153, 153, 153);
            palette.SetColor(87, 153, 153, 102);
            palette.SetColor(88, 153, 153, 51);
            palette.SetColor(89, 153, 153, 0);
            palette.SetColor(90, 153, 102, 255);
            palette.SetColor(91, 153, 102, 204);
            palette.SetColor(92, 153, 102, 153);
            palette.SetColor(93, 153, 102, 102);
            palette.SetColor(94, 153, 102, 51);
            palette.SetColor(95, 153, 102, 0);
            palette.SetColor(96, 153, 51, 255);
            palette.SetColor(97, 153, 51, 204);
            palette.SetColor(98, 153, 51, 153);
            palette.SetColor(99, 153, 51, 102);
            palette.SetColor(100, 153, 51, 51);
            palette.SetColor(101, 153, 51, 0);
            palette.SetColor(102, 153, 0, 255);
            palette.SetColor(103, 153, 0, 204);
            palette.SetColor(104, 153, 0, 153);
            palette.SetColor(105, 153, 0, 102);
            palette.SetColor(106, 153, 0, 51);
            palette.SetColor(107, 153, 0, 0);
            palette.SetColor(108, 102, 255, 255);
            palette.SetColor(109, 102, 255, 204);
            palette.SetColor(110, 102, 255, 153);
            palette.SetColor(111, 102, 255, 102);
            palette.SetColor(112, 102, 255, 51);
            palette.SetColor(113, 102, 255, 0);
            palette.SetColor(114, 102, 204, 255);
            palette.SetColor(115, 102, 204, 204);
            palette.SetColor(116, 102, 204, 153);
            palette.SetColor(117, 102, 204, 102);
            palette.SetColor(118, 102, 204, 51);
            palette.SetColor(119, 102, 204, 0);
            palette.SetColor(120, 102, 153, 255);
            palette.SetColor(121, 102, 153, 204);
            palette.SetColor(122, 102, 153, 153);
            palette.SetColor(123, 102, 153, 102);
            palette.SetColor(124, 102, 153, 51);
            palette.SetColor(125, 102, 153, 0);
            palette.SetColor(126, 102, 102, 255);
            palette.SetColor(127, 102, 102, 204);
            palette.SetColor(128, 102, 102, 153);
            palette.SetColor(129, 102, 102, 102);
            palette.SetColor(130, 102, 102, 51);
            palette.SetColor(131, 102, 102, 0);
            palette.SetColor(132, 102, 51, 255);
            palette.SetColor(133, 102, 51, 204);
            palette.SetColor(134, 102, 51, 153);
            palette.SetColor(135, 102, 51, 102);
            palette.SetColor(136, 102, 51, 51);
            palette.SetColor(137, 102, 51, 0);
            palette.SetColor(138, 102, 0, 255);
            palette.SetColor(139, 102, 0, 204);
            palette.SetColor(140, 102, 0, 153);
            palette.SetColor(141, 102, 0, 102);
            palette.SetColor(142, 102, 0, 0);
            palette.SetColor(143, 102, 0, 0);
            palette.SetColor(144, 51, 255, 255);
            palette.SetColor(145, 51, 255, 204);
            palette.SetColor(146, 51, 255, 153);
            palette.SetColor(147, 51, 255, 102);
            palette.SetColor(148, 51, 255, 51);
            palette.SetColor(149, 51, 255, 0);
            palette.SetColor(150, 51, 204, 255);
            palette.SetColor(151, 51, 204, 204);
            palette.SetColor(152, 51, 204, 153);
            palette.SetColor(153, 51, 204, 102);
            palette.SetColor(154, 51, 204, 51);
            palette.SetColor(155, 51, 204, 0);
            palette.SetColor(156, 51, 153, 255);
            palette.SetColor(157, 51, 153, 204);
            palette.SetColor(158, 51, 153, 153);
            palette.SetColor(159, 51, 153, 102);
            palette.SetColor(160, 51, 153, 51);
            palette.SetColor(161, 51, 153, 0);
            palette.SetColor(162, 51, 102, 255);
            palette.SetColor(163, 51, 102, 204);
            palette.SetColor(164, 51, 102, 153);
            palette.SetColor(165, 51, 102, 102);
            palette.SetColor(166, 51, 102, 51);
            palette.SetColor(167, 51, 102, 0);
            palette.SetColor(168, 51, 51, 255);
            palette.SetColor(169, 51, 51, 204);
            palette.SetColor(170, 51, 51, 153);
            palette.SetColor(171, 51, 51, 102);
            palette.SetColor(172, 51, 51, 51);
            palette.SetColor(173, 51, 51, 0);
            palette.SetColor(174, 51, 0, 255);
            palette.SetColor(175, 51, 0, 204);
            palette.SetColor(176, 51, 0, 153);
            palette.SetColor(177, 51, 0, 102);
            palette.SetColor(178, 51, 0, 51);
            palette.SetColor(179, 51, 0, 0);
            palette.SetColor(180, 0, 255, 255);
            palette.SetColor(181, 0, 255, 204);
            palette.SetColor(182, 0, 255, 153);
            palette.SetColor(183, 0, 255, 102);
            palette.SetColor(184, 0, 255, 51);
            palette.SetColor(185, 0, 255, 0);
            palette.SetColor(186, 0, 204, 255);
            palette.SetColor(187, 0, 204, 204);
            palette.SetColor(188, 0, 204, 153);
            palette.SetColor(189, 0, 204, 102);
            palette.SetColor(190, 0, 204, 51);
            palette.SetColor(191, 0, 204, 0);
            palette.SetColor(192, 0, 153, 255);
            palette.SetColor(193, 0, 153, 204);
            palette.SetColor(194, 0, 153, 153);
            palette.SetColor(195, 0, 153, 102);
            palette.SetColor(196, 0, 153, 51);
            palette.SetColor(197, 0, 153, 0);
            palette.SetColor(198, 0, 102, 255);
            palette.SetColor(199, 0, 102, 204);
            palette.SetColor(200, 0, 102, 153);
            palette.SetColor(201, 0, 102, 102);
            palette.SetColor(202, 0, 102, 51);
            palette.SetColor(203, 0, 102, 0);
            palette.SetColor(204, 0, 51, 255);
            palette.SetColor(205, 0, 51, 204);
            palette.SetColor(206, 0, 51, 153);
            palette.SetColor(207, 0, 51, 102);
            palette.SetColor(208, 0, 51, 51);
            palette.SetColor(209, 0, 51, 0);
            palette.SetColor(210, 0, 0, 255);
            palette.SetColor(211, 0, 0, 204);
            palette.SetColor(212, 0, 0, 153);
            palette.SetColor(213, 0, 0, 102);
            palette.SetColor(214, 0, 0, 51);
            palette.SetColor(215, 238, 0, 0);
            palette.SetColor(216, 221, 0, 0);
            palette.SetColor(217, 187, 0, 0);
            palette.SetColor(218, 170, 0, 0);
            palette.SetColor(219, 136, 0, 0);
            palette.SetColor(220, 119, 0, 0);
            palette.SetColor(221, 85, 0, 0);
            palette.SetColor(222, 68, 0, 0);
            palette.SetColor(223, 34, 0, 0);
            palette.SetColor(224, 17, 0, 0);
            palette.SetColor(225, 0, 238, 0);
            palette.SetColor(226, 0, 221, 0);
            palette.SetColor(227, 0, 187, 0);
            palette.SetColor(228, 0, 170, 0);
            palette.SetColor(229, 0, 136, 0);
            palette.SetColor(230, 0, 119, 0);
            palette.SetColor(231, 0, 85, 0);
            palette.SetColor(232, 0, 68, 0);
            palette.SetColor(233, 0, 34, 0);
            palette.SetColor(234, 0, 17, 0);
            palette.SetColor(235, 0, 0, 238);
            palette.SetColor(236, 0, 0, 221);
            palette.SetColor(237, 0, 0, 187);
            palette.SetColor(238, 0, 0, 170);
            palette.SetColor(239, 0, 0, 136);
            palette.SetColor(240, 0, 0, 119);
            palette.SetColor(241, 0, 0, 85);
            palette.SetColor(242, 0, 0, 68);
            palette.SetColor(243, 0, 0, 34);
            palette.SetColor(244, 0, 0, 17);
            palette.SetColor(245, 238, 238, 238);
            palette.SetColor(246, 221, 221, 221);
            palette.SetColor(247, 187, 187, 187);
            palette.SetColor(248, 170, 170, 170);
            palette.SetColor(249, 136, 136, 136);
            palette.SetColor(250, 119, 119, 119);
            palette.SetColor(251, 85, 85, 85);
            palette.SetColor(252, 68, 68, 68);
            palette.SetColor(253, 34, 34, 34);
            palette.SetColor(254, 17, 17, 17);
            palette.SetColor(255, 0, 0, 0);

            return palette;
        }
コード例 #16
0
        public GraphicsImage(Reader reader, bool dcGFX = false)
        {
            if (dcGFX)
            {
                reader.ReadByte();
            }

            width  = (ushort)(reader.ReadByte() << 8);
            width |= reader.ReadByte();

            height  = (ushort)(reader.ReadByte() << 8);
            height |= reader.ReadByte();

            // Create image
            gfxImage = new Bitmap(width, height, PixelFormat.Format8bppIndexed);

            ColorPalette cp = gfxImage.Palette;

            // Read & Process palette
            for (int i = 0; i < 255; i++)
            {
                GFXpal[i].R   = reader.ReadByte();
                GFXpal[i].G   = reader.ReadByte();
                GFXpal[i].B   = reader.ReadByte();
                cp.Entries[i] = Color.FromArgb(255, GFXpal[i].R, GFXpal[i].G, GFXpal[i].B);
            }
            gfxImage.Palette = cp;

            //Read Image Data
            byte[] buf      = new byte[3];
            bool   finished = false;
            int    cnt      = 0;
            int    loop     = 0;

            data = new byte[(width * height) + 1];

            while (!finished)
            {
                buf[0] = reader.ReadByte();
                if (buf[0] == 255)
                {
                    buf[1] = reader.ReadByte();
                    if (buf[1] == 255)
                    {
                        finished = true;
                        break;
                    }
                    else
                    {
                        buf[2] = reader.ReadByte();
                        loop   = 0;

                        // Repeat value needs to decreased by one to decode
                        // the graphics from the Dreamcast demo
                        if (dcGFX)
                        {
                            buf[2]--;
                        }

                        while (loop < buf[2] && !reader.IsEof)
                        {
                            data[cnt++] = buf[1];
                            loop++;
                        }
                    }
                }
                else
                {
                    data[cnt++] = buf[0];
                }
            }

            Console.Write("file Length = " + reader.BaseStream.Length + " file pos = " + reader.Pos + " data remaining = " + (reader.BaseStream.Length - reader.Pos));

            // Write data to image
            int pixel = 0;

            for (int h = 0; h < height; h++)
            {
                for (int w = 0; w < width; w++)
                {
                    BitmapData ImgData = gfxImage.LockBits(new Rectangle(new Point(w, h), new Size(1, 1)), System.Drawing.Imaging.ImageLockMode.ReadWrite, System.Drawing.Imaging.PixelFormat.Format8bppIndexed);
                    byte       b       = System.Runtime.InteropServices.Marshal.ReadByte(ImgData.Scan0);
                    System.Runtime.InteropServices.Marshal.WriteByte(ImgData.Scan0, (data[pixel]));
                    gfxImage.UnlockBits(ImgData);
                    pixel++;
                }
            }

            reader.Close();
        }
コード例 #17
0
        private Image GetQuantizedImage(Image image)
        {
            if (image == null)
            {
                const string message = "Cannot quantize your file. Please choose a new file.";
                throw new ArgumentNullException(message);
            }

            Bitmap     bitmap     = (Bitmap)image;
            Rectangle  bounds     = Rectangle.FromLTRB(0, 0, bitmap.Width, bitmap.Height);
            BitmapData sourceData = bitmap.LockBits(bounds, ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);

            try
            {
                int[] sourceBuffer = new int[image.Width];

                long sourceOffset = sourceData.Scan0.ToInt64();

                for (int i = 0; i < image.Height; i++)
                {
                    Marshal.Copy(new IntPtr(sourceOffset), sourceBuffer, 0, image.Width);

                    foreach (Color color in sourceBuffer.Select(argb => Color.FromArgb(argb)))
                    {
                        this.activeQuantizer.AddColor(color);
                    }

                    sourceOffset += sourceData.Stride;
                }
            }
            catch
            {
                bitmap.UnlockBits(sourceData);
                throw;
            }

            Bitmap result = new Bitmap(image.Width, image.Height, PixelFormat.Format8bppIndexed);

            try
            {
                List <Color> palette      = this.activeQuantizer.GetPalette(256);
                ColorPalette imagePalette = result.Palette;

                for (Int32 index = 0; index < palette.Count; index++)
                {
                    imagePalette.Entries[index] = palette[index];
                }

                PaletteBox.Image = GetPalette.GetPaletteBitmap(palette);
                result.Palette   = imagePalette;
            }
            catch (Exception)
            {
                bitmap.UnlockBits(sourceData);
                throw;
            }

            BitmapData targetData = result.LockBits(bounds, ImageLockMode.WriteOnly, PixelFormat.Format8bppIndexed);

            try
            {
                byte[] targetBuffer = new byte[result.Width];
                int[]  sourceBuffer = new int[image.Width];

                long sourceOffset = sourceData.Scan0.ToInt64();
                long targetOffset = targetData.Scan0.ToInt64();

                for (int i = 0; i < image.Height; i++)
                {
                    Marshal.Copy(new IntPtr(sourceOffset), sourceBuffer, 0, image.Width);

                    for (int j = 0; j < image.Width; j++)
                    {
                        Color color = Color.FromArgb(sourceBuffer[j]);
                        targetBuffer[j] = (byte)this.activeQuantizer.GetPaletteIndex(color);
                    }

                    Marshal.Copy(targetBuffer, 0, new IntPtr(targetOffset), result.Width);

                    sourceOffset += sourceData.Stride;
                    targetOffset += targetData.Stride;
                }
            }
            finally
            {
                bitmap.UnlockBits(sourceData);
                result.UnlockBits(targetData);
            }

            this.result           = result;
            ColorDistanceBox.Text = ColorDistance.GetColorDistance(this.sourceImage, result).ToString();
            return(result);
        }
コード例 #18
0
    private static void SaveBitmapPaletteDirect(Dataset ds, string filename, int iOverview)
    {
        // Get the GDAL Band objects from the Dataset
        Band band = ds.GetRasterBand(1);

        if (iOverview >= 0 && band.GetOverviewCount() > iOverview)
        {
            band = band.GetOverview(iOverview);
        }

        ColorTable ct = band.GetRasterColorTable();

        if (ct == null)
        {
            Console.WriteLine("   Band has no color table!");
            return;
        }

        if (ct.GetPaletteInterpretation() != PaletteInterp.GPI_RGB)
        {
            Console.WriteLine("   Only RGB palette interp is supported by this sample!");
            return;
        }

        // Get the width and height of the Dataset
        int width  = band.XSize;
        int height = band.YSize;

        // Create a Bitmap to store the GDAL image in
        Bitmap bitmap = new Bitmap(width, height, PixelFormat.Format8bppIndexed);

        DateTime start = DateTime.Now;

        byte[] r = new byte[width * height];

        band.ReadRaster(0, 0, width, height, r, width, height, 0, 0);
        // Use GDAL raster reading methods to read the image data directly into the Bitmap
        BitmapData bitmapData = bitmap.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite, PixelFormat.Format8bppIndexed);

        try
        {
            int          iCol = ct.GetCount();
            ColorPalette pal  = bitmap.Palette;
            for (int i = 0; i < iCol; i++)
            {
                ColorEntry ce = ct.GetColorEntry(i);
                pal.Entries[i] = Color.FromArgb(ce.c4, ce.c1, ce.c2, ce.c3);
            }
            bitmap.Palette = pal;

            int    stride = bitmapData.Stride;
            IntPtr buf    = bitmapData.Scan0;

            band.ReadRaster(0, 0, width, height, buf, width, height, DataType.GDT_Byte, 1, stride);
            TimeSpan renderTime = DateTime.Now - start;
            Console.WriteLine("SaveBitmapDirect fetch time: " + renderTime.TotalMilliseconds + " ms");
        }
        finally
        {
            bitmap.UnlockBits(bitmapData);
        }

        bitmap.Save(filename);
    }
コード例 #19
0
        public override void OnGUI()
        {
            base.OnGUI();
            //CheckDoc
            MarkDownDoc doc = null;

            if (string.IsNullOrEmpty(CurrentDocName))
            {
                if (Docs.TryGetValue("Index", out doc))
                {
                    CurrentDocName = "Index";
                }
            }
            else
            {
                doc = Docs[CurrentDocName];
                if (Event.current.type == EventType.Layout)
                {
                    if (DocPages.Count > 0)
                    {
                        var oldDoc = Docs[DocPages.Peek()];
                        if (oldDoc.datas.Count > 0)
                        {
                            oldDoc.Release();
                        }
                    }
                    if (doc.datas.Count == 0)
                    {
                        doc.Load();
                    }
                    else
                    {
                        if (AutoRefresh && doc.RawDoc.text != doc.rawDoc)
                        {
                            doc.Release();
                            doc.rawDoc = doc.RawDoc.text;
                            doc.Load();
                        }
                    }
                }
            }
            //DrawDoc
            if (doc != null)
            {
                //ToolBar
                ToolBar();
                //DocContent
                EditorGUI.DrawRect(DrawRect, ColorPalette.Get(ColorSettings, "BackGround", Color.white));
                v = GUILayout.BeginScrollView(v);
                {
                    if (searched != null)
                    {
                        if (Event.current.type == EventType.Repaint)
                        {
                            EditorGUI.DrawRect(searched.drawRect, ColorPalette.Get(ColorSettings, "HightLight", Color.white));
                        }
                        if (Search.Current.IsNullOrEmpty())
                        {
                            searched = null;
                        }
                    }
                    EditorMarkDownDrawer.DrawDoc(doc, changePage, changeDoc, window.Repaint);
                }
                GUILayout.EndScrollView();
                if (Event.current.type == EventType.Repaint)
                {
                    DrawRect = GUILayoutUtility.GetLastRect();
                }
            }
            else
            {
                EditorGUILayout.SelectableLabel("Can't find Index.md Document at :" + PathTools.RelativeAssetPath(this.GetType(), RelativePath));
                EditorGUILayout.SelectableLabel("First you should create default page");
                if (GUILayout.Button("CreateReadMe"))
                {
                    if (EditorUtility.DisplayDialog("CreateIndex.md", "After create .md file,you have to reopen this editorwindow.", "OK", "Cancel"))
                    {
                        //Template
                        string[]  assets = AssetDatabase.FindAssets("TMP_ReadMe");
                        TextAsset text   = AssetDatabase.LoadAssetAtPath <TextAsset>(AssetDatabase.GUIDToAssetPath(assets[0]));
                        //
                        var DirRoot     = PathTools.RelativeAssetPath(this.GetType(), RelativePath);
                        var FileDirRoot = Directory.GetParent(DirRoot).FullName + @"\" + Path.GetFileName(DirRoot);
                        if (!Directory.Exists(FileDirRoot))
                        {
                            Directory.CreateDirectory(FileDirRoot);
                        }
                        FileTools.WriteAllText(FileDirRoot + "/Index.md", text.text);

                        AssetDatabase.Refresh();
                        window.Close();
                    }
                }
            }
            //PingDocScript
            if (EditScript)
            {
                GUILayout.BeginHorizontal();
                {
                    AutoRefresh = GUILayout.Toggle(AutoRefresh, "自动刷新");
                    OnGUIUtility.ScriptField("Editor Script", this.GetType());
                }
                GUILayout.EndHorizontal();
            }
        }
コード例 #20
0
ファイル: SpriteTools.cs プロジェクト: mo-g/ags
        public static Bitmap GetPlaceHolder(int width = 12, int height = 7)
        {
            if (width <= 0 || height <= 0)
            {
                throw new ArgumentOutOfRangeException("Cannot generate a zero-sized bitmap");
            }

            // fine art as a byte array
            byte[][] cup =
            {
                new byte[12] {
                    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
                },
                new byte[12] {
                    0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00
                },
                new byte[12] {
                    0x00, 0x01, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x01, 0x01, 0x01, 0x00
                },
                new byte[12] {
                    0x00, 0x01, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x01, 0x00, 0x01, 0x00
                },
                new byte[12] {
                    0x00, 0x01, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x01, 0x01, 0x01, 0x00
                },
                new byte[12] {
                    0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00
                },
                new byte[12] {
                    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
                }
            };

            Bitmap     bitmap     = new Bitmap(width, height, PixelFormat.Format8bppIndexed);
            BitmapData bitmapData = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.WriteOnly, bitmap.PixelFormat);
            long       ptr        = bitmapData.Scan0.ToInt64();
            int        y          = 0;

            for (int row = 0; row < height; row++)
            {
                int x    = 0;
                int span = cup[y].Length;

                while (span == cup[y].Length)
                {
                    if (x + span >= width)
                    {
                        // align with the right edge of the bitmap
                        span = width - x;
                    }

                    Marshal.Copy(cup[y], 0, new IntPtr(ptr), span);
                    x   += span;
                    ptr += span;
                }

                // align with bitmap stride
                ptr += bitmapData.Stride - x;

                // next image row
                if (y == cup.Length - 1)
                {
                    y = 0;
                }
                else
                {
                    y++;
                }
            }

            bitmap.UnlockBits(bitmapData);

            // set colours
            ColorPalette palette = bitmap.Palette;

            palette.Entries[0] = Color.FromArgb(0, 0, 0);
            palette.Entries[1] = Color.FromArgb(85, 85, 255);
            palette.Entries[2] = Color.FromArgb(0, 0, 170);
            bitmap.Palette     = palette;

            return(bitmap);
        }
コード例 #21
0
        public IEnumerable <ColorLegendItemDto> Create(Type type, ColorMap map, List <object> values, ColorPalette palette)
        {
            if (type == typeof(Boolean))
            {
                return(_booleanFactory.Create(map, values.Cast <bool?>().ToList(), palette));
            }

            if (type == typeof(DateTime))
            {
                return(_dateTimeFactory.Create(map, values.Cast <DateTime?>().ToList(), palette));
            }

            if (type == typeof(Double))
            {
                return(_floatFactory.Create(map, values.Cast <double?>().ToList(), palette));
            }

            if (type == typeof(Int32))
            {
                return(_integerFactory.Create(map, values.Cast <int?>().ToList(), palette));
            }

            if (type == typeof(String))
            {
                return(_stringFactory.Create(map, values.Cast <string>().ToList(), palette));
            }

            throw new ArgumentException("Could not create color legend items because data type was not recognized");
        }
コード例 #22
0
        private unsafe Bitmap ApplyMaskIgnoringEdges(Bitmap originalImage, int[,] mask, ScalingMethod scalingMethod)
        {
            Bitmap finalImage = new Bitmap(
                originalImage.Width,
                originalImage.Height,
                originalImage.PixelFormat);

            int depth      = 1;
            int maskHeight = mask.GetLength(0);
            int maskWidth  = mask.GetLength(1);

            ColorPalette finalPalette = finalImage.Palette;

            for (int i = 0; i < 256; ++i)
            {
                finalPalette.Entries[i] = Color.FromArgb(i, i, i);
            }
            finalImage.Palette = finalPalette;

            lock (imageLock)
            {
                BitmapData originalBitmapData = originalImage.LockBits(
                    new Rectangle(0, 0, originalImage.Width, originalImage.Height),
                    ImageLockMode.ReadOnly,
                    originalImage.PixelFormat);
                BitmapData finalBitmapData = finalImage.LockBits(
                    new Rectangle(0, 0, finalImage.Width, finalImage.Height),
                    ImageLockMode.ReadOnly,
                    finalImage.PixelFormat);

                byte *originalBitmapPointer = (byte *)originalBitmapData.Scan0.ToPointer();
                byte *finalBitmapPointer    = (byte *)finalBitmapData.Scan0.ToPointer();

                byte originalBitmapRemain = (byte)(originalBitmapData.Stride - originalBitmapData.Width);
                byte finalBitmapRemain    = (byte)(finalBitmapData.Stride - finalBitmapData.Width);

                //set up pointers starting positions
                originalBitmapPointer += originalBitmapData.Stride * (maskHeight / 2) + depth * (maskWidth / 2);
                finalBitmapPointer    += finalBitmapData.Stride * (maskHeight / 2) + depth * (maskWidth / 2);

                //pointers next row offsets
                int originalPointerOffset = originalBitmapRemain + maskWidth * depth - depth;
                int finalPointerOffset    = finalBitmapRemain + maskWidth * depth - depth;
                int helpingPointerOffset  = originalBitmapData.Stride - maskWidth * depth;

                int helpingPointerStartOffset = originalBitmapData.Stride * (maskHeight / 2) + depth * (maskWidth / 2);

                int workspaceWidth  = originalImage.Width - maskWidth + depth;
                int workspaceHeigth = originalImage.Height - maskHeight + depth;
                //set up helping pointer
                byte *helpingPointer;

                int[,] result = new int[workspaceHeigth, workspaceWidth];

                int usedSum;
                int pixelSum;
                for (int i = 0; i < workspaceHeigth; ++i)
                {
                    for (int j = 0; j < workspaceWidth; ++j)
                    {
                        helpingPointer  = originalBitmapPointer;
                        helpingPointer -= helpingPointerStartOffset;

                        usedSum  = 0;
                        pixelSum = 0;
                        for (int k = 0; k < maskHeight; ++k)
                        {
                            for (int l = 0; l < maskWidth; ++l)
                            {
                                pixelSum += mask[k, l] * helpingPointer[0];
                                usedSum  += mask[k, l];

                                helpingPointer += depth;
                            }
                            helpingPointer += helpingPointerOffset;
                        }
                        result[i, j] = pixelSum / (usedSum == 0 ? 1 : usedSum);

                        originalBitmapPointer += depth;
                    }
                    originalBitmapPointer += originalPointerOffset;
                }

                //rescale
                byte[,] rescaled;
                switch (scalingMethod)
                {
                case ScalingMethod.RangeRescale:
                    rescaled = RescaleStretch(result);
                    break;

                case ScalingMethod.Cutting:
                    rescaled = RescaleCut(result);
                    break;

                case ScalingMethod.Trivalent:
                    rescaled = RescaleTrivalent(result);
                    break;

                default:
                    throw new ArgumentException("Unknown rescaling method");
                }

                //apply rescaled pixels
                for (int i = 0; i < workspaceHeigth; ++i)
                {
                    for (int j = 0; j < workspaceWidth; ++j)
                    {
                        finalBitmapPointer[0] = rescaled[i, j];
                        finalBitmapPointer   += depth;
                    }
                    finalBitmapPointer += finalPointerOffset;
                }

                originalImage.UnlockBits(originalBitmapData);
                finalImage.UnlockBits(finalBitmapData);
            }

            return(finalImage);
        }
コード例 #23
0
ファイル: SandJar.cs プロジェクト: xipeluife/GGJ2016
	public static Jar CreateTargetSandJar(ColorPalette palette)
	{
		List<Color> remainingColors = new List<Color> (palette.Colors);
		List<Color> result = new List<Color>();

		int layerNumber = Random.Range(remainingColors.Count, MaximumLayerNumber);

		while(remainingColors.Count > 0)
		{
			// Take one reandomly from available and put it on the queue
			int randomIndex = Random.Range(0, remainingColors.Count);
			Color targetColor = remainingColors[randomIndex];
			remainingColors.RemoveAt(randomIndex);
			result.Add(targetColor);

			if(result.Count > 1 && result.Count <= layerNumber)
			{
				// Check if repeating
				if((Random.Range(0.0f,1.0f) > 0.5f))
				{
					for(int i = 0; i < result.Count - 1; i++)
					{
						// Maybe repeat all except the last one
						if((Random.Range(0.0f,1.0f) > 0.5f))
						{
							result.Add(result[i]);
							break;
						}
					}					
				}
			}
		}

		// Assign layer percentages
		List<float> layerAmount = new List<float>();
		float equalAmount = 1f / result.Count;

		for(int i = 0; i < result.Count; i++)
		{
			layerAmount.Add(equalAmount);
		}

		Jar resultJar;
		resultJar.ColorsToFill = result;
		resultJar.PercentageFilled = layerAmount;
		resultJar.ColorsFilled = new Color[result.Count];
		resultJar.currentIndex = 0;

		return resultJar;

	}
        public unsafe Bitmap ReduceColors(UnmanagedImage image, Color[] palette)
        {
            if (((image.PixelFormat != PixelFormat.Format24bppRgb) && (image.PixelFormat != PixelFormat.Format32bppRgb)) && ((image.PixelFormat != PixelFormat.Format32bppArgb) && (image.PixelFormat != PixelFormat.Format32bppPArgb)))
            {
                throw new UnsupportedImageFormatException("Unsupported format of the source image.");
            }
            if ((palette.Length < 2) || (palette.Length > 0x100))
            {
                throw new ArgumentException("Invalid size of the target color palette.");
            }
            this.paletteToUse = palette;
            this.cache.Clear();
            int          width    = image.Width;
            int          height   = image.Height;
            int          stride   = image.Stride;
            int          num4     = Image.GetPixelFormatSize(image.PixelFormat) / 8;
            int          num5     = stride - (width * num4);
            Bitmap       bitmap   = new Bitmap(width, height, (palette.Length > 0x10) ? PixelFormat.Format8bppIndexed : PixelFormat.Format4bppIndexed);
            ColorPalette palette2 = bitmap.Palette;
            int          index    = 0;
            int          length   = palette.Length;

            while (index < length)
            {
                palette2.Entries[index] = palette[index];
                index++;
            }
            bitmap.Palette = palette2;
            BitmapData bitmapdata = bitmap.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite, bitmap.PixelFormat);
            byte *     numPtr     = (byte *)image.ImageData.ToPointer();
            byte *     numPtr2    = (byte *)bitmapdata.Scan0.ToPointer();
            bool       flag       = palette.Length > 0x10;

            for (int i = 0; i < height; i++)
            {
                byte *numPtr3 = numPtr2 + (i * bitmapdata.Stride);
                int   num9    = 0;
                while (num9 < width)
                {
                    byte num10 = (byte)this.GetClosestColor(numPtr[2], numPtr[1], numPtr[0]);
                    if (flag)
                    {
                        numPtr3[0] = num10;
                        numPtr3++;
                    }
                    else if ((num9 % 2) == 0)
                    {
                        numPtr3[0] = (byte)(numPtr3[0] | ((byte)(num10 << 4)));
                    }
                    else
                    {
                        numPtr3[0] = (byte)(numPtr3[0] | num10);
                        numPtr3++;
                    }
                    num9++;
                    numPtr += num4;
                }
                numPtr += num5;
            }
            bitmap.UnlockBits(bitmapdata);
            return(bitmap);
        }
コード例 #25
0
        //点、线、面填充颜色变化响应事件
        private void cbColor_MouseUp(object sender, MouseEventArgs e)
        {
            IRgbColor pColor = new RgbColor();    //颜色实例
            pColor.RGB = 255;
            tagRECT pTag = new tagRECT();    //用于下面显示 ColorPalette 的位置
            pTag.left = cbColor.PointToScreen(System.Drawing.Point.Empty).X;            //按钮控件的左边全局横坐标
            pTag.bottom = cbColor.PointToScreen(System.Drawing.Point.Empty).Y + cbColor.Height;  //按钮控件的下边全局纵坐标
            IColorPalette pColorPalette = new ColorPalette();
            pColorPalette.TrackPopupMenu(ref pTag, pColor, false, 0);     //显示 ColorPalette
            pColor = pColorPalette.Color as IRgbColor;          //获取选中的颜色
            Color color = Color.FromArgb(pColor.Red, pColor.Green, pColor.Blue);  //将颜色转为 C# 颜色
            btColor.BackColor = color;
            cbColor.BackColor = color;

            switch (((IFeatureLayer)pLayer).FeatureClass.ShapeType)  //判断几何体样式
            {
                case esriGeometryType.esriGeometryPoint:          //点
                    ((IMarkerSymbol)pStyleGalleryItem.Item).Color = pColor;  //转为 IMarkerSymbol,注意改好后要在图片上显示
                    PreviewPicture();
                    break;
                case esriGeometryType.esriGeometryPolyline:        //线
                    ((ILineSymbol)pStyleGalleryItem.Item).Color = pColor;  //转为 ILineSymbol
                    PreviewPicture();
                    break;
                case esriGeometryType.esriGeometryPolygon:      //面
                    ((IFillSymbol)pStyleGalleryItem.Item).Color = pColor;  //转为 IFillSymbol
                    PreviewPicture();
                    break;
                default:
                    break;
            }
        }
コード例 #26
0
        public Bitmap GetFrame()
        {
            int nRet;

            bmp = null;
            MyCamera.MVCC_INTVALUE stParam = new MyCamera.MVCC_INTVALUE();
            nRet = pCamera.MV_CC_GetIntValue_NET("PayloadSize", ref stParam);
            if (MyCamera.MV_OK != nRet)
            {
                return(null);
            }
            nPayloadSize = stParam.nCurValue;
            if (nPayloadSize > m_nBufSizeForDriver)
            {
                m_nBufSizeForDriver = nPayloadSize;
                m_pBufForDriver     = new byte[m_nBufSizeForDriver];

                // Determine the buffer size to save image
                // BMP image size: width * height * 3 + 2048 (Reserved for BMP header)
                m_nBufSizeForSaveImage = m_nBufSizeForDriver * 3 + 2048;
                m_pBufForSaveImage     = new byte[m_nBufSizeForSaveImage];
            }

            IntPtr pData = Marshal.UnsafeAddrOfPinnedArrayElement(m_pBufForDriver, 0);

            MyCamera.MV_FRAME_OUT_INFO_EX stFrameInfo = new MyCamera.MV_FRAME_OUT_INFO_EX();
            //Get one frame timeout, timeout is 1 sec
            nRet = pCamera.MV_CC_GetOneFrameTimeout_NET(pData, m_nBufSizeForDriver, ref stFrameInfo, 1000);
            if (MyCamera.MV_OK != nRet)
            {
                return(null);
            }

            MyCamera.MvGvspPixelType enDstPixelType;
            if (IsMonoData(stFrameInfo.enPixelType))
            {
                enDstPixelType = MyCamera.MvGvspPixelType.PixelType_Gvsp_Mono8;
            }
            else if (IsColorData(stFrameInfo.enPixelType))
            {
                enDstPixelType = MyCamera.MvGvspPixelType.PixelType_Gvsp_RGB8_Packed;
            }
            else
            {
                return(null);
            }

            IntPtr pImage = Marshal.UnsafeAddrOfPinnedArrayElement(m_pBufForSaveImage, 0);

            MyCamera.MV_PIXEL_CONVERT_PARAM stConverPixelParam = new MyCamera.MV_PIXEL_CONVERT_PARAM();
            stConverPixelParam.nWidth         = stFrameInfo.nWidth;
            stConverPixelParam.nHeight        = stFrameInfo.nHeight;
            stConverPixelParam.pSrcData       = pData;
            stConverPixelParam.nSrcDataLen    = stFrameInfo.nFrameLen;
            stConverPixelParam.enSrcPixelType = stFrameInfo.enPixelType;
            stConverPixelParam.enDstPixelType = enDstPixelType;
            stConverPixelParam.pDstBuffer     = pImage;
            stConverPixelParam.nDstBufferSize = m_nBufSizeForSaveImage;
            nRet = pCamera.MV_CC_ConvertPixelType_NET(ref stConverPixelParam);
            if (MyCamera.MV_OK != nRet)
            {
                return(null);
            }

            if (enDstPixelType == MyCamera.MvGvspPixelType.PixelType_Gvsp_Mono8)
            {
                //************************Mono8 转 Bitmap*******************************
                bmp = new Bitmap(stFrameInfo.nWidth, stFrameInfo.nHeight, stFrameInfo.nWidth * 1, PixelFormat.Format8bppIndexed, pImage);

                ColorPalette cp = bmp.Palette;
                // init palette
                for (int i = 0; i < 256; i++)
                {
                    cp.Entries[i] = Color.FromArgb(i, i, i);
                }
                // set palette back
                bmp.Palette = cp;
            }
            else
            {
                //*********************RGB8 转 Bitmap**************************
                for (int i = 0; i < stFrameInfo.nHeight; i++)
                {
                    for (int j = 0; j < stFrameInfo.nWidth; j++)
                    {
                        byte chRed = m_pBufForSaveImage[i * stFrameInfo.nWidth * 3 + j * 3];
                        m_pBufForSaveImage[i * stFrameInfo.nWidth * 3 + j * 3]     = m_pBufForSaveImage[i * stFrameInfo.nWidth * 3 + j * 3 + 2];
                        m_pBufForSaveImage[i * stFrameInfo.nWidth * 3 + j * 3 + 2] = chRed;
                    }
                }
                try
                {
                    bmp = new Bitmap(stFrameInfo.nWidth, stFrameInfo.nHeight, stFrameInfo.nWidth * 3, PixelFormat.Format24bppRgb, pImage);
                }
                catch
                {
                }
            }
            return(bmp);
        }
コード例 #27
0
ファイル: ColorCellEditor.cs プロジェクト: zhuangyy/Motion
            /// <summary>
            /// Initializes a new instance of the ColorPicker class with default settings
            /// </summary>
            public ColorPicker(ColorCellEditor editor)
            {
                if (editor == null)
                {
                    throw new ArgumentNullException("editor", "editor cannot be null");
                }

                this.editor = editor;

                this.webHeightSet = false;
                this.systemHeightSet = false;

                this.tabControl = new TabControl();
                this.customTabPage = new ThemedTabPage();
                this.palette = new ColorPalette(editor);
                this.webTabPage = new ThemedTabPage();
                this.webListBox = new ColorListBox();
                this.systemTabPage = new ThemedTabPage();
                this.systemListBox = new ColorListBox();
                this.tabControl.SuspendLayout();
                this.SuspendLayout();
                //
                // tabControl1
                //
                this.tabControl.Controls.Add(this.customTabPage);
                this.tabControl.Controls.Add(this.webTabPage);
                this.tabControl.Controls.Add(this.systemTabPage);
                this.tabControl.Location = new System.Drawing.Point(0, 0);
                this.tabControl.Name = "tabControl";
                this.tabControl.SelectedIndex = 0;
                this.tabControl.Size = new Size(this.DefaultSize.Width - 2, this.DefaultSize.Height - 2);
                this.tabControl.TabIndex = 0;
                this.tabControl.TabStop = false;
                this.tabControl.GotFocus += new EventHandler(tabControl_GotFocus);
                //
                // customTabPage
                //
                this.customTabPage.Location = new System.Drawing.Point(4, 22);
                this.customTabPage.Name = "customTabPage";
                this.customTabPage.Size = new System.Drawing.Size(192, 214);
                this.customTabPage.TabIndex = 0;
                this.customTabPage.Text = "Custom";
                this.customTabPage.Controls.Add(this.palette);
                //
                // palette
                //
                this.palette.Dock = DockStyle.Fill;
                this.palette.Picked += new EventHandler(this.OnPalettePick);
                this.palette.KeyPress += new KeyPressEventHandler(this.editor.OnKeyPress);
                //
                // webTabPage
                //
                this.webTabPage.Location = new System.Drawing.Point(4, 22);
                this.webTabPage.Name = "webTabPage";
                this.webTabPage.Size = new System.Drawing.Size(192, 214);
                this.webTabPage.TabIndex = 1;
                this.webTabPage.Text = "Web";
                this.webTabPage.Controls.Add(this.webListBox);
                //
                // webListBox
                //
                this.webListBox.DrawMode = DrawMode.OwnerDrawFixed;
                this.webListBox.BorderStyle = BorderStyle.FixedSingle;
                this.webListBox.IntegralHeight = false;
                this.webListBox.Sorted = false;
                this.webListBox.Dock = DockStyle.Fill;
                this.webListBox.Click += new EventHandler(OnListClick);
                this.webListBox.DrawItem += new DrawItemEventHandler(OnListDrawItem);
                this.webListBox.KeyDown += new KeyEventHandler(OnListKeyDown);
                this.webListBox.KeyPress += new KeyPressEventHandler(this.editor.OnKeyPress);
                //
                // systemTabPage
                //
                this.systemTabPage.Location = new System.Drawing.Point(4, 22);
                this.systemTabPage.Name = "systemTabPage";
                this.systemTabPage.Size = new System.Drawing.Size(192, 214);
                this.systemTabPage.TabIndex = 2;
                this.systemTabPage.Text = "System";
                this.systemTabPage.Controls.Add(this.systemListBox);
                //
                // systemListBox
                //
                this.systemListBox.DrawMode = DrawMode.OwnerDrawFixed;
                this.systemListBox.BorderStyle = BorderStyle.FixedSingle;
                this.systemListBox.IntegralHeight = false;
                this.systemListBox.Sorted = false;
                this.systemListBox.Dock = DockStyle.Fill;
                this.systemListBox.Click += new EventHandler(OnListClick);
                this.systemListBox.DrawItem += new DrawItemEventHandler(OnListDrawItem);
                this.systemListBox.KeyDown += new KeyEventHandler(OnListKeyDown);
                this.systemListBox.FontChanged += new EventHandler(OnFontChanged);
                this.systemListBox.KeyPress += new KeyPressEventHandler(this.editor.OnKeyPress);

                // for some reason Array.Sort craps out with the WebColorComparer,
                // so the WebColors property returns an array that is already sorted
                //Array.Sort(this.WebColors, new ColorCellEditor.ColorPicker.WebColorComparer());
                for (int i=0; i<this.WebColors.Length; i++)
                {
                    this.webListBox.Items.Add(this.WebColors[i]);
                }

                Array.Sort(this.SystemColors, new ColorCellEditor.ColorPicker.SystemColorComparer());
                for (int i=0; i<this.SystemColors.Length; i++)
                {
                    this.systemListBox.Items.Add(this.SystemColors[i]);
                }

                //
                // ColorPicker
                //
                this.Controls.Add(this.tabControl);
                this.Name = "ColorPicker";
                this.Size = this.DefaultSize;
                this.tabControl.ResumeLayout(false);
                this.ResumeLayout(false);

                this.AdjustListBoxItemHeight();
            }
コード例 #28
0
ファイル: gfx.cs プロジェクト: MGRich/RSDK-Reverse
        public gfx(Reader reader)
        {
            width  = reader.ReadByte() << 8;
            width |= reader.ReadByte();

            height  = reader.ReadByte() << 8;
            height |= reader.ReadByte();

            // Create image

            GFXpal = new gfxPalette();

            gfxImage = new Bitmap(width, height, PixelFormat.Format8bppIndexed);

            ColorPalette cp = gfxImage.Palette;

            // Read & Process palette, ISSUE HERE
            for (int i = 0; i < 255; i++)
            {
                GFXpal.r[i]   = reader.ReadByte();
                GFXpal.g[i]   = reader.ReadByte();
                GFXpal.b[i]   = reader.ReadByte();
                cp.Entries[i] = Color.FromArgb(255, GFXpal.r[i], GFXpal.g[i], GFXpal.b[i]);
            }
            gfxImage.Palette = cp;

            //Read Image Data
            int[] buf      = new int[3];
            bool  finished = false;
            int   cnt      = 0;
            int   loop     = 0;

            data = new int[width * height];

            while (!reader.IsEof)
            {
                buf[0] = reader.ReadByte();

                if (buf[0] != 0xFF && !reader.IsEof)
                {
                    data[cnt++] = buf[0];
                }

                else
                {
                    buf[1] = reader.ReadByte();

                    if (buf[1] != 0xFF && !reader.IsEof)
                    {
                        buf[2] = reader.ReadByte();
                        loop   = 0;

                        // Repeat value needs to decreased by one to decode

                        while (loop < buf[2] && !reader.IsEof)
                        {
                            data[cnt++] = buf[1];
                            loop++;
                        }
                    }
                    else
                    {
                        finished = true;
                    }
                }
            }

            // Write data to image
            int pixel = 0;

            for (int h = 0; h < height; h++)
            {
                for (int w = 0; w < width; w++)
                {
                    BitmapData ImgData = gfxImage.LockBits(new Rectangle(new Point(w, h), new Size(1, 1)), System.Drawing.Imaging.ImageLockMode.ReadWrite, System.Drawing.Imaging.PixelFormat.Format8bppIndexed);
                    byte       b       = System.Runtime.InteropServices.Marshal.ReadByte(ImgData.Scan0);
                    System.Runtime.InteropServices.Marshal.WriteByte(ImgData.Scan0, (byte)(data[pixel]));
                    gfxImage.UnlockBits(ImgData);
                    pixel++;
                }
            }
            reader.Close();
        }
コード例 #29
0
ファイル: Quantizer.cs プロジェクト: sami1971/Eto
 /// <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);
コード例 #30
0
 private void TextBoxTextChanged(object sender, TextChangedEventArgs e)
 {
     (sender as TextBox).BorderBrush = ColorPalette.GetPredefinedColor(PredefinedColors.DarkGrey);
 }
コード例 #31
0
        public Bitmap Convert(Bitmap source, PixelFormat target)
        {
            if ((source.PixelFormat == target) || (target == PixelFormat.DontCare))
            {
                return(source);
            }
            Bitmap image = new Bitmap(source.Width, source.Height, target);

            if ((source.PixelFormat == PixelFormat.Format4bppIndexed) && (target == PixelFormat.Format8bppIndexed))
            {
                byte[] array  = GetArray(source);
                byte[] array2 = new byte[(array.Length * 2)];
                byte   current;
                for (int i = 0; i < array.Length; i++)
                {
                    current           = array[i];
                    array2[2 * i]     = (byte)((current & 0xF0) >> 4);
                    array2[2 * i + 1] = (byte)((current & 0x0F));
                }
                image         = MakeImage(source.Width, source.Height, array2, target);
                image.Palette = source.Palette;
            }
            if (((source.PixelFormat == PixelFormat.Format24bppRgb) || (source.PixelFormat == PixelFormat.Format32bppArgb)) && (target == PixelFormat.Format8bppIndexed))
            {
                int skip = 3;
                if (source.PixelFormat == PixelFormat.Format32bppArgb)
                {
                    skip = 4;
                }
                Color[] newPalette  = new Color[256];
                byte[]  array       = new byte[source.Width * source.Height];
                byte[]  sourceArray = GetArray(source);
                Color   Pixel       = Color.FromArgb(sourceArray[2], sourceArray[1], sourceArray[0]);
                newPalette[0] = Pixel;
                int index = 1;
                array[0] = 0;
                byte r     = 0;
                byte g     = 0;
                byte b     = 0;
                bool match = false;
                for (int i = 1; i < (source.Width * source.Height); i++)
                {
                    b     = sourceArray[(i * skip)];
                    g     = sourceArray[(i * skip + 1)];
                    r     = sourceArray[(i * skip + 2)];
                    Pixel = Color.FromArgb(r, g, b);
                    for (int j = 0; j < index; j++)
                    {
                        if (Pixel == newPalette[j])
                        {
                            array[i] = (byte)j;
                            match    = true;
                            break;
                        }
                    }
                    if (!match)
                    {
                        if (index >= 256)
                        {
                            MessageBox.Show("Conversion failed");
                            return(null);
                        }
                        newPalette[index] = Pixel;
                        array[i]          = (byte)index;
                        index++;
                    }
                    match = false;
                }
                image = MakeImage(source.Width, source.Height, array, target);
                ColorPalette oldPalette = image.Palette;
                for (int i = 0; i < index; i++)
                {
                    oldPalette.Entries[i] = newPalette[i];
                }
                image.Palette = oldPalette;
            }
            return(image);
        }
コード例 #32
0
 protected ColorGrid(ColorCollection colors, ColorCollection customColors, ColorPalette palette)
 {
   _cellBackground = new Bitmap(this.GetType().Assembly.GetManifestResourceStream(string.Concat(this.GetType().Namespace, ".Resources.cellbackground.png")));
   _cellBackgroundBrush = new TextureBrush(_cellBackground, WrapMode.Tile);
   this.SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | ControlStyles.OptimizedDoubleBuffer | ControlStyles.Selectable | ControlStyles.StandardClick | ControlStyles.StandardDoubleClick | ControlStyles.SupportsTransparentBackColor, true);
   this.HotIndex = InvalidIndex;
   this.ColorRegions = new Dictionary<int, Rectangle>();
   if (this.Palette != ColorPalette.None)
     this.Colors = colors;
   else
     this.Palette = palette;
   this.CustomColors = customColors;
   this.ShowCustomColors = true;
   this.CellSize = new Size(12, 12);
   this.Spacing = new Size(3, 3);
   this.Columns = 16;
   this.AutoSize = true;
   this.Padding = new Padding(5);
   this.AutoAddColors = true;
   this.CellBorderColor = SystemColors.ButtonShadow;
   this.ShowToolTips = true;
   this.SeparatorHeight = 8;
   this.EditMode = ColorEditingMode.CustomOnly;
   this.Color = Color.Black;
   this.CellBorderStyle = ColorCellBorderStyle.FixedSingle;
   this.SelectedCellStyle = ColorGridSelectedCellStyle.Zoomed;
 }
コード例 #33
0
        /// <summary>
        /// 获取灰度值位图(内存处理方法)
        /// </summary>
        /// <param name="bitmap">转换位图</param>
        /// <param name="mode">处理模式</param>
        /// <returns>处理结果位图</returns>
        public static Bitmap GrayscaleBitmap(Bitmap bitmap, GrayMode mode = GrayMode.Perceived)
        {
            if (bitmap == null)
            {
                return(null);
            }
            Bitmap    srcBitmap = (Bitmap)bitmap.Clone();
            int       width = srcBitmap.Width, height = srcBitmap.Height;
            Rectangle rect = new Rectangle(0, 0, width, height);
            //将Bitmap锁定到系统内存中,获得BitmapData
            BitmapData srcBmData = srcBitmap.LockBits(rect, ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);

            //创建Bitmap
            Bitmap     dstBitmap = new Bitmap(width, height, PixelFormat.Format8bppIndexed);
            BitmapData dstBmData = dstBitmap.LockBits(rect, ImageLockMode.ReadWrite, PixelFormat.Format8bppIndexed);
            // get palette
            ColorPalette cp = dstBitmap.Palette;

            // init palette
            for (int i = 0; i < 256; i++)
            {
                cp.Entries[i] = Color.FromArgb(i, i, i);
            }
            dstBitmap.Palette = cp;

            //位图中第一个像素数据的地址。它也可以看成是位图中的第一个扫描行
            IntPtr srcPtr = srcBmData.Scan0, dstPtr = dstBmData.Scan0;

            //将Bitmap对象的信息存放到byte数组中
            int src_bytes = srcBmData.Stride * height, dst_bytes = dstBmData.Stride * height;

            byte[] srcValues = new byte[src_bytes], dstValues = new byte[dst_bytes];

            //复制GRB信息到byte数组
            Marshal.Copy(srcPtr, srcValues, 0, src_bytes);
            Marshal.Copy(dstPtr, dstValues, 0, dst_bytes);

            //根据Y=0.299*R+0.114*G+0.587B,Y为亮度
            for (int i = 0; i < height; i++)
            {
                for (int j = 0; j < width; j++)
                {
                    //只处理每行中图像像素数据,舍弃未用空间
                    //注意位图结构中RGB按BGR的顺序存储
                    int  k = 3 * j;
                    byte r = srcValues[i * srcBmData.Stride + k + 2];
                    byte g = srcValues[i * srcBmData.Stride + k + 1];
                    byte b = srcValues[i * srcBmData.Stride + k];

                    // 灰度值提取
                    byte temp = 0;
                    switch (mode)
                    {
                    case GrayMode.AverageMethod:
                        temp = (byte)((r + g + b) / 3);
                        break;

                    case GrayMode.Perceived:
                        temp = (byte)(r * 0.299 + g * 0.587 + b * 0.114);
                        break;

                    case GrayMode.TakeGreen:
                        temp = g;
                        break;
                    }


                    dstValues[i * dstBmData.Stride + j] = temp;
                }
            }

            Marshal.Copy(dstValues, 0, dstPtr, dst_bytes);

            //解锁位图
            srcBitmap.UnlockBits(srcBmData);
            dstBitmap.UnlockBits(dstBmData);

            return(dstBitmap);
        }
コード例 #34
0
ファイル: IconManager.cs プロジェクト: ewrogers/SleepHunter4
        public void ReloadIcons()
        {
            var settings = UserSettingsManager.Instance.Settings;

              skillIconPalette = GetColorPalette(settings.IconDataFile, settings.SkillPaletteFile);
              spellIconPalette = GetColorPalette(settings.IconDataFile, settings.SpellPaletteFile);

              skillIconImage = GetEpfImage(settings.IconDataFile, settings.SkillIconFile);
              spellIconImage = GetEpfImage(settings.IconDataFile, settings.SpellIconFile);
        }
コード例 #35
0
        public static Bitmap ToBitmap(string filePath)
        {
            using (FileStream fs = new FileStream(filePath, FileMode.Open))
            {
                using (BinaryReader reader = new BinaryReader(fs, Encoding.ASCII))
                {
                    if (reader.ReadChar() == 'P' && reader.ReadChar() == '5')
                    {
                        reader.ReadChar();
                        //reader.ReadBytes(24);
                        int           width  = 0;
                        int           height = 0;
                        int           level  = 0;
                        bool          two    = false;
                        StringBuilder sb     = new StringBuilder();
                        width  = ReadNumber(reader, sb);
                        height = ReadNumber(reader, sb);
                        level  = ReadNumber(reader, sb);
                        two    = (level > 255);

                        Bitmap bmp = new Bitmap(width, height, PixelFormat.Format8bppIndexed);
                        if (grayScale == null)
                        {
                            grayScale = bmp.Palette;
                            for (int i = 0; i < 256; i++)
                            {
                                grayScale.Entries[i] = Color.FromArgb(i, i, i);
                            }
                        }
                        bmp.Palette = grayScale;
                        BitmapData dt     = bmp.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.WriteOnly, PixelFormat.Format8bppIndexed);
                        int        offset = dt.Stride - dt.Width;
                        unsafe
                        {
                            byte *ptr = (byte *)dt.Scan0;

                            for (int i = 0; i < height; i++)
                            {
                                for (int j = 0; j < width; j++)
                                {
                                    byte v;
                                    if (two)
                                    {
                                        v = (byte)(((double)((reader.ReadByte() << 8) + reader.ReadByte()) / level) * 255.0);
                                    }
                                    else
                                    {
                                        v = reader.ReadByte();
                                    }
                                    *ptr = v;
                                    ptr++;
                                }
                                ptr += offset;
                            }
                        }

                        bmp.UnlockBits(dt);
                        return(bmp);
                    }
                    else
                    {
                        throw new InvalidOperationException("target file is not a PGM file");
                    }
                }
            }
        }
コード例 #36
0
	public void GetAdjustedPalette(ColorPalette palette, ColorAdjustType type) {}
コード例 #37
0
        public override bool SaveImageData(String filename, IImageByte sourceImage)
        {
            if (File.Exists(filename))
            {
                File.Delete(filename);
            }

            ImageFormat format = ImageFormat.Jpeg;

            if (filename.ToLower().EndsWith(".png"))
            {
                format = ImageFormat.Png;
            }
            else if (!filename.ToLower().EndsWith(".jpg") && !filename.ToLower().EndsWith(".jpeg"))
            {
                filename += ".jpg";
            }

            if (!System.IO.File.Exists(filename))
            {
                if (sourceImage.BitDepth == 32)
                {
                    Bitmap     bitmapToSave = new Bitmap(sourceImage.Width, sourceImage.Height, PixelFormat.Format32bppArgb);
                    BitmapData bitmapData   = bitmapToSave.LockBits(new Rectangle(0, 0, bitmapToSave.Width, bitmapToSave.Height), System.Drawing.Imaging.ImageLockMode.ReadWrite, bitmapToSave.PixelFormat);
                    int        destIndex    = 0;
                    unsafe
                    {
                        byte[] sourceBuffer    = sourceImage.GetBuffer();
                        byte * pDestBuffer     = (byte *)bitmapData.Scan0;
                        int    scanlinePadding = bitmapData.Stride - bitmapData.Width * 4;
                        for (int y = 0; y < sourceImage.Height; y++)
                        {
                            int sourceIndex = sourceImage.GetBufferOffsetXY(0, sourceImage.Height - 1 - y);
                            for (int x = 0; x < sourceImage.Width; x++)
                            {
                                pDestBuffer[destIndex++] = sourceBuffer[sourceIndex++];
                                pDestBuffer[destIndex++] = sourceBuffer[sourceIndex++];
                                pDestBuffer[destIndex++] = sourceBuffer[sourceIndex++];
                                pDestBuffer[destIndex++] = sourceBuffer[sourceIndex++];
                            }
                            destIndex += scanlinePadding;
                        }
                    }
                    bitmapToSave.Save(filename, format);
                    bitmapToSave.UnlockBits(bitmapData);
                    return(true);
                }
                else if (sourceImage.BitDepth == 8 && format == ImageFormat.Png)
                {
                    Bitmap       bitmapToSave = new Bitmap(sourceImage.Width, sourceImage.Height, PixelFormat.Format8bppIndexed);
                    ColorPalette palette      = bitmapToSave.Palette;
                    for (int i = 0; i < palette.Entries.Length; i++)
                    {
                        palette.Entries[i] = Color.FromArgb(i, i, i);
                    }
                    bitmapToSave.Palette = palette;
                    BitmapData bitmapData = bitmapToSave.LockBits(new Rectangle(0, 0, bitmapToSave.Width, bitmapToSave.Height), System.Drawing.Imaging.ImageLockMode.ReadWrite, bitmapToSave.PixelFormat);
                    int        destIndex  = 0;
                    unsafe
                    {
                        byte[] sourceBuffer = sourceImage.GetBuffer();
                        byte * pDestBuffer  = (byte *)bitmapData.Scan0;
                        for (int y = 0; y < sourceImage.Height; y++)
                        {
                            int sourceIndex = sourceImage.GetBufferOffsetXY(0, sourceImage.Height - 1 - y);
                            for (int x = 0; x < sourceImage.Width; x++)
                            {
                                pDestBuffer[destIndex++] = sourceBuffer[sourceIndex++];
                            }
                        }
                    }
                    bitmapToSave.Save(filename, format);
                    bitmapToSave.UnlockBits(bitmapData);
                    return(true);
                }
                else
                {
                    throw new System.NotImplementedException();
                }
            }

            return(false);
        }
コード例 #38
0
        public static ColorCollection GetPalette(ColorPalette palette)
        {
            ColorCollection result;

              switch (palette)
              {
            case ColorPalette.Recent:
              string sRecentFile = Assembly.GetExecutingAssembly().Location + ".recent";
              if (File.Exists(sRecentFile))
              {
            result = new ColorCollection();
            result.Load(sRecentFile);
            break;
              }else
              {
            result = NamedColors;
            break;
              }
            case ColorPalette.Named:
              result = NamedColors;
              break;
            case ColorPalette.Office2010:
              result = Office2010Standard;
              break;
            case ColorPalette.Paint:
              result = PaintPalette;
              break;
            case ColorPalette.Standard:
              result = QbColors;
              break;
            case ColorPalette.None:
              result = new ColorCollection();
              break;
            case ColorPalette.WebSafe:
              result = WebSafe;
              break;
            case ColorPalette.Standard256:
              result = StandardPalette;
              break;
            default:
              throw new ArgumentException("Invalid palette", "palette");
              }

              return result;
        }
コード例 #39
0
 public void Add_Click(object sender, RoutedEventArgs e)
 {
     if (!IsWrongTextBoxValue())
     {
         var OwnerWindowInstance = this.Owner as AudiencesWindow;
         var audience            = new SchoolAudience(NameTextBox.Text, AudienceTypeTextBox.Text, int.Parse(CapacityTextBox.Text));
         OwnerWindowInstance.SchoolAudienceDict.dictionaryList.Add(audience);
         OwnerWindowInstance.AudiencesList.Items.Add(audience);
         ((Owner as AudiencesWindow).Owner as EditorWindow).HomePage.AudiencesIndicator.Fill = ColorPalette.GetPredefinedColor(PredefinedColors.Green);
         ElementsModification.ResetControlText <TextBox>(this);
     }
 }
コード例 #40
0
ファイル: SandJar.cs プロジェクト: xipeluife/GGJ2016
	public void Initialize(ColorPalette palette)
	{
		jar = SandJar.CreateTargetSandJar(palette);
		CreateTargetSandJarGameObject(jar, targetSandJarParent.transform);
	}
コード例 #41
0
        public static ColorMapping Parse(JsonObject data, IColorPaletteEntry lightRegion, IColorPaletteEntry darkRegion, ColorPalette lightBase, ColorPalette darkBase, ColorPalette lightPrimary, ColorPalette darkPrimary, IColorPaletteEntry white, IColorPaletteEntry black)
        {
            var target = data["Target"].GetEnum <ColorTarget>();
            var source = data["Source"].GetEnum <ColorSource>();
            int index  = 0;

            if (data.ContainsKey("SourceIndex"))
            {
                index = data["SourceIndex"].GetInt();
            }

            switch (source)
            {
            case ColorSource.LightRegion:
                return(new ColorMapping(lightRegion, target));

            case ColorSource.DarkRegion:
                return(new ColorMapping(darkRegion, target));

            case ColorSource.LightBase:
                return(new ColorMapping(lightBase.Palette[index], target));

            case ColorSource.DarkBase:
                return(new ColorMapping(darkBase.Palette[index], target));

            case ColorSource.LightPrimary:
                return(new ColorMapping(lightPrimary.Palette[index], target));

            case ColorSource.DarkPrimary:
                return(new ColorMapping(darkPrimary.Palette[index], target));

            case ColorSource.White:
                return(new ColorMapping(white, target));

            case ColorSource.Black:
                return(new ColorMapping(black, target));
            }

            return(null);
        }
コード例 #42
0
        public static List <ColorMapping> ParseList(JsonArray data, IColorPaletteEntry lightRegion, IColorPaletteEntry darkRegion, ColorPalette lightBase, ColorPalette darkBase, ColorPalette lightPrimary, ColorPalette darkPrimary, IColorPaletteEntry white, IColorPaletteEntry black)
        {
            List <ColorMapping> retVal = new List <ColorMapping>();

            foreach (var node in data)
            {
                retVal.Add(ColorMapping.Parse(node.GetObject(), lightRegion, darkRegion, lightBase, darkBase, lightPrimary, darkPrimary, white, black));
            }
            return(retVal);
        }
コード例 #43
0
ファイル: IconManager.cs プロジェクト: ewrogers/SleepHunter4
        RenderedBitmap RenderSpellIcon(int index)
        {
            var settings = UserSettingsManager.Instance.Settings;

              if (spellIconPalette == null)
            spellIconPalette = GetColorPalette(settings.IconDataFile, settings.SpellPaletteFile);

              if (spellIconImage == null)
            spellIconImage = GetEpfImage(settings.IconDataFile, settings.SpellIconFile);

              if (spellIconPalette == null || spellIconImage == null)
            return null;

              if (index >= spellIconImage.FrameCount)
            return null;

              var frame = spellIconImage.GetFrameAt(index);
              var bitmap = RenderManager.Instance.Render(frame, spellIconPalette);

              return bitmap;
        }
コード例 #44
0
        public Bitmap ConverTo8BitsPerPixel()
        {
            Bitmap       newBitmap = new Bitmap(Width, Height, PixelFormat.Format8bppIndexed);
            List <Color> palette   = new List <Color>();

            palette.Add(Color.Transparent);
            ColorPalette bPalette = newBitmap.Palette;
            var          entries  = bPalette.Entries;

            for (int i = 0; i < newBitmap.Palette.Entries.Length; i++)
            {
                entries[i] = Color.Transparent;
            }

            BitmapData data = newBitmap.LockBits(new Rectangle(0, 0, Width, Height), ImageLockMode.WriteOnly, PixelFormat.Format8bppIndexed);

            byte[] bytes = new byte[data.Height * data.Stride];
            Marshal.Copy(data.Scan0, bytes, 0, bytes.Length);

            for (int y = 0; y < Height; y++)
            {
                for (int x = 0; x < Width; x++)
                {
                    Color c = GetPixel(x, y);
                    if (c.A < 5)
                    {
                        bytes[y * data.Stride + x] = 0;
                    }
                    else
                    {
                        int maxDiff;
                        int index = FindBestMatch(c, palette, out maxDiff);

                        if (index == -1 && palette.Count < 255)
                        {
                            index          = palette.Count;
                            entries[index] = c;
                            palette.Add(c);
                            bytes[y * data.Stride + x] = (byte)index;
                        }
                        else if (palette.Count < 200 && maxDiff > 5)
                        {
                            index          = palette.Count;
                            entries[index] = c;
                            palette.Add(c);
                            bytes[y * data.Stride + x] = (byte)index;
                        }
                        else if (palette.Count < 255 && maxDiff > 15)
                        {
                            index          = palette.Count;
                            entries[index] = c;
                            palette.Add(c);
                            bytes[y * data.Stride + x] = (byte)index;
                        }
                        else if (index >= 0)
                        {
                            bytes[y * data.Stride + x] = (byte)index;
                        }
                    }
                }
            }
            Marshal.Copy(bytes, 0, data.Scan0, bytes.Length);
            newBitmap.UnlockBits(data);
            newBitmap.Palette = bPalette;
            return(newBitmap);
        }
	// Constructors
	public ColorPaletteAccessibleObject(ColorPalette owner) {}
コード例 #46
0
        private void InitCamera()
        {
            CameraSdkStatus status    = CameraSdkStatus.CAMERA_STATUS_USER_CANCEL;
            CameraSdkStatus _status_1 = CameraSdkStatus.CAMERA_STATUS_USER_CANCEL;
            CameraSdkStatus _status_2 = CameraSdkStatus.CAMERA_STATUS_USER_CANCEL;

            tSdkCameraDevInfo[] DevList;
            MvApi.CameraEnumerateDevice(out DevList);
            int NumDev = (DevList != null ? DevList.Length : 0);

            if (NumDev < 1)
            {
                MessageBox.Show("未扫描到相机");
                return;
            }
            else if (NumDev == 1)
            {
                _status_1 = MvApi.CameraGrabber_Create(out m_Grabber_1, ref DevList[0]);
            }
            else if (NumDev == 2)
            {
                _status_1 = MvApi.CameraGrabber_Create(out m_Grabber_1, ref DevList[0]);
                _status_2 = MvApi.CameraGrabber_Create(out m_Grabber_2, ref DevList[1]);
            }
            else //选择哪个相机
            {
                status = MvApi.CameraGrabber_CreateFromDevicePage(out m_Grabber_1);
            }

            if (_status_1 == 0)
            {
                //获得相机的描述信息
                MvApi.CameraGrabber_GetCameraDevInfo(m_Grabber_1, out m_DevInfo_1);
                //获得相机的句柄
                MvApi.CameraGrabber_GetCameraHandle(m_Grabber_1, out m_hCamera_1);
                //sheshe设置相机配置窗口的启动页面
                MvApi.CameraCreateSettingPage(m_hCamera_1, this.Handle, m_DevInfo_1.acFriendlyName, null, (IntPtr)0, 0);
                //设置RGB回调函数
                MvApi.CameraGrabber_SetRGBCallback(m_Grabber_1, m_FrameCallback_1, IntPtr.Zero);
                tSdkCameraCapbility cap_1;
                //黑白相机设置ISP输出灰度图像
                //彩色相机ISP默认输出BGR24图像

                //获得相机特性
                MvApi.CameraGetCapability(m_hCamera_1, out cap_1);
                //表示该型号相机是否为黑白相机,如果是黑白相机,则颜色相关的功能都无法调节
                if (cap_1.sIspCapacity.bMonoSensor != 0)
                {
                    MvApi.CameraSetIspOutFormat(m_hCamera_1, (uint)MVSDK.emImageFormat.CAMERA_MEDIA_TYPE_MONO8);
                    //创建灰度调色板
                    Bitmap Image = new Bitmap(1, 1, PixelFormat.Format8bppIndexed);
                    m_GrayPal_1 = Image.Palette;
                    for (int Y = 0; Y < m_GrayPal_1.Entries.Length; Y++)
                    {
                        m_GrayPal_1.Entries[Y] = Color.FromArgb(255, Y, Y, Y);
                    }
                }
                //设置vflip,由于sdk输出的数据默认是从底部到顶部,打开flip后就可以直接转成bitmap
                MvApi.CameraSetMirror(m_hCamera_1, 1, 1);
                // MvApi.CameraGrabber_StartLive(m_Grabber);
                label_Camera1Status.Text = "相机1:初始化成功";
            }
            else
            {
                MessageBox.Show(String.Format("打开相机失败,原因:{0}", _status_1));
            }
            if (_status_2 == 0)
            {
                //获得相机的描述信息
                MvApi.CameraGrabber_GetCameraDevInfo(m_Grabber_2, out m_DevInfo_2);
                //获得相机的句柄
                MvApi.CameraGrabber_GetCameraHandle(m_Grabber_2, out m_hCamera_2);
                //sheshe设置相机配置窗口的启动页面
                MvApi.CameraCreateSettingPage(m_hCamera_2, this.Handle, m_DevInfo_2.acFriendlyName, null, (IntPtr)0, 0);
                //设置RGB回调函数
                MvApi.CameraGrabber_SetRGBCallback(m_Grabber_2, m_FrameCallback_2, IntPtr.Zero);
                tSdkCameraCapbility cap_2;
                //黑白相机设置ISP输出灰度图像
                //彩色相机ISP默认输出BGR24图像

                //获得相机特性
                MvApi.CameraGetCapability(m_hCamera_2, out cap_2);
                //表示该型号相机是否为黑白相机,如果是黑白相机,则颜色相关的功能都无法调节
                if (cap_2.sIspCapacity.bMonoSensor != 0)
                {
                    MvApi.CameraSetIspOutFormat(m_hCamera_2, (uint)MVSDK.emImageFormat.CAMERA_MEDIA_TYPE_MONO8);
                    //创建灰度调色板
                    Bitmap Image = new Bitmap(1, 1, PixelFormat.Format8bppIndexed);
                    m_GrayPal_2 = Image.Palette;
                    for (int Y = 0; Y < m_GrayPal_2.Entries.Length; Y++)
                    {
                        m_GrayPal_2.Entries[Y] = Color.FromArgb(255, Y, Y, Y);
                    }
                }
                //设置vflip,由于sdk输出的数据默认是从底部到顶部,打开flip后就可以直接转成bitmap
                MvApi.CameraSetMirror(m_hCamera_2, 1, 1);
                // MvApi.CameraGrabber_StartLive(m_Grabber);
                label_Camera2Status.Text = "相机2:初始化成功";
            }
            else
            {
                MessageBox.Show(String.Format("打开相机失败,原因:{0}", _status_2));
            }
        }
コード例 #47
0
ファイル: ColorPalette.cs プロジェクト: hj1980/Mosa
        /// <summary>
        /// Gets the Standard 16 color palette.
        /// </summary>
        /// <returns></returns>
        public static ColorPalette CreateStandard16ColorPalette()
        {
            ColorPalette palette = new ColorPalette(16);

            palette.SetColor(0, 0, 0, 0);
            palette.SetColor(1, 0, 0, 170);
            palette.SetColor(2, 0, 170, 0);
            palette.SetColor(3, 0, 170, 170);
            palette.SetColor(4, 170, 0, 0);
            palette.SetColor(5, 170, 0, 170);
            palette.SetColor(6, 170, 85, 0);
            palette.SetColor(7, 170, 170, 170);
            palette.SetColor(8, 85, 85, 85);
            palette.SetColor(9, 85, 85, 255);
            palette.SetColor(10, 85, 255, 85);
            palette.SetColor(11, 85, 255, 255);
            palette.SetColor(12, 255, 85, 85);
            palette.SetColor(13, 255, 85, 255);
            palette.SetColor(14, 255, 255, 85);
            palette.SetColor(15, 255, 255, 255);

            return palette;
        }
コード例 #48
0
        /// <summary>
        /// Converts a frame to displayable image
        /// </summary>
        /// <param name="frame">The frame to be converted</param>
        /// <returns>An .NET Image constructed out of the Vimba frame</returns>
        private static Image ConvertFrame(Frame frame)
        {
            if (null == frame)
            {
                throw new ArgumentNullException("frame");
            }

            //Check if the image is valid
            if (VmbFrameStatusType.VmbFrameStatusComplete != frame.ReceiveStatus)
            {
                throw new Exception("Invalid frame received. Reason: " + frame.ReceiveStatus.ToString());
            }

            //Convert raw frame data into image (for image display)
            Image image = null;

            switch (frame.PixelFormat)
            {
            case VmbPixelFormatType.VmbPixelFormatMono8:
            {
                Bitmap bitmap = new Bitmap((int)frame.Width, (int)frame.Height, PixelFormat.Format8bppIndexed);

                //Set greyscale palette
                ColorPalette palette = bitmap.Palette;
                for (int i = 0; i < palette.Entries.Length; i++)
                {
                    palette.Entries[i] = Color.FromArgb(i, i, i);
                }
                bitmap.Palette = palette;

                //Copy image data
                BitmapData bitmapData = bitmap.LockBits(new Rectangle(0,
                                                                      0,
                                                                      (int)frame.Width,
                                                                      (int)frame.Height),
                                                        ImageLockMode.WriteOnly,
                                                        PixelFormat.Format8bppIndexed);
                try
                {
                    //Copy image data line by line
                    for (int y = 0; y < (int)frame.Height; y++)
                    {
                        System.Runtime.InteropServices.Marshal.Copy(frame.Buffer,
                                                                    y * (int)frame.Width,
                                                                    new IntPtr(bitmapData.Scan0.ToInt64() + y * bitmapData.Stride),
                                                                    (int)frame.Width);
                    }
                }
                finally
                {
                    bitmap.UnlockBits(bitmapData);
                }

                image = bitmap;
            }
            break;

            case VmbPixelFormatType.VmbPixelFormatBgr8:
            {
                Bitmap bitmap = new Bitmap((int)frame.Width, (int)frame.Height, PixelFormat.Format24bppRgb);

                //Copy image data
                BitmapData bitmapData = bitmap.LockBits(new Rectangle(0,
                                                                      0,
                                                                      (int)frame.Width,
                                                                      (int)frame.Height),
                                                        ImageLockMode.WriteOnly,
                                                        PixelFormat.Format24bppRgb);
                try
                {
                    //Copy image data line by line
                    for (int y = 0; y < (int)frame.Height; y++)
                    {
                        System.Runtime.InteropServices.Marshal.Copy(frame.Buffer,
                                                                    y * ((int)frame.Width) * 3,
                                                                    new IntPtr(bitmapData.Scan0.ToInt64() + y * bitmapData.Stride),
                                                                    ((int)(frame.Width) * 3));
                    }
                }
                finally
                {
                    bitmap.UnlockBits(bitmapData);
                }

                image = bitmap;
            }
            break;

            default:
                throw new Exception("Current pixel format is not supported by this example (only Mono8 and BRG8Packed are supported).");
            }

            return(image);
        }
コード例 #49
0
ファイル: ColorPalette.cs プロジェクト: Mrbransky/Kissy_Ghost
 void OnEnable()
 {
     colorPalette = target as ColorPalette;
 }
コード例 #50
0
        /// <summary>
        /// Load and read Sprite file.
        /// </summary>
        /// <param name="inputFile">Input file.</param>
        /// <param name="transparent">Replace blue color with transparent.</param>
        /// <exception cref="HLToolsUnsupportedFile"></exception>
        public Frame[] LoadFile(string inputFile, bool transparent = false)
        {
            Filename = inputFile;

            //Reset previous loaded data
            List <Frame> frames = new List <Frame>();

            Close();

            fs        = new FileStream(inputFile, FileMode.Open, FileAccess.ReadWrite, FileShare.Read);
            binReader = new BinaryReader(fs);

            //First try get header ID
            SprHeader spriteHeader = new SprHeader();

            spriteHeader.Id = binReader.ReadChars(4);

            string magic = new string(spriteHeader.Id);

            if (magic != SpriteHeaderId) //if invalid SPR file
            {
                throw new HLToolsUnsupportedFile("Invalid or unsupported Sprite File!");
            }

            spriteHeader.Version        = binReader.ReadInt32();
            spriteHeader.Type           = (SprType)binReader.ReadInt32();
            spriteHeader.TextFormat     = (SprTextFormat)binReader.ReadInt32();
            spriteHeader.BoundingRadius = binReader.ReadSingle();
            spriteHeader.MaxWidth       = binReader.ReadInt32();
            spriteHeader.MaxHeight      = binReader.ReadInt32();
            spriteHeader.NumFrames      = binReader.ReadInt32();
            spriteHeader.BeamLen        = binReader.ReadSingle();
            spriteHeader.SynchType      = (SprSynchType)binReader.ReadInt32();

            SpriteHeader = spriteHeader;

            //Palette length
            ushort u = binReader.ReadUInt16();

            //Prepare new palette for bitmap
            ColorPalette pal = null;

            using (Bitmap tmpBitmap = new Bitmap(1, 1, PixelFormat.Format8bppIndexed))
            {
                pal = tmpBitmap.Palette;
                byte[] palBytes = binReader.ReadBytes(u * 3);
                for (int i = 0, j = 0; i < u; i++)
                {
                    //Load (R,G,B) from file

                    /*if (transparent && SpriteHeader.TextFormat == SprTextFormat.SPR_ADDITIVE)
                     * {
                     *  //pal.Entries[i] = Color.FromArgb((u - 1) - i, palBytes[j], palBytes[j + 1], palBytes[j + 2]);
                     * }
                     * else
                     * {
                     *  //pal.Entries[i] = Color.FromArgb(palBytes[j], palBytes[j + 1], palBytes[j + 2]);
                     * }*/
                    pal.Entries[i] = Color.FromArgb(palBytes[j], palBytes[j + 1], palBytes[j + 2]);

                    //Check for transparent color
                    if (i == (u - 1)) //256th color is alpha
                    {
                        if (transparent && spriteHeader.TextFormat == SprTextFormat.SPR_ALPHTEST)
                        {
                            pal.Entries[i] = Color.FromArgb(0, pal.Entries[i]);
                        }
                    }

                    j += 3;
                }
            }

            indexesOfPixelPositions = new long[spriteHeader.NumFrames];
            pixelsLengths           = new uint[spriteHeader.NumFrames];


            //Load frames
            for (int i = 0; i < spriteHeader.NumFrames; i++)
            {
                int frameGroup   = binReader.ReadInt32();
                int frameOriginX = binReader.ReadInt32();
                int frameOriginY = binReader.ReadInt32();
                int frameWidth   = binReader.ReadInt32();
                int frameHeight  = binReader.ReadInt32();

                Bitmap bmp = new Bitmap(frameWidth, frameHeight, PixelFormat.Format8bppIndexed)
                {
                    Palette = pal
                };

                //Get pixelsize
                uint pixelSize = (uint)(frameWidth * frameHeight);

                indexesOfPixelPositions[i] = binReader.BaseStream.Position;
                pixelsLengths[i]           = pixelSize;

                //Load all pixels from file to array
                byte[] pixels = binReader.ReadBytes((int)pixelSize);

                //Lock bitmap for pixel manipulation
                BitmapData bmd = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.WriteOnly, PixelFormat.Format8bppIndexed);
                System.Runtime.InteropServices.Marshal.Copy(pixels, 0, bmd.Scan0, pixels.Length);
                bmp.UnlockBits(bmd);

                //Insert new frame to frames list
                Frame frame = new Frame
                {
                    OriginX = frameOriginX,
                    OriginY = frameOriginY,
                    Image   = bmp
                };
                frames.Add(frame);
            }

            return(frames.ToArray());
        }
コード例 #51
0
 //填充外边框颜色变化响应事件
 private void cbOutlineColor_MouseUp(object sender, MouseEventArgs e)
 {
     IRgbColor pColor = new RgbColor();
     pColor.RGB = 255;
     tagRECT ptagRECT = new tagRECT();
     ptagRECT.left = cbOutlineColor.PointToScreen(System.Drawing.Point.Empty).X;
     ptagRECT.bottom = cbOutlineColor.PointToScreen(System.Drawing.Point.Empty).Y + cbOutlineColor.Height;
     IColorPalette pColorPalette = new ColorPalette();
     pColorPalette.TrackPopupMenu(ref ptagRECT, pColor, false, 0);
     pColor = pColorPalette.Color as IRgbColor;
     Color color = Color.FromArgb(pColor.Red, pColor.Green, pColor.Blue);
     //btOutlineColor.BackColor = color;
     cbOutlineColor.BackColor = color;
     ILineSymbol pLineSymbol = ((IFillSymbol)pStyleGalleryItem.Item).Outline;
     pLineSymbol.Color = pColor;
     ((IFillSymbol)pStyleGalleryItem.Item).Outline = pLineSymbol;
     PreviewPicture();
 }
コード例 #52
0
        /// <summary>
        /// OpenCVのMatを指定した出力先にSystem.Drawing.Bitmapとして変換する
        /// </summary>
        /// <param name="src">変換するMat</param>
        /// <param name="dst">出力先のSystem.Drawing.Bitmap</param>
        /// <remarks>Author: shimat, Gummo (ROI support)</remarks>
#else
        /// <summary>
        /// Converts Mat to System.Drawing.Bitmap
        /// </summary>
        /// <param name="src">Mat</param>
        /// <param name="dst">Mat</param>
        /// <remarks>Author: shimat, Gummo (ROI support)</remarks>
#endif
        public static unsafe void ToBitmap(this Mat src, Bitmap dst)
        {
            if (src == null)
            {
                throw new ArgumentNullException(nameof(src));
            }
            if (dst == null)
            {
                throw new ArgumentNullException(nameof(dst));
            }
            if (src.IsDisposed)
            {
                throw new ArgumentException("The image is disposed.", nameof(src));
            }
            if (src.Depth() != MatType.CV_8U)
            {
                throw new ArgumentException("Depth of the image must be CV_8U");
            }
            //if (src.IsSubmatrix())
            //    throw new ArgumentException("Submatrix is not supported");
            if (src.Width != dst.Width || src.Height != dst.Height)
            {
                throw new ArgumentException("");
            }

            PixelFormat pf = dst.PixelFormat;

            // 1プレーン用の場合、グレースケールのパレット情報を生成する
            if (pf == PixelFormat.Format8bppIndexed)
            {
                ColorPalette plt = dst.Palette;
                for (int x = 0; x < 256; x++)
                {
                    plt.Entries[x] = Color.FromArgb(x, x, x);
                }
                dst.Palette = plt;
            }

            int        w    = src.Width;
            int        h    = src.Height;
            Rectangle  rect = new Rectangle(0, 0, w, h);
            BitmapData?bd   = null;

            bool submat     = src.IsSubmatrix();
            bool continuous = src.IsContinuous();

            try
            {
                bd = dst.LockBits(rect, ImageLockMode.WriteOnly, pf);

                IntPtr srcData = src.Data;
                byte * pSrc    = (byte *)(srcData.ToPointer());
                byte * pDst    = (byte *)(bd.Scan0.ToPointer());
                int    ch      = src.Channels();
                int    sstep   = (int)src.Step();
                int    dstep   = ((src.Width * ch) + 3) / 4 * 4; // 4の倍数に揃える
                int    stride  = bd.Stride;

                switch (pf)
                {
                case PixelFormat.Format1bppIndexed:
                {
                    if (submat)
                    {
                        throw new NotImplementedException("submatrix not supported");
                    }

                    // BitmapDataは4byte幅だが、IplImageは1byte幅
                    // 手作業で移し替える
                    //int offset = stride - (w / 8);
                    int  x = 0;
                    int  y;
                    int  bytePos;
                    byte mask;
                    byte b = 0;
                    int  i;
                    for (y = 0; y < h; y++)
                    {
                        for (bytePos = 0; bytePos < stride; bytePos++)
                        {
                            if (x < w)
                            {
                                for (i = 0; i < 8; i++)
                                {
                                    mask = (byte)(0x80 >> i);
                                    if (x < w && pSrc[sstep * y + x] == 0)
                                    {
                                        b &= (byte)(mask ^ 0xff);
                                    }
                                    else
                                    {
                                        b |= mask;
                                    }

                                    x++;
                                }
                                pDst[bytePos] = b;
                            }
                        }
                        x     = 0;
                        pDst += stride;
                    }
                    break;
                }

                case PixelFormat.Format8bppIndexed:
                case PixelFormat.Format24bppRgb:
                case PixelFormat.Format32bppArgb:
                    if (sstep == dstep && !submat && continuous)
                    {
                        uint imageSize = (uint)(src.DataEnd.ToInt64() - src.Data.ToInt64());
                        MemoryHelper.CopyMemory(pDst, pSrc, imageSize);
                    }
                    else
                    {
                        for (int y = 0; y < h; y++)
                        {
                            long offsetSrc = (y * sstep);
                            long offsetDst = (y * dstep);
                            // 一列ごとにコピー
                            MemoryHelper.CopyMemory(pDst + offsetDst, pSrc + offsetSrc, w * ch);
                        }
                    }
                    break;

                default:
                    throw new NotImplementedException();
                }
            }
            finally
            {
                dst.UnlockBits(bd);
            }
        }
コード例 #53
0
 protected ColorGrid(ColorCollection colors, ColorCollection customColors, ColorPalette palette)
 {
     this.BeginUpdate();
       this.SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | ControlStyles.OptimizedDoubleBuffer | ControlStyles.Selectable | ControlStyles.StandardClick | ControlStyles.StandardDoubleClick | ControlStyles.SupportsTransparentBackColor, true);
       _previousHotIndex = InvalidIndex;
       _previousColorIndex = InvalidIndex;
       _hotIndex = InvalidIndex;
       this.ColorRegions = new Dictionary<int, Rectangle>();
       if (this.Palette != ColorPalette.None)
       {
     this.Colors = colors;
       }
       else
       {
     this.Palette = palette;
       }
       this.CustomColors = customColors;
       this.ShowCustomColors = true;
       this.CellSize = new Size(12, 12);
       this.Spacing = new Size(3, 3);
       this.Columns = 16;
       this.AutoSize = true;
       this.Padding = new Padding(5);
       this.AutoAddColors = true;
       this.CellBorderColor = SystemColors.ButtonShadow;
       this.ShowToolTips = true;
       this.SeparatorHeight = 8;
       this.EditMode = ColorEditingMode.CustomOnly;
       this.Color = Color.Black;
       this.CellBorderStyle = ColorCellBorderStyle.FixedSingle;
       this.SelectedCellStyle = ColorGridSelectedCellStyle.Zoomed;
       this.EndUpdate();
 }
コード例 #54
0
 private void OnEnable()
 {
     colorPalette = target as ColorPalette;
 }
コード例 #55
0
    public static ColorCollection GetPalette(ColorPalette palette)
    {
      ColorCollection result;

      switch (palette)
      {
        case ColorPalette.Named:
          result = NamedColors;
          break;
        case ColorPalette.Office2010:
          result = Office2010Standard;
          break;
        case ColorPalette.Paint:
          result = PaintPalette;
          break;
        case ColorPalette.Standard:
          result = QbColors;
          break;
        case ColorPalette.None:
          result = new ColorCollection();
          break;
        default:
          throw new ArgumentException("Invalid palette", "palette");
      }

      return result;
    }
コード例 #56
0
 void Start()
 {
     meshR = GetComponent<MeshRenderer>();
     palette = colorPalette.GetComponent<ColorPalette>();
     currentFreq = colorSwapFreq;
 }