Esempio n. 1
0
 public void Image_GetSetPixel()
 {
     Image i = new Image(1, 1);
     Color c = i.GetPixel(0, 0);
     Assert.AreEqual(c.ToString(), "rgba(0,0,0,0.0)");
     i.SetPixel(0,0, new Color(255, 255, 255));
     Color c1 = i.GetPixel(0, 0);
     Assert.AreEqual(c1.ToString(), "rgb(255,255,255)");
 }
Esempio n. 2
0
        public void ImageView_IsSolid()
        {
            Image i = new Image(256, 256);
            ImageView iv = i.View(0, 0, 256, 256);
            Assert.IsTrue(iv.IsSolid());

            i.SetPixel(0, 0, new Color("red"));
            iv = i.View(0, 0, 256, 256);
            Assert.IsFalse(iv.IsSolid());
        }
Esempio n. 3
0
 public override Image Load(Stream s)
 {
     Tiff tif = Tiff.Open(s);
     FieldValue[] value = tif.GetField(TiffTag.ImageWidth);
     int width = value[0].ToInt();
     value = tif.GetField(TiffTag.ImageLength);
     int height = value[0].ToInt();
     int[] raster = new int[height * width];
     tif.ReadRGBAImage(width, height, raster);
     Image i = new Image(width, height);
     int rgba, rasterOffset;
     byte r, g, b, a;
     for (uint y = 0; y < i.Height; y++)
     {
         rasterOffset = (int)(y * i.Width);
         for (uint x = 0; x < i.Width; x++)
         {
             rgba = raster[rasterOffset++];
             r = (byte)(rgba & 0xff);
             g = (byte)((rgba >> 8) & 0xff);
             b = (byte)((rgba >> 16) & 0xff);
             a = (byte)((rgba >> 24) & 0xff);
             i.SetPixel(x, y, new Pixel(r, g, b, a));
         }
     }
     // Need to flip the image.
     Image i2 = new Image(width, height);
     uint y2 = 0;
     for (uint y = (uint)(i.Height - 1); y >= 0 && y < i.Height; y--)
     {
         for (uint x = 0; x < i.Width; x++)
         {
             i2.SetPixel(x, y2, i.GetPixel(x, y));
         }
         y2++;
     }
     i.Dispose();
     return i2;
 }
 void CreateBlankTexture()
 {
     LogFile.GetInstance().WriteLine("CreateBlankTexture()");
     //Bitmap bitmap = new Bitmap(1, 1, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
     //Graphics g = Graphics.FromImage(bitmap);
     //Pen pen = new Pen(System.Drawing.Color.FromArgb(255,255, 255, 255));
     //g.DrawRectangle(pen, 0, 0, 1, 1);
     //DevIL.DevIL.SaveBitmap("testout.JPG", bitmap);
     Image image = new Image(1, 1);
     image.SetPixel(0, 0, 255, 255, 255, 255);
     this.texture = new GlTexture(image,false);
 }
Esempio n. 5
0
        public override Image Load(System.IO.Stream s)
        {

            if (s.ReadByte() == 255)
            {
                byte[] buf = new byte[s.Length - 1];
                s.Read(buf, 0, buf.Length);
                s = new MemoryStream(Orvid.Compression.LZMA.Decompress(buf));
            }
            else
            {
                s.Position = 0;
            }
            byte[] tmp = new byte[8];
            s.Read(tmp, 0, 8); // skip the 8 empty bytes at the start of the file.
            tmp = new byte[4];
            s.Read(tmp, 0, 4);
            uint Height = ReadUInt32(tmp); // Read the Height.
            s.Read(tmp, 0, 4);
            uint Width = ReadUInt32(tmp); // Read the Width.
            Image i = new Image((int)Width, (int)Height);
            byte r, g, b, a;
            for (uint x = 0; x < Width; x++)
            {
                for (uint y = 0; y < Height; y++)
                {
                    r = (byte)s.ReadByte();
                    g = (byte)s.ReadByte();
                    b = (byte)s.ReadByte();
                    a = (byte)s.ReadByte();
                    i.SetPixel(x, y, new Pixel(r, g, b, a));
                }
            }
            return i;
        }
Esempio n. 6
0
            //private class pcx_t
            //{
            //    public char manufacturer;
            //    public char version;
            //    public char encoding;
            //    public char bits_per_pixel;
            //    public short xmin, ymin, xmax, ymax;
            //    public short hres, vres;
            //    public int[] palette = new int[48];
            //    public char reserved;
            //    public char color_planes;
            //    public short bytes_per_line;
            //    public short palette_type;
            //    public byte[] filler = new byte[58];
            //    public byte[] data;

            //    public pcx_t(byte[] raw)
            //    {
            //        manufacturer = (char)raw[0];
            //        version = (char)raw[1];
            //        encoding = (char)raw[2];
            //        bits_per_pixel = (char)raw[3];
            //        xmin = (short)((raw[4] + (raw[5] << 8)) & 0xff);
            //        ymin = (short)((raw[6] + (raw[7] << 8)) & 0xff);
            //        xmax = (short)((raw[8] + (raw[9] << 8)) & 0xff);
            //        ymax = (short)((raw[10] + (raw[11] << 8)) & 0xff);
            //        hres = (short)((raw[12] + (raw[13] << 8)) & 0xff);
            //        vres = (short)((raw[14] + (raw[15] << 8)) & 0xff);
            //        for (int i = 0; i < 48; i++)
            //            palette[i] = (raw[16 + i] & 0xff);
            //        reserved = (char)raw[64];
            //        color_planes = (char)raw[65];
            //        bytes_per_line = (short)((raw[66] + (raw[67] << 8)) & 0xff);
            //        palette_type = (short)((raw[68] + (raw[69] << 8)) & 0xff);
            //        for (int i = 0; i < 58; i++)
            //            filler[i] = raw[70 + i];
            //        data = new byte[raw.Length - 128];
            //        for (int i = 0; i < raw.Length - 128; i++)
            //            data[i] = raw[128 + i];
            //    }
            //}

            //private static byte[] imageData;
            //private static int imageWidth, imageHeight;
            //public static Image Load(Stream s)
            //{
            //    int[] palette, pic, ot, pix;
            //    int k, x, y, len = 0, dataByte, runLength;
            //    byte[] raw;
            //    pcx_t pcx;

            //    raw = new byte[s.Length];
            //    s.Read(raw, 0, (int)s.Length);


            //    pcx = new pcx_t(raw);
            //    raw = pcx.data;

            //    if (pcx.manufacturer != 0x0a || pcx.version != 5 || pcx.encoding != 1 || pcx.bits_per_pixel != 8 || pcx.xmax >= 640 || pcx.ymax >= 480)
            //    {
            //        throw new Exception("Bad Pcx Data!");
            //    }

            //    palette = new int[768];
            //    for (int i = 0; i < 768; i++)
            //    {
            //        if ((uint)(len - 128 - 768 + i) < pcx.data.Length)
            //        {
            //            palette[i] = pcx.data[len - 128 - 768 + i] & 0xff;
            //        }
            //    }

            //    imageWidth = pcx.xmax + 1;
            //    imageHeight = pcx.ymax + 1;

            //    ot = new int[(pcx.ymax + 1) * (pcx.xmax + 1)];
            //    pic = ot;
            //    pix = ot;
            //    int pixcount = 0;
            //    int rawcount = 0;

            //    for (y = 0; y <= pcx.ymax; y++, pixcount += pcx.xmax + 1)
            //    {
            //        for (x = 0; x <= pcx.xmax; )
            //        {
            //            dataByte = raw[rawcount++];

            //            if ((dataByte & 0xC0) == 0xC0)
            //            {
            //                runLength = dataByte & 0x3F;
            //                dataByte = raw[rawcount++];
            //            }
            //            else
            //                runLength = 1;

            //            while (runLength-- > 0)
            //                pix[pixcount + x++] = dataByte & 0xff;
            //        }
            //    }

            //    Image im = new Image(imageWidth, imageHeight);
            //    imageData = new byte[imageWidth * imageHeight * 4];

            //    //convert to rgb format
            //    for (k = 0; k < (imageWidth * imageHeight); k++)
            //    {
            //        imageData[k * 4] = (byte)palette[pic[k] * 3];
            //        imageData[k * 4 + 1] = (byte)palette[pic[k] * 3 + 1];
            //        imageData[k * 4 + 2] = (byte)palette[pic[k] * 3 + 2];
            //        imageData[k * 4 + 3] = 0xff;
            //    }
            //    uint ndx = 0;
            //    for (uint yloc = 0; yloc < imageHeight; yloc++)
            //    {
            //        for (uint xloc = 0; xloc < imageWidth; xloc++)
            //        {
            //            im.SetPixel(xloc, yloc, new Pixel(imageData[ndx], imageData[ndx + 1], imageData[ndx + 2], imageData[ndx + 3]));
            //            ndx += 4;
            //        }
            //    }

            //    return im;
            //}
            #endregion


            #region Load
            public static Image Load(Stream input)
            {
                PcxPalette palette = null;
                uint[] numArray = null;
                Image im;
                PcxHeader header = new PcxHeader(input);

                #region Checks
                if (header.id != PcxId.ZSoftPCX)
                {
                    throw new FormatException("Not a PCX file.");
                }
                if (((header.version != PcxVersion.Version3_0) && (header.version != PcxVersion.Version2_8_Palette)) && ((header.version != PcxVersion.Version2_8_DefaultPalette) && (header.version != PcxVersion.Version2_5)))
                {
                    throw new FormatException("Unsupported PCX version: " + header.version.ToString());
                }
                if (((header.bitsPerPixel != 1) && (header.bitsPerPixel != 2)) && ((header.bitsPerPixel != 4) && (header.bitsPerPixel != 8)))
                {
                    throw new FormatException("Unsupported PCX bits per pixel: " + header.bitsPerPixel.ToString() + " bits per pixel");
                }
                int width = (header.xMax - header.xMin) + 1;
                int height = (header.yMax - header.yMin) + 1;
                if (((width < 0) || (height < 0)) || ((width > 0xffff) || (height > 0xffff)))
                {
                    throw new FormatException("Invalid image dimensions: (" + header.xMin.ToString() + "," + header.yMin.ToString() + ")-(" + header.xMax.ToString() + "," + header.yMax.ToString() + ")");
                }
                int num3 = (header.bytesPerLine * 8) / header.bitsPerPixel;
                int BitDepth = header.bitsPerPixel * header.nPlanes;
                if ((((BitDepth != 1) && (BitDepth != 2)) && ((BitDepth != 4) && (BitDepth != 8))) && (BitDepth != 0x18))
                {
                    throw new FormatException("Unsupported PCX bit depth: " + BitDepth.ToString());
                }
                #endregion

                #region Load Palette
                while (true)
                {
                    if (BitDepth == 1)
                    {
                        palette = PcxPalette.FromEgaPalette(PcxPalette.MONO_PALETTE);
                        break;
                    }
                    if (BitDepth >= 8)
                    {
                        if (BitDepth == 8)
                        {
                            long position = input.Position;
                            input.Seek(-769L, SeekOrigin.End);
                            if (input.ReadByte() != 12)
                            {
                                throw new FormatException("PCX palette marker not present in file");
                            }
                            palette = new PcxPalette(input, 0x100);
                            input.Seek(position, SeekOrigin.Begin);
                        }
                        else
                        {
                            palette = new PcxPalette(0x100);
                        }
                        break;
                    }
                    switch (header.version)
                    {
                        case PcxVersion.Version2_5:
                        case PcxVersion.Version2_8_DefaultPalette:
                            if (BitDepth == 2)
                            {
                                numArray = PcxPalette.CGA_PALETTE;
                                palette = PcxPalette.FromEgaPalette(numArray);
                            }
                            break;

                        default:
                            numArray = new uint[0];
                            palette = PcxPalette.FromColorMap(header.colorMap);
                            break;
                    }
                    if (numArray == null)
                    {
                        numArray = PcxPalette.EGA_PALETTE;
                    }
                    break;
                }
                #endregion

                im = new Image(width, height);
                uint[] array = new uint[width];
                for (int y = 0; y < height; y++)
                {
                    PcxByteReader byteReader = (header.encoding == PcxEncoding.RunLengthEncoded) ? ((PcxByteReader)new PcxRleByteReader(input)) : ((PcxByteReader)new PcxRawByteReader(input));
                    PcxIndexReader indxReader = new PcxIndexReader(byteReader, header.bitsPerPixel);
                    for (int j = 0; j < header.nPlanes; j++)
                    {
                        for (int m = 0; m < num3; m++)
                        {
                            uint num10 = indxReader.ReadIndex();
                            if (m < width)
                            {
                                array[m] |= num10 << (j * header.bitsPerPixel);
                            }
                        }
                    }
                    for (int x = 0; x < width; x++)
                    {
                        Pixel bgra;
                        uint TempC = array[x];
                        if (BitDepth == 24)
                        {
                            byte r = (byte)(TempC & 0xff);
                            byte g = (byte)((TempC >> 8) & 0xff);
                            byte b = (byte)((TempC >> 16) & 0xff);
                            bgra = new Pixel(r, g, b, 255);
                        }
                        else
                        {
                            bgra = palette[TempC];
                        }
                        im.SetPixel((uint)x, (uint)y, bgra);
                    }
                }
                return im;
            }
        public void Save( string filename )
        {
            double[,] mesh = SlopeMap.GetInstance().GetSlopeMap();
            int width = mesh.GetUpperBound(0) + 1;
            int height = mesh.GetUpperBound(1) + 1;

            double maxslopetoexport = Config.GetInstance().SlopemapExportMaxSlope;

            Image image = new Image(width, height);
            //Bitmap bitmap = new Bitmap(width, height, PixelFormat.Format24bppRgb);
            //Graphics g = Graphics.FromImage(bitmap);
            // cache pencolors;
            List<MovementAreaConfig> movementareas = Config.GetInstance().movementareas;
            SortedList<double, Color> sortedcolorbymaxslope = new SortedList<double, Color>();
            foreach (MovementAreaConfig movementarea in movementareas)
            {
                if (movementarea.MaxSlope >= 0)
                {
                    sortedcolorbymaxslope.Add(movementarea.MaxSlope, movementarea.color);
                }
                else
                {
                    sortedcolorbymaxslope.Add(double.PositiveInfinity, movementarea.color);
                }
            }
            for (int area = 0; area < sortedcolorbymaxslope.Count; area++)
            {
                LogFile.GetInstance().WriteLine(sortedcolorbymaxslope.Keys[area] + " " + sortedcolorbymaxslope.Values[area].ToString());
            }
            for (int i = 0; i < width; i++)
            {
                for (int j = 0; j < height; j++)
                {
                    Color colortouse = new Color(1, 1, 1);
                    for (int area = 0; area < sortedcolorbymaxslope.Count; area++)
                    {
                        if (mesh[i, j] < sortedcolorbymaxslope.Keys[area])
                        {
                            colortouse = sortedcolorbymaxslope.Values[area];
                            break;
                        }
                    }
                    int valuetowrite = (int)(mesh[i, j] * 255 / maxslopetoexport);
                    valuetowrite = Math.Max(0, valuetowrite);
                    valuetowrite = Math.Min(255, valuetowrite);
                    image.SetPixel(i, j, (byte)(colortouse.r * 255 * valuetowrite),
                        (byte)( colortouse.g * 255 * valuetowrite ),
                        (byte)( colortouse.b * 255 * valuetowrite ),
                        255
                    );
                }
            }
            image.Save(filename);
            exportheightmapfilename = filename;
            MainUI.GetInstance().uiwindow.InfoMessage("Slopemap exported");
        }
Esempio n. 8
0
            private Image LoadFromBinary(byte[] data, byte height, byte width, uint bits)
            {
                #region LoadData
                bool[] idata = new bool[data.Length * 8];
                int bitnum = 0;
                for (int inc = 0; inc < data.Length; inc++)
                {
                    if ((data[inc] & 1) == 1)
                    {
                        idata[bitnum] = true;
                    }
                    bitnum++;
                    if ((data[inc] & 2) == 2)
                    {
                        idata[bitnum] = true;
                    }
                    bitnum++;
                    if ((data[inc] & 4) == 4)
                    {
                        idata[bitnum] = true;
                    }
                    bitnum++;
                    if ((data[inc] & 8) == 8)
                    {
                        idata[bitnum] = true;
                    }
                    bitnum++;
                    if ((data[inc] & 16) == 16)
                    {
                        idata[bitnum] = true;
                    }
                    bitnum++;
                    if ((data[inc] & 32) == 32)
                    {
                        idata[bitnum] = true;
                    }
                    bitnum++;
                    if ((data[inc] & 64) == 64)
                    {
                        idata[bitnum] = true;
                    }
                    bitnum++;
                    if ((data[inc] & 128) == 128)
                    {
                        idata[bitnum] = true;
                    }
                    bitnum++;
                }
                #endregion

                bitnum = 0;
                Image i = new Image(width, height);

                //for (uint y = 0; y < height; y++)
                for (uint x = 0; x < width; x++)
                {
                    //for (uint x = 0; x < width; x++)
                    for (uint y = 0; y < height; y++)
                    {
                        if (bitnum >= bits)
                        {
                            break;
                        }
                        if (idata[bitnum])
                        {
                            bitnum++;
                            if (idata[bitnum])
                            {
                                bitnum++;
                                i.SetPixel(x, y, Colors.Black); // Color the pixel white
                            }
                            else
                            {
                                bitnum++;
                                bool[] tmp = new bool[8];
                                Array.Copy(idata, bitnum, tmp, 0, 8);
                                bitnum += 8;
                                byte greyscale = ReadByte(tmp);
                                i.SetPixel(x, y, new Pixel(greyscale, greyscale, greyscale, 255));
                            }
                        }
                        else
                        {
                            bitnum++;
                            i.SetPixel(x, y, Colors.White); // Color the pixel black
                        }
                    }
                    if (bitnum >= bits)
                    {
                        break;
                    }
                }

                return i;
            }
Esempio n. 9
0
 static Image ReadBitmapData(Stream input, VbpFileHeader fileHeader, VbpInformationHeader infoHeader)
 {
     input.Position = fileHeader.OffBits;
     int count = (infoHeader.Width * infoHeader.Height) * 2;
     byte[] buffer = new byte[count];
     input.Read(buffer, 0, count);
     Image bitmap = new Image(infoHeader.Width, infoHeader.Height);
     int shift = GetShift(infoHeader.ColorMask.R);
     int num3 = GetShift(infoHeader.ColorMask.G);
     int num4 = GetShift(infoHeader.ColorMask.B);
     int num5 = 0;
     for (int i = 0; i < infoHeader.Height; i++)
     {
         for (int j = 0; j < infoHeader.Width; j++)
         {
             ushort num8 = BitConverter.ToUInt16(buffer, num5++ * 2);
             ushort red = (ushort)_colorTable5Bit[(num8 & infoHeader.ColorMask.R) >> shift];
             ushort green = (ushort)_colorTable5Bit[(num8 & infoHeader.ColorMask.G) >> num3];
             ushort blue = (ushort)_colorTable5Bit[(num8 & infoHeader.ColorMask.B) >> num4];
             Pixel color = new Pixel((byte)red, (byte)green, (byte)blue, 255);
             bitmap.SetPixel((uint)j, (uint)i, color);
         }
     }
     return bitmap;
 }
Esempio n. 10
0
        public override void Render(Image im, BoundingBox clip, AffineTransform tx, string text, Vec2 loc, Pixel color)
        {
            if (text == null || text.Length == 0)
                return;

            int offset = 0, 
                x = 0, y = 0,
                bdfFontDepth = bdfFont.getDepth(),
                x_min = int.MaxValue,
                y_min = int.MaxValue,
                x_max = int.MinValue,
                y_max = int.MinValue,
                charsCount = text.Length,
                fHeight, scan, fg_r, fg_g, 
                fg_b, bx, by, offsetLine,
                fPixel, px, py, bg_r, 
                bg_g, bg_b, r, g, b
                ;
            int[] fData;
            Vec2 src, dst;
            BDFParser.Rectangle glyph_box = new BDFParser.Rectangle();
            BDFGlyph glyph;
            Image img;

            if ((bdfFont != null) && (charsCount > 0))
            {
                char[] chrs = text.ToCharArray();
                int mH = 0;
                int mY = 0;
                int mxY = 0;
                int tW = 0;
                int tH = 0;
                for (uint m = 0; m < text.Length; m++)
                {
                    glyph = bdfFont.getGlyph(chrs[m]);
                    glyph_box = glyph.getBbx(glyph_box);
                    if (glyph_box.height > mH)
                    {
                        mH = glyph_box.height + 2;
                    }
                    if (glyph_box.y < mY)
                    {
                        mY = glyph_box.y;
                    }
                    if (glyph_box.y > mxY)
                    {
                        mxY = glyph_box.y;
                    }
                    tW += glyph_box.width + glyph_box.x + 2;
                }

                tH = mH + (mxY - mY);
                y = mH + -mY;
                img = new Image(tW, tH);


                float f_max = (1 << bdfFontDepth) - 1;
                if (f_max == 0)
                    f_max = 1;

                glyph_box = new BDFParser.Rectangle();
                src = new Vec2();
                dst = new Vec2();

                for (int i = 0; i < charsCount; i++)
                {
                    glyph = bdfFont.getGlyph(chrs[i]);
                    if (glyph == null)
                    {
                        continue;
                    }
                    
                    glyph_box = glyph.getBbx(glyph_box);

                    fHeight = glyph_box.height;
                    fData = glyph.getData();
                    scan = fData.Length / fHeight;

                    fg_r = color.R;
                    fg_g = color.G;
                    fg_b = color.B;

                    //box location
                    bx = x + offset + glyph_box.x;
                    by = y - fHeight - glyph_box.y;

                    for (int k = 0; k < fHeight; k++)
                    {
                        offsetLine = k * scan;
                        for (int j = 0; j < scan; j++)
                        {
                            fPixel = fData[offsetLine + j];
                            if (fPixel != 0)
                            {

                                //pixel location
                                px = bx + j;
                                py = by + k;

                                if (tx != null)
                                {
                                    //src.setLocation(px, py);
                                    //tx.transform(src, dst);
#warning TODO: Add support for this.
                                    //px = dst.X;
                                    //py = dst.Y;
                                }

                                //clip
                                if (clip == null || clip.Contains(px, py))
                                {
                                    //compute color
                                    Pixel bg_color = img.GetPixel((uint)px, (uint)py);

                                    bg_r = bg_color.R;
                                    bg_g = bg_color.G;
                                    bg_b = bg_color.B;

                                    //todo improve this pixel composition

                                    float alpha = fPixel / f_max;

                                    r = bg_r + ((int)((fg_r - bg_r) * alpha)) & 0xFF;
                                    g = bg_g + ((int)((fg_g - bg_g) * alpha)) & 0xFF;
                                    b = bg_b + ((int)((fg_b - bg_b) * alpha)) & 0xFF;

                                    Pixel nw = new Pixel((byte)r, (byte)g, (byte)b, 255);

                                    img.SetPixel((uint)px, (uint)py, nw);

                                    if (x_min > px)
                                        x_min = px;
                                    if (y_min > py)
                                        y_min = py;
                                    if (x_max < px)
                                        x_max = px;
                                    if (y_max < py)
                                        y_max = py;
                                }
                            }
                        }
                    }
                    offset += glyph.getDWidth().width;
                }
                //img = ImageManipulator.Resize(img, new Vec2(img.Width * 8, img.Height * 8), ImageManipulator.ScalingAlgorithm.Bicubic);
                //img = ImageManipulator.Resize(img, Vec2.Zero, ImageManipulator.ScalingAlgorithm.Hq2x);
                //img = ImageManipulator.Resize(img, Vec2.Zero, ImageManipulator.ScalingAlgorithm.Hq4x);
                im.DrawImage(loc, img);
            }
        }
 public void Save(string filename)
 {
     double[,] mesh = Terrain.GetInstance().Map;
     int width = mesh.GetUpperBound(0) + 1;
     int height = mesh.GetUpperBound(1) + 1;
     Image image = new Image(width, height);
     //Bitmap bitmap = new Bitmap( width, height, PixelFormat.Format24bppRgb );
     //Graphics g = Graphics.FromImage(bitmap);
     //Pen[] pens = new Pen[256];
     //for (int i = 0; i < 256; i++)
     //{
       //  pens[i] = new Pen(System.Drawing.Color.FromArgb(i, i, i));
     //}
     double minheight = Config.GetInstance().minheight;
     double maxheight = Config.GetInstance().maxheight;
     double heightmultiplier = 255 / (maxheight - minheight);
     for (int i = 0; i < width; i++)
     {
         for( int j = 0; j < height; j++ )
         {
             int normalizedmeshvalue = (int)( (mesh[i, j] - minheight) * heightmultiplier );
             normalizedmeshvalue = Math.Max( 0,normalizedmeshvalue );
             normalizedmeshvalue = Math.Min( 255,normalizedmeshvalue );
             byte normalizedmeshvaluebyte = (byte)normalizedmeshvalue;
             image.SetPixel(i, j, normalizedmeshvaluebyte, normalizedmeshvaluebyte, normalizedmeshvaluebyte, 255);
             //g.DrawRectangle(pens[ normalizedmeshvalue ], i, j, 1, 1);
         }
     }
     if (File.Exists(filename))
     {
         File.Delete(filename);
     }
     image.Save(filename);
     //DevIL.DevIL.SaveBitmap(filename, bitmap);
     //bitmap.Save(filename, ImageFormat.Bmp);
     Terrain.GetInstance().HeightmapFilename = filename;
     Terrain.GetInstance().OnTerrainModified();
     MainUI.GetInstance().uiwindow.InfoMessage("Heightmap saved");
 }
Esempio n. 12
0
File: OPFF.cs Progetto: Orvid/Cosmos
        private Image LoadFromBinary(byte[] data, byte height, byte width, int bits)
        {
            MemoryStream m = new MemoryStream(data);
            BinaryReader br = new BinaryReader(m);
            Image i = new Image(width, height);

            for (uint x = 0; x < width; x++)
            //for (uint y = 0; y < height; y++)
            {
                for (uint y = 0; y < height; y++)
                //for (uint x = 0; x < width; x++)
                {
                    //if (br.ReadBoolean())
                    //{
                    //    if (br.ReadBoolean())
                    //    {
                    //        i.SetPixel(x, y, Colors.Black); // Color the pixel black
                    //    }
                    //    else
                    //    {
                            byte greyscale = br.ReadByte();
                            if (greyscale != 255)
                            {
                                i.SetPixel(x, y, new Pixel(greyscale, greyscale, greyscale, 255)); // Color the pixel as greyscale
                            }
                    //    }
                    //}
                    //else
                    //{
                    //    i.SetPixel(x, y, Colors.White); // Color the pixel white
                    //}
                }
            }
            data = null;
            br.Dispose();
            m.Dispose();
            return i;
        }
Esempio n. 13
0
 public static Image Load(Stream input)
 {
     string str;
     if (ReadLine(input, out str) || (str.Trim().Substring(0, 6).CompareTo("/* XPM") != 0))
     {
         throw new Exception("No valid XPM header found");
     }
     do
     {
         if (ReadLine(input, out str))
         {
             throw new Exception("Cannot find the values section of the file");
         }
     }
     while (str.Trim().Substring(0, 1).CompareTo("\"") != 0);
     char[] separator = new char[] { ' ', '\t', '"' };
     string[] strArray = str.Split(separator);
     if (strArray.Length < 6)
     {
         throw new Exception("Invalid values section of the file");
     }
     int width = Convert.ToInt32(strArray[1]);
     int height = Convert.ToInt32(strArray[2]);
     int num3 = Convert.ToInt32(strArray[3]);
     int length = Convert.ToInt32(strArray[4]);
     Image image = new Image(width, height);
     do
     {
         if (ReadLine(input, out str))
         {
             throw new Exception("Cannot find the color section of the file");
         }
     }
     while (str.Trim().Substring(0, 1).CompareTo("\"") != 0);
     Dictionary<string, Pixel> dictionary = new Dictionary<string, Pixel>();
     for (int i = 0; i < num3; i++)
     {
         string str2 = str.Trim();
         string key = str2.Substring(1, length);
         strArray = str2.Substring(length + 1).Split(separator);
         if (strArray.Length < 4)
         {
             throw new Exception("Invalid color entry");
         }
         if (strArray[1].CompareTo("c") != 0)
         {
             throw new Exception("Non color type found, unhandled");
         }
         if (strArray[2].CompareTo("None") == 0)
         {
             Pixel color = new Pixel(true);
             dictionary.Add(key, color);
         }
         else
         {
             if (strArray[2].Substring(0, 1).CompareTo("#") != 0)
             {
                 throw new Exception("Non RGB color type found, unhandled");
             }
             byte red = (byte)Convert.ToInt32(strArray[2].Substring(1, 2), 0x10);
             byte green = (byte)Convert.ToInt32(strArray[2].Substring(3, 2), 0x10);
             byte blue = (byte)Convert.ToInt32(strArray[2].Substring(5, 2), 0x10);
             Pixel color2 = new Pixel(red, green, blue, 255);
             dictionary.Add(key, color2);
         }
         if (ReadLine(input, out str))
         {
             throw new Exception("Corrupt color section in the file");
         }
     }
     do
     {
         if (ReadLine(input, out str))
         {
             throw new Exception("Cannot find the pixel section of the file");
         }
     }
     while (str.Trim().Substring(0, 1).CompareTo("\"") != 0);
     for (int j = 0; j < height; j++)
     {
         string str4 = str.Trim();
         if (str4.Substring(1).IndexOf('"') != (width * length))
         {
             throw new Exception("Corrupt pixel entry in the file");
         }
         int startIndex = 1;
         int x = 0;
         while (x < width)
         {
             Pixel color3;
             string str5 = str4.Substring(startIndex, length);
             if (!dictionary.TryGetValue(str5, out color3))
             {
                 throw new Exception("Unknown pixel value - weird");
             }
             image.SetPixel((uint)x, (uint)j, color3);
             x++;
             startIndex += length;
         }
         if (ReadLine(input, out str))
         {
             throw new Exception("Corrupt pixel section in the file");
         }
     }
     return image;
 }
Esempio n. 14
0
                /// <summary>
                /// Decodes the image from the specified _stream and sets
                /// the data to image.
                /// </summary>
                /// <param name="image">The image, where the data should be set to.
                /// Cannot be null (Nothing in Visual Basic).</param>
                /// <param name="stream">The _stream, where the image should be
                /// decoded from. Cannot be null (Nothing in Visual Basic).</param>
                /// <exception cref="ArgumentNullException">
                /// 	<para><paramref name="image"/> is null (Nothing in Visual Basic).</para>
                /// 	<para>- or -</para>
                /// 	<para><paramref name="stream"/> is null (Nothing in Visual Basic).</para>
                /// </exception>
                public Image Decode(Stream stream)
                {
                    _stream = stream;

                    try
                    {
                        ReadFileHeader();
                        ReadInfoHeader();

                        int colorMapSize = -1;

                        if (_infoHeader.ClrUsed == 0)
                        {
                            if (_infoHeader.BitsPerPixel == 1 ||
                                _infoHeader.BitsPerPixel == 4 ||
                                _infoHeader.BitsPerPixel == 8)
                            {
                                colorMapSize = (int)Math.Pow(2, _infoHeader.BitsPerPixel) * 4;
                            }
                        }
                        else
                        {
                            colorMapSize = _infoHeader.ClrUsed * 4;
                        }

                        byte[] palette = null;
                        if (colorMapSize > 0)
                        {
                            palette = new byte[colorMapSize];

                            _stream.Read(palette, 0, colorMapSize);
                        }

                        byte[] imageData = new byte[_infoHeader.Width * _infoHeader.Height * 4];

                        switch (_infoHeader.Compression)
                        {
                            case BmpCompression.RGB:
                                if (_infoHeader.HeaderSize != 40)
                                {
                                    throw new Exception("Header Size value '" + _infoHeader.HeaderSize.ToString() + "' is not valid.");
                                }

                                if (_infoHeader.BitsPerPixel == 32)
                                {
                                    ReadRgb32(imageData, _infoHeader.Width, _infoHeader.Height);
                                }
                                else if (_infoHeader.BitsPerPixel == 24)
                                {
                                    ReadRgb24(imageData, _infoHeader.Width, _infoHeader.Height);
                                }
                                else if (_infoHeader.BitsPerPixel == 16)
                                {
                                    ReadRgb16(imageData, _infoHeader.Width, _infoHeader.Height);
                                }
                                else if (_infoHeader.BitsPerPixel <= 8)
                                {
                                    ReadRgbPalette(imageData, palette,
                                        _infoHeader.ImageSize,
                                        _infoHeader.Width,
                                        _infoHeader.Height,
                                        _infoHeader.BitsPerPixel);
                                }
                                break;
                            default:
                                throw new NotSupportedException("Does not support this kind of bitmap files.");
                        }

                        Image i = new Image(_infoHeader.Width, _infoHeader.Height);
                        int indx = 0;
                        byte r, g, b, a;
                        for (uint y = 0; y < i.Height; y++)
                        {
                            for (uint x = 0; x < i.Width; x++)
                            {
                                r = imageData[indx];
                                indx++;
                                g = imageData[indx];
                                indx++;
                                b = imageData[indx];
                                indx++;
                                a = imageData[indx];
                                indx++;
                                i.SetPixel(x, y, new Pixel(r, g, b, a));
                            }
                        }
                        imageData = null;
                        System.GC.Collect();
                        return i;
                    }
                    catch (IndexOutOfRangeException e)
                    {
                        throw new Exception("Bitmap does not have a valid format.", e);
                    }
                }
Esempio n. 15
0
        public void Image_Compare()
        {
            Map m1 = new Map(256, 256);
            Map m2 = new Map(256, 256);
            Image i1 = new Image(256, 256);
            Image i2 = new Image(256, 256);
            Assert.AreEqual(i1.Compare(i2), 0);

            i1.SetPixel(0, 0, new Color("white"));
            Assert.AreEqual(i1.Compare(i2), 1);

            m1.Background = new Color("black");
            m1.Render(i1);
            Assert.AreEqual(i1.Width() * i1.Height(), i1.Compare(i2));

            //test options
            m1.Background= new Color(100, 100, 100, 255);
            m1.Render(i1);
            i2 = new Image(256, 256);
            m2.Background = new Color(100,100,100,100);
            m2.Render(i2);
            Dictionary<string, object> options;
            options = new Dictionary<string, object> { { "Alpha", false } };
            Assert.AreEqual(i1.Compare(i2, options), 0);

            m1.Background = new Color(255, 255, 255);
            m1.Render(i1);
            m2.Background = new Color(255, 255, 255);
            m2.Render(i2);
            i2.SetPixel(0, 0, new Color(250, 250, 250));
            options = new Dictionary<string, object> { { "Threshold", 5 } };
            Assert.AreEqual(i1.Compare(i2, options), 0);
        }
        // what we need to do is to render the splatted texture in ortho mode with lighting off
        // or normals off (to be tested)
        // then to export the generated bitmap
        // viewport should be set to heightmapwidth x heightmapheight
        public void Export(string filepath)
        {
            Terrain terrain = Terrain.GetInstance();
            int picturewidth = terrain.MapWidth * Terrain.SquareSize;
            int pictureheight = terrain.MapHeight * Terrain.SquareSize;
            LogFile.GetInstance().WriteLine("Export to " + filepath + " picturewidth " + picturewidth + " pictureheight: " + pictureheight);
            //int windowwidth = RendererSdl.GetInstance().WindowWidth;
            //int windowheight = RendererSdl.GetInstance().WindowHeight;
            int windowwidth = 256;
            int windowheight = 256;

            Gl.glViewport(0, 0, windowwidth, windowheight);

            byte[] buffer = new byte[windowwidth * windowheight * 4];
            //System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap( picturewidth, pictureheight );
            //byte[] imagedata = new byte[picturewidth * pictureheight * 4];
            Image image = new Image(picturewidth, pictureheight);

            List<RendererPass> rendererpasses = new List<RendererPass>();
            bool multipass = true; // force multipass for now for simplicity
            int maxtexels = RendererSdl.GetInstance().MaxTexelUnits;
            if (multipass)
            {
                for (int i = 0; i < terrain.texturestages.Count; i++)
                {
                    MapTextureStage maptexturestage = terrain.texturestages[i];
                    int numtexturestagesrequired = maptexturestage.NumTextureStagesRequired;
                    if (numtexturestagesrequired > 0) // exclude Nops
                    {
                        RendererPass rendererpass = new RendererPass(maxtexels);
                        for (int j = 0; j < maptexturestage.NumTextureStagesRequired; j++)
                        {
                            rendererpass.AddStage(new RendererTextureStage(maptexturestage, j, true, picturewidth, pictureheight));
                        }
                        rendererpasses.Add(rendererpass);
                    }
                }
            }

            GraphicsHelperGl g = new GraphicsHelperGl();

            Gl.glMatrixMode(Gl.GL_PROJECTION);
            Gl.glPushMatrix();
            Gl.glLoadIdentity();
            Gl.glOrtho(0, windowwidth, windowheight, 0, -1, 1);

            Gl.glMatrixMode(Gl.GL_MODELVIEW);
            Gl.glPushMatrix();
            Gl.glLoadIdentity();

            Gl.glDisable(Gl.GL_CULL_FACE);
            Gl.glDisable(Gl.GL_LIGHTING);

            g.EnableBlendSrcAlpha();
            Gl.glDepthFunc( Gl.GL_LEQUAL );

            for (int chunkx = 0; chunkx < Math.Ceiling((double)picturewidth / windowwidth); chunkx++)
            {
                for (int chunky = 0; chunky < Math.Ceiling((double)pictureheight / windowheight); chunky++)
                {
                    Console.WriteLine("chunkx " + chunkx + " chunky " + chunky);

                    Gl.glClear(Gl.GL_COLOR_BUFFER_BIT | Gl.GL_DEPTH_BUFFER_BIT);		// Clear The Screen And Depth Buffer

                    foreach (RendererPass rendererpass in rendererpasses)
                    {
                        rendererpass.Apply();

                        Gl.glBegin(Gl.GL_QUADS);

                        double ul = (chunkx * windowwidth);
                        double ur = (chunkx * windowwidth + windowwidth);
                        double vt = (chunky * windowheight);
                        double vb = (chunky * windowheight + windowheight);
                        Gl.glTexCoord2d( ul,vt );
                        Gl.glMultiTexCoord2dARB(Gl.GL_TEXTURE1_ARB,ul, vt);
                        Gl.glVertex2i(0, 0);

                        Gl.glTexCoord2d( ul,vb );
                        Gl.glMultiTexCoord2dARB(Gl.GL_TEXTURE1_ARB,ul, vb);
                        Gl.glVertex2i(0, windowheight);

                        Gl.glTexCoord2d( ur,vb );
                        Gl.glMultiTexCoord2dARB(Gl.GL_TEXTURE1_ARB,ur, vb);
                        Gl.glVertex2i(windowwidth, windowheight);

                        Gl.glTexCoord2d( ur,vt );
                        Gl.glMultiTexCoord2dARB(Gl.GL_TEXTURE1_ARB,ur, vt);
                        Gl.glVertex2i(windowwidth, 0);

                        Gl.glEnd();
                    }

                    IntPtr ptr = Marshal.AllocHGlobal(windowwidth * windowheight * 4);
                    Gl.glReadPixels(0, 0, windowwidth, windowheight, Gl.GL_RGBA, Gl.GL_UNSIGNED_BYTE, ptr);
                    Marshal.Copy(ptr, buffer, 0, windowwidth * windowheight * 4);
                    Marshal.FreeHGlobal(ptr);

                    for (int x = 0; x < windowwidth; x++)
                    {
                        for (int y = 0; y < windowheight; y++)
                        {
                            if ((chunky * windowheight + y < pictureheight) &&
                                (chunkx * windowwidth + x < picturewidth))
                            {
                                int pixeloffset = (windowheight - y - 1) * windowwidth * 4 + x * 4;
                                //bitmap.SetPixel(x + chunkx * windowwidth, y + chunky * windowheight, System.Drawing.Color.FromArgb(buffer[pixeloffset + 0],
                                    //buffer[pixeloffset + 1], buffer[pixeloffset + 2]));
                                image.SetPixel(x + chunkx * windowwidth, y + chunky * windowheight,
                                    buffer[pixeloffset + 0],
                                    buffer[pixeloffset + 1],
                                    buffer[pixeloffset + 2],
                                    255
                                    );
                            }
                        }
                    }
                }
            }
            if (File.Exists(filepath))
            {
                File.Delete(filepath);
            }
            image.Save(filepath);
            //DevIL.DevIL.SaveBitmap( filepath, bitmap);

            Gl.glPopMatrix();
            Gl.glMatrixMode(Gl.GL_PROJECTION);
            Gl.glPopMatrix();
            Gl.glMatrixMode(Gl.GL_MODELVIEW);

            Gl.glEnable(Gl.GL_LIGHTING);

            g.ActiveTexture(1);
            g.DisableTexture2d();
            g.SetTextureScale(1);
            g.ActiveTexture(0);
            g.SetTextureScale(1);

            Gl.glEnable(Gl.GL_CULL_FACE);
            Gl.glEnable(Gl.GL_LIGHTING);
            Gl.glDisable(Gl.GL_BLEND);

            g.EnableModulate();

            Gl.glViewport(0, 0, RendererSdl.GetInstance().OuterWindowWidth, RendererSdl.GetInstance().OuterWindowHeight);
            g.CheckError();

            MainUI.GetInstance().uiwindow.InfoMessage("Exported blended terrain texture to " + filepath);
        }
Esempio n. 17
0
            private void ReadFrameColors(byte[] indices, byte[] colorTable, GifImageDescriptor descriptor)
            {
                int imageWidth = _logicalScreenDescriptor.Width;
                int imageHeight = _logicalScreenDescriptor.Height;

                if (_currentFrame == null)
                {
                    _currentFrame = new byte[imageWidth * imageHeight * 4];
                }

                byte[] lastFrame = null;

                if (_graphicsControl != null &&
                    _graphicsControl.DisposalMethod == DisposalMethod.RestoreToPrevious)
                {
                    lastFrame = new byte[imageWidth * imageHeight * 4];

                    Array.Copy(_currentFrame, lastFrame, lastFrame.Length);
                }

                int offset = 0, i = 0, index = -1;

                int iPass = 0; // the interlace pass
                int iInc = 8; // the interlacing line increment
                int iY = 0; // the current interlaced line
                int writeY = 0; // the target y offset to write to

                for (int y = descriptor.Top; y < descriptor.Top + descriptor.Height; y++)
                {
                    // Check if this image is interlaced.
                    if (descriptor.InterlaceFlag)
                    {
                        // If so then we read lines at predetermined offsets.
                        // When an entire image height worth of offset lines has been read we consider this a pass.
                        // With each pass the number of offset lines changes and the starting line changes.
                        if (iY >= descriptor.Height)
                        {
                            iPass++;
                            switch (iPass)
                            {
                                case 1:
                                    iY = 4;
                                    break;
                                case 2:
                                    iY = 2;
                                    iInc = 4;
                                    break;
                                case 3:
                                    iY = 1;
                                    iInc = 2;
                                    break;
                            }
                        }

                        writeY = iY + descriptor.Top;

                        iY += iInc;
                    }
                    else
                    {
                        writeY = y;
                    }

                    for (int x = descriptor.Left; x < descriptor.Left + descriptor.Width; x++)
                    {
                        offset = writeY * imageWidth + x;

                        index = indices[i];

                        if (_graphicsControl == null ||
                            _graphicsControl.TransparencyFlag == false ||
                            _graphicsControl.TransparencyIndex != index)
                        {
                            _currentFrame[offset * 4 + 0] = colorTable[index * 3 + 0];
                            _currentFrame[offset * 4 + 1] = colorTable[index * 3 + 1];
                            _currentFrame[offset * 4 + 2] = colorTable[index * 3 + 2];
                            _currentFrame[offset * 4 + 3] = (byte)255;
                        }

                        i++;
                    }
                }

                byte[] pixels = new byte[imageWidth * imageHeight * 4];

                Array.Copy(_currentFrame, pixels, pixels.Length);
                _currentFrame = new byte[imageWidth * imageHeight * 4];
                Image frame = new Image(imageWidth, imageHeight);
                
                int indx = 0;
                byte r, g, b, a;
                for (uint y = 0; y < frame.Height; y++)
                {
                    for (uint x = 0; x < frame.Width; x++)
                    {
                        r = pixels[indx];
                        indx++;
                        g = pixels[indx];
                        indx++;
                        b = pixels[indx];
                        indx++;
                        a = pixels[indx];
                        indx++;
                        frame.SetPixel(x, y, new Pixel(r, g, b, a));
                    }
                }
                pixels = null;
                System.GC.Collect();
                _image.AddFrame(frame);


                if (_graphicsControl != null)
                {
                    if (_graphicsControl.DelayTime > 0)
                    {
                        _image.TimePerFrame = _graphicsControl.DelayTime;
                    }

                    if (_graphicsControl.DisposalMethod == DisposalMethod.RestoreToBackground)
                    {
                        Image im = new Image(imageWidth, imageHeight);
                        im.Clear(new Pixel(true));
                        _image.AddFrame(im);
                        _image.Loop = false;
                        
                    }
                    else if (_graphicsControl.DisposalMethod == DisposalMethod.RestoreToPrevious)
                    {
                        _image.Loop = true;
                    }
                }
            }