Exemplo n.º 1
0
 static public CodeDecoder           Decode(byte[] abImage)
 {
    PngReader xPng=new PngReader( new MemoryStream( abImage ) );
    //
    ImageLines xLines=xPng.ReadRowsByte();
    //
    byte[,] abData=new byte[xLines.ImgInfo.Cols, xLines.ImgInfo.Rows];
    //
    int iBits = xLines.ImgInfo.BitspPixel;
    int iChannels = xLines.ImgInfo.Channels;
    //
    if ( iBits==1 )
    {
       for (int y = 0; y < xLines.ImgInfo.Rows; y++)
          for (int x = 0; x < xLines.ImgInfo.Cols/8; x++)
          {
             byte b= xLines.ScanlinesB[y][x];
             //
             for (int a=0; a<8; a++)
                abData[x*8+a, y] = (byte)( ( (b & (1<<(7-a))) !=0 ) ? 255 : 0 );
          }
    }
    else if( iBits==8 )
    {
       int iC=0;
       for (int y = 0; y < xLines.ImgInfo.Rows; y++)
          for (int x = 0; x < xLines.ImgInfo.Cols; x++, iC+=iChannels)
             abData[x,y]=xLines.ScanlinesB[y][iC];
    }
    //
    return Decode( abData , xLines.ImgInfo.Cols , xLines.ImgInfo.Rows);
 }
Exemplo n.º 2
0
        /// <summary>
        /// Saves the PNGFile to disk.
        /// </summary>
        /// <param name="path">Output path for the PNGFile.</param>
        public void SaveAs(string path)
        {
            PngReader reader = FileHelper.CreatePngReader(originalFile);
            PngWriter writer = FileHelper.CreatePngWriter(path, reader.ImgInfo, true);

            writer.CopyChunksFirst(reader, ChunkCopyBehaviour.COPY_ALL_SAFE);

            for (var x = 0; x < reader.ImgInfo.Rows; x++)
            {
                ImageLine line = reader.ReadRowByte(x);
                for (var y = 0; y < line.ScanlineB.Length; y += reader.ImgInfo.BytesPixel)
                {
                    line.ScanlineB[y]     = lines[x][y / reader.ImgInfo.BytesPixel].Red;
                    line.ScanlineB[y + 1] = lines[x][(y + 1) / reader.ImgInfo.BytesPixel].Green;
                    line.ScanlineB[y + 2] = lines[x][(y + 2) / reader.ImgInfo.BytesPixel].Blue;
                    if (reader.ImgInfo.Alpha)
                    {
                        line.ScanlineB[y + 3] = lines[x][(y + 3) / reader.ImgInfo.BytesPixel].Alpha;
                    }
                }
                writer.WriteRow(line, x);
            }
            writer.CopyChunksLast(reader, ChunkCopyBehaviour.COPY_ALL_SAFE);
            writer.End();
            reader.End();
        }
Exemplo n.º 3
0
        public static void testEqual(String image1, String image2)
        {
            PngReader png1 = FileHelper.CreatePngReader(image1);

            PngHelperInternal.InitCrcForTests(png1);
            PngReader png2 = FileHelper.CreatePngReader(image2);

            PngHelperInternal.InitCrcForTests(png2);
            if (png1.IsInterlaced() != png2.IsInterlaced())
            {
                fatalError("Cannot compare, one is interlaced, the other not:" + png1 + " " + png2,
                           png1, png2);
            }
            if (!png1.ImgInfo.Equals(png2.ImgInfo))
            {
                fatalError("Image are of different type", png1, png2);
            }
            png1.ReadRow(png1.ImgInfo.Rows - 1);
            png2.ReadRow(png2.ImgInfo.Rows - 1);
            png1.End();
            png2.End();
            long crc1 = PngHelperInternal.GetCrctestVal(png1);
            long crc2 = PngHelperInternal.GetCrctestVal(png2);

            if (crc1 != crc2)
            {
                fatalError("different crcs " + image1 + "=" + crc1 + " " + image2 + "=" + crc2,
                           png1, png2);
            }
        }
Exemplo n.º 4
0
        public void LoadFromP8PNG(Stream stream)
        {
            PngReader reader = new PngReader(stream);

            if (!validatePNG(reader.ImgInfo))
            {
                throw new BadImageFormatException("Bad Cart");
            }

            int offset = 0;

            for (int row = 0; row < reader.ImgInfo.Rows && offset < CART_SIZE; row++)
            {
                ImageLine line = reader.ReadRowInt(row);
                for (int col = 0; col < line.ImgInfo.Cols && offset < CART_SIZE; col++)
                {
                    rom[offset] = decodeBytes(line.Scanline, col * 4);
                    offset     += 1;
                }
            }

            Version = rom[0x8000];
            Build   = (rom[0x8001] << 24) + (rom[0x8002] << 16) + (rom[0x8003] << 8) + rom[0x8004];

            /*
             * Debug.Log(rom[0]);
             * Debug.Log(rom[1]);
             * Debug.Log(rom[2]);
             * Debug.Log(rom[3]);
             */
            reader.End();
        }
Exemplo n.º 5
0
        public static void testWrite(string src, string target)
        {
            // for writing is not necesary to register
            DummyClass c = new DummyClass();

            c.name = "Hernán";
            c.age  = 45;

            PngReader pngr = FileHelper.CreatePngReader(src);
            PngWriter pngw = FileHelper.CreatePngWriter(target, pngr.ImgInfo, true);

            pngw.CopyChunksFirst(pngr, ChunkCopyBehaviour.COPY_ALL_SAFE);
            PngChunkSERI mychunk = new PngChunkSERI(pngw.ImgInfo);

            mychunk.SetObj(c);
            mychunk.Priority = true; // if we want it to be written as soon as possible
            pngw.GetChunksList().Queue(mychunk);
            for (int row = 0; row < pngr.ImgInfo.Rows; row++)
            {
                ImageLine l1 = pngr.ReadRow(row);
                pngw.WriteRow(l1, row);
            }
            pngw.CopyChunksLast(pngr, ChunkCopyBehaviour.COPY_ALL);
            pngr.End();
            pngw.End();
            Console.Out.WriteLine("Done. Writen : " + target);
        }
Exemplo n.º 6
0
    static public FullColorImage LoadPNG(string _path, PalettizedImageConfig _config)
    {
        PngReader pngr = FileHelper.CreatePngReader(_path);

        if (pngr.ImgInfo.Indexed)
        {
            Debug.LogException(new UnityException("Image is indexed"));
            return(null);
        }

        Debug.Log("Image BPP=" + pngr.ImgInfo.BitspPixel);

        /*
         * PngChunkPLTE palette = pngr.GetMetadata().GetPLTE();
         *
         * PalettizedImage image = new PalettizedImage( pngr.ImgInfo.Cols, pngr.ImgInfo.Rows, palette.GetNentries());
         * image.SetConfig( _config );
         * image.m_fileName = System.IO.Path.GetFileNameWithoutExtension( _path );
         *
         * image.ReadPalette( palette );
         * image.ReadImage( pngr );
         *
         * return image;
         */
        return(null);
    }
Exemplo n.º 7
0
        private static void additionalTestInterlaced(string orig, string origni)
        {
            // tests also read/write in packed format
            PngReader pngr = FileHelper.CreatePngReader(orig);
            string    copy = TestsHelper.addSuffixToName(orig, "_icopy");

            pngr.SetUnpackedMode(false);
            PngWriter pngw = FileHelper.CreatePngWriter(copy, pngr.ImgInfo, true);

            pngw.CopyChunksFirst(pngr, ChunkCopyBehaviour.COPY_ALL);
            pngw.SetUseUnPackedMode(false);
            Random random  = new Random();
            bool   useByte = random.NextDouble() > 0.5 && pngr.ImgInfo.BitDepth < 16;

            for (int row = 0; row < pngr.ImgInfo.Rows; row++)
            {
                if (useByte)
                {
                    ImageLine line = pngr.ReadRowByte(row);
                    pngw.WriteRow(line, row);
                }
                else
                {
                    ImageLine line = pngr.ReadRowInt(row);
                    pngw.WriteRow(line, row);
                }
            }
            pngr.End();
            pngw.End();
            TestsHelper.testEqual(copy, origni);
            System.IO.File.Delete(copy);
        }
Exemplo n.º 8
0
        private void btnOpen_Click(object sender, RoutedEventArgs e)
        {
            CommonOpenFileDialog openDialog = new CommonOpenFileDialog();

            openDialog.ShowPlacesList            = true;
            openDialog.Multiselect               = false;
            openDialog.IsFolderPicker            = false;
            openDialog.AddToMostRecentlyUsedList = true;
            openDialog.Filters.Add(new CommonFileDialogFilter("PNG images", "*.png"));
            if (openDialog.ShowDialog(this) == CommonFileDialogResult.Ok)
            {
                soureFilePath = openDialog.FileName;
                // get comment meta
                using (FileStream fileStream = new FileStream(soureFilePath, FileMode.Open, FileAccess.Read)) {
                    pngReader = new PngReader(fileStream);
                    // 参考自Hjg.Pngcs的SampleCustomChunk项目
                    // get last line: this forces loading all chunks
                    pngReader.ReadChunksOnly();
                    tblkComment.Text = pngReader.GetMetadata().GetTxtForKey(Key_SemanticInfo);
                    pngReader.End();
                    fileStream.Close();
                }

                image.BeginInit();
                image.Source = new BitmapImage(new Uri(soureFilePath));
                image.EndInit();
            }
        }
        public static void doit(String orig)
        {
            string copy = TestsHelper.addSuffixToName(orig, "_tc");

            PngReader pngr = FileHelper.CreatePngReader(orig);

            if (!pngr.ImgInfo.Indexed)
            {
                throw new Exception("Not indexed image");
            }
            PngChunkPLTE plte  = pngr.GetMetadata().GetPLTE();
            PngChunkTRNS trns  = pngr.GetMetadata().GetTRNS(); // transparency metadata, can be null
            bool         alpha = trns != null;
            ImageInfo    im2   = new ImageInfo(pngr.ImgInfo.Cols, pngr.ImgInfo.Rows, 8, alpha);
            PngWriter    pngw  = FileHelper.CreatePngWriter(copy, im2, true);

            pngw.CopyChunksFirst(pngr, ChunkCopyBehaviour.COPY_ALL_SAFE);
            int[] buf = null;
            for (int row = 0; row < pngr.ImgInfo.Rows; row++)
            {
                ImageLine line = pngr.ReadRowInt(row);
                buf = ImageLineHelper.Palette2rgb(line, plte, trns, buf);
                pngw.WriteRowInt(buf, row);
            }
            pngw.CopyChunksLast(pngr, ChunkCopyBehaviour.COPY_ALL_SAFE);
            pngr.End();
            pngw.End();
            Console.WriteLine("True color: " + copy);
        }
Exemplo n.º 10
0
        private IEnumerable <Bitmap> ReadRowChunk(PngReader reader, int chunkIndex)
        {
            if (!reader.ImgInfo.Indexed)
            {
                throw new ArgumentException("Only indexed color PNGs are supported.");
            }

            var lines = new byte[32][];
            var pal   = reader.GetMetadata().GetPLTE();

            for (var i = 0; i < 32; i++)
            {
                lines[i] = reader.ReadRowByte(
                    new byte[reader.ImgInfo.Cols],
                    (chunkIndex * 32) + i);
            }

            var bitmapsPerRow = reader.ImgInfo.Cols / 32;

            for (var i = 0; i < bitmapsPerRow; i++)
            {
                var bmp = ReadBitmap(i, lines, pal);
                this.tileCache.GetOrAddBitmap(bmp);
                yield return(bmp);
            }
        }
Exemplo n.º 11
0
        public static void addMetadata(String origFilename, Dictionary <string, string> data)
        {
            String    destFilename = "tmp.png";
            PngReader pngr         = FileHelper.CreatePngReader(origFilename);                     // or you can use the constructor
            PngWriter pngw         = FileHelper.CreatePngWriter(destFilename, pngr.ImgInfo, true); // idem
            //Console.WriteLine(pngr.ToString()); // just information
            int chunkBehav = ChunkCopyBehaviour.COPY_ALL_SAFE;                                     // tell to copy all 'safe' chunks

            pngw.CopyChunksFirst(pngr, chunkBehav);                                                // copy some metadata from reader
            foreach (string key in data.Keys)
            {
                PngChunk chunk = pngw.GetMetadata().SetText(key, data[key]);
                chunk.Priority = true;
            }

            int channels = pngr.ImgInfo.Channels;

            if (channels < 3)
            {
                throw new Exception("This example works only with RGB/RGBA images");
            }
            for (int row = 0; row < pngr.ImgInfo.Rows; row++)
            {
                ImageLine l1 = pngr.ReadRowInt(row);     // format: RGBRGB... or RGBARGBA...
                pngw.WriteRow(l1, row);
            }
            pngw.CopyChunksLast(pngr, chunkBehav); // metadata after the image pixels? can happen
            pngw.End();                            // dont forget this
            pngr.End();
            File.Delete(origFilename);
            File.Move(destFilename, origFilename);
        }
Exemplo n.º 12
0
        public static void DecreaseRed(String origFilename, String destFilename)
        {
            if (origFilename.Equals(destFilename))
            {
                throw new PngjException("input and output file cannot coincide");
            }
            PngReader pngr = FileHelper.CreatePngReader(origFilename);
            PngWriter pngw = FileHelper.CreatePngWriter(destFilename, pngr.ImgInfo, true);

            Console.WriteLine(pngr.ToString());
            int chunkBehav = ChunkCopyBehaviour.COPY_ALL_SAFE; // copy all 'safe' chunks

            // this can copy some metadata from reader
            pngw.CopyChunksFirst(pngr, chunkBehav);
            int channels = pngr.ImgInfo.Channels;

            if (channels < 3)
            {
                throw new Exception("This method is for RGB/RGBA images");
            }
            for (int row = 0; row < pngr.ImgInfo.Rows; row++)
            {
                ImageLine l1 = pngr.ReadRow(row);
                for (int j = 0; j < pngr.ImgInfo.Cols; j++)
                {
                    l1.Scanline[j * channels] /= 2;
                }
                pngw.WriteRow(l1, row);
            }
            // just in case some new metadata has been read after the image
            pngw.CopyChunksLast(pngr, chunkBehav);
            pngw.End();
        }
Exemplo n.º 13
0
        public static void tile(String orig, String dest, int factor)
        {
            if (orig.Equals(dest))
            {
                throw new PngjException("input and output file cannot coincide");
            }
            if (factor < 2 || factor > 100)
            {
                throw new PngjException("bad factor ");
            }
            PngReader pngr = FileHelper.CreatePngReader(orig);
            var       x    = pngr.ImgInfo;
            PngWriter pngw = FileHelper.CreatePngWriter(dest, pngr.ImgInfo, true);

            pngr.SetUnpackedMode(true);    // we dont want to do the unpacking ourselves, we want a sample per array element
            pngw.SetUseUnPackedMode(true); // not really necesary here, as we pass the ImageLine, but anyway...
            pngw.CopyChunksFirst(pngr, ChunkCopyBehaviour.COPY_ALL_SAFE);
            for (int row = 0; row < pngr.ImgInfo.Rows; row++)
            {
                ImageLine l1 = pngr.ReadRowInt(row);
                mirrorLineInt(pngr.ImgInfo, l1.Scanline);
                pngw.WriteRow(l1, row);
            }
            pngw.CopyChunksLast(pngr, ChunkCopyBehaviour.COPY_ALL_SAFE);
            pngw.End();
        }
Exemplo n.º 14
0
        public sprite_data load_sprite_png(string _filename, string _name, bool _apply_palette, bool _crop_image, int _palette_slot)
        {
            PngReader png_reader = FileHelper.CreatePngReader(_filename);

            try
            {
                if (!png_reader.ImgInfo.Indexed)
                {
                    throw new Exception(_filename + "\n\nNot indexed image!");
                }

                if (png_reader.IsInterlaced())
                {
                    throw new Exception(_filename + "\n\nOnly non interlaced .PNG images are supported!");
                }

//				if( ( png_reader.ImgInfo.Cols & 0x07 ) != 0 || ( png_reader.ImgInfo.Rows & 0x07 ) != 0 )
//				{
//					png_reader.End();
//					throw new Exception( _filename + "\n\nThe image size must be a multiple of 8 !" );
//				}

//				if( ( ( png_reader.ImgInfo.Cols >> 3 ) * ( png_reader.ImgInfo.Rows >> 3 ) ) > utils.CONST_CHR_BANK_MAX_SPRITES_CNT )
//				{
//					png_reader.End();
//					throw new Exception( _filename + "\n\nThe imported image contains more than " + utils.CONST_CHR_BANK_MAX_SPRITES_CNT + " CHRs!" );
//				}

#if DEF_NES
                if (png_reader.GetMetadata().GetPLTE().MinBitDepth() != 2)
                {
                    throw new Exception(_filename + "\n\nThe PNG image must have a 4 colors palette!");
                }
#elif DEF_SMS || DEF_PCE
                int img_bit_depth = png_reader.GetMetadata().GetPLTE().MinBitDepth();

                if (img_bit_depth != 4 && img_bit_depth != 2)
                {
                    throw new Exception(_filename + "\n\nThe PNG image must have a 4 or 2 bpp color depth!");
                }

                if (png_reader.GetMetadata().GetPLTE().GetNentries() > 16)
                {
                    throw new Exception(_filename + "\n\nThe PNG image must have a 16 or 4 colors palette!");
                }
#else
                ...
#endif
                sprite_params spr_params = m_CHR_data_storage.create(png_reader, _apply_palette, _crop_image, _palette_slot);

                sprite_data spr = new sprite_data(_name);
                spr.setup(spr_params);

                spr.update_dimensions();

                png_reader.End();

                return(spr);
            }
Exemplo n.º 15
0
        public sprite_params create(PngReader _png_reader, bool _apply_palette, bool _crop_image, int _palette_slot)
        {
            CHR_data_group chr_data = new CHR_data_group();

            add(chr_data);

            return(chr_data.setup(_png_reader, _apply_palette, _crop_image, _palette_slot));
        }
Exemplo n.º 16
0
 public static void fatalError(String s, PngReader png1)
 {
     try {
         png1.End();
     } catch (Exception) {
     }
     throw new PngjException(s);
 }
Exemplo n.º 17
0
        //---------------------------------------------------------------------
        public bool load(byte[] data)
        {
            MemoryStream ms = new MemoryStream(data);

            mPngReader = new PngReader(ms);

            return(mPngReader != null);
        }
Exemplo n.º 18
0
        static void testmirror(string orig, string origni, string truecolor)
        {
            string mirror = TestsHelper.addSuffixToName(orig, "_mirror");
            string recov  = TestsHelper.addSuffixToName(orig, "_recov");
            long   crc0   = 0;
            bool   interlaced;
            bool   palete;

            {
                PngReader pngr = FileHelper.CreatePngReader(orig);
                palete = pngr.ImgInfo.Indexed;
                PngHelperInternal.InitCrcForTests(pngr);
                pngr.SetUnpackedMode(true);
                interlaced = pngr.IsInterlaced();
                PngWriter pngw = FileHelper.CreatePngWriter(mirror, pngr.ImgInfo, true);
                pngw.SetFilterType(FilterType.FILTER_CYCLIC); // just to test all filters
                pngw.CopyChunksFirst(pngr, ChunkCopyBehaviour.COPY_ALL);
                pngw.SetUseUnPackedMode(true);
                for (int row = 0; row < pngr.ImgInfo.Rows; row++)
                {
                    ImageLine line = pngr.ReadRowInt(row);
                    mirrorLine(line);
                    pngw.WriteRow(line, row);
                }
                pngr.End();
                crc0 = PngHelperInternal.GetCrctestVal(pngr);
                pngw.CopyChunksFirst(pngr, ChunkCopyBehaviour.COPY_ALL);
                pngw.End();
            }
            // mirror again, now with BYTE (if depth<16) and loading all rows
            {
                PngReader pngr2 = FileHelper.CreatePngReader(mirror);
                pngr2.SetUnpackedMode(true);
                PngWriter pngw = FileHelper.CreatePngWriter(recov, pngr2.ImgInfo, true);
                pngw.SetFilterType(FilterType.FILTER_AGGRESSIVE);
                pngw.CopyChunksFirst(pngr2, ChunkCopyBehaviour.COPY_ALL);
                pngw.SetUseUnPackedMode(true);
                ImageLines lines = pngr2.ImgInfo.BitDepth < 16 ? pngr2.ReadRowsByte() : pngr2
                                   .ReadRowsInt();
                for (int row = 0; row < pngr2.ImgInfo.Rows; row++)
                {
                    ImageLine line = lines.GetImageLineAtMatrixRow(row);
                    mirrorLine(line);
                    pngw.WriteRow(line, row);
                }
                pngr2.End();
                pngw.End();
            }
            // now check
            if (orig[11] != 'i')
            {
                TestsHelper.testCrcEquals(recov, crc0);
            }
            //if (interlaced)
            //    additionalTestInterlaced(orig, origni);
            //if (palete && System.IO.File.Exists(truecolor))
            //    additionalTestPalette(orig, truecolor);
        }
Exemplo n.º 19
0
        public static void showChunks(String file)
        {
            PngReader pngr = FileHelper.CreatePngReader(file);

            pngr.MaxTotalBytesRead = 1024 * 1024 * 1024L * 3; // 3Gb!
            pngr.ReadSkippingAllRows();
            Console.Out.WriteLine(pngr.ToString());
            Console.Out.WriteLine(pngr.GetChunksList().ToStringFull());
        }
Exemplo n.º 20
0
        public string getMetadata(string file, string key)
        {
            PngReader pngr = FileHelper.CreatePngReader(file);
            //pngr.MaxTotalBytesRead = 1024 * 1024 * 1024L * 3; // 3Gb!
            //pngr.ReadSkippingAllRows();
            string data = pngr.GetMetadata().GetTxtForKey(key);

            pngr.End();
            return(data);;
        }
        /// <summary> Create Color[] from PNG file, async </summary>
        public static async Task <ReadColorsResult> ReadColorsAsync
        (
            string filePath
        )
        {
            ReadColorsResult results = new ReadColorsResult {
                pixels = null,
                width  = -1,
                height = -1,
                textureFormatInfered = 0
            };
            PngReader reader = null;

            try
            {
                reader = FileHelper.CreatePngReader(filePath);
                var info = reader.ImgInfo;
                results.height = info.Rows;
                results.width  = info.Cols;
                results.pixels = new Color[results.width * results.height];

                int channels = info.Channels;
                int bitDepth = info.BitDepth;

                //select appropriate texture format:
                results.textureFormatInfered = GetTextureFormat(bitDepth, channels, info.Indexed);

                //create pixel array:
                await Task.Run(() => {
                    ReadSamples(reader, results);
                });
            }
            catch (System.Exception ex)
            {
                Debug.LogException(ex);
                if (results.pixels == null)
                {
                    results.width  = 2;
                    results.height = 2;
                    results.pixels = new Color[results.width * results.height];
                }
                if (results.textureFormatInfered == 0)
                {
                    results.textureFormatInfered = TextureFormat.RGBA32;
                }
            }
            finally
            {
                if (reader != null)
                {
                    reader.Dispose();
                }
            }
            return(results);
        }
Exemplo n.º 22
0
        static int LoadTexture_Lua(IntPtr L)
        {
            var path = Api.lua_tostring(L, 1);

            try
            {
                var           bytes = File.ReadAllBytes(Path.Combine(Application.persistentDataPath, path));
                TextureFormat fmt = TextureFormat.ARGB32;
                bool          hasOffset = false;
                long          offx = 0, offy = 0, units = 0;
                if (path.EndsWith(".jpg"))
                {
                    fmt = TextureFormat.RGB24;
                }
                else if (path.EndsWith(".png"))
                {
                    var r         = new PngReader(new MemoryStream(bytes));
                    var chunkList = r.GetChunksList();
                    var offChunk  = chunkList.GetById1(PngChunkOFFS.ID) as PngChunkOFFS;
                    if (offChunk != null)
                    {
                        hasOffset = true;
                        units     = offChunk.GetUnits();
                        offx      = offChunk.GetPosX();
                        offy      = offChunk.GetPosY();
                    }
                }
                var tex = new Texture2D(2, 2, fmt, false, true);
                if (tex.LoadImage(bytes))
                {
                    lua.Lua.PushObjectInternal(L, tex);
                    var retCount = 1;
                    if (hasOffset)
                    {
                        Api.lua_pushinteger(L, offx);
                        Api.lua_pushinteger(L, offy);
                        Api.lua_pushinteger(L, units);
                        retCount += 3;
                    }
                    return(retCount);
                }
                else
                {
                    Api.lua_pushnil(L);
                    Api.lua_pushstring(L, "err LoadImage from " + path);
                    return(2);
                }
            }
            catch (Exception e)
            {
                Api.lua_pushnil(L);
                Api.lua_pushstring(L, e.Message);
                return(2);
            }
        }
Exemplo n.º 23
0
        private RawTexture loadPng(Stream stream)
        {
            RawTexture t      = new RawTexture();
            var        reader = new PngReader();

            t.Pixels      = reader.Read(stream);
            t.PixelFormat = OpenTK.Graphics.ES20.PixelFormat.Rgba;
            t.Width       = reader.Width;
            t.Height      = reader.Height;
            return(t);
        }
    /// <summary>
    /// Reads image in PNG format, converts to palette-based pixel format and saves to interlaced PNG format
    /// using memory-friendly Pipeline API
    /// </summary>
    private static void ReadConvertAndWritePngMemoryFriendly()
    {
        using (var reader = new PngReader("../../../../_Output/WritePng.png"))
            using (var colorConverter = new ColorConverter(PixelFormat.Format8bppIndexed))
                using (var writer = new PngWriter("../../../../_Output/ReadConvertAndWritePngMemoryFriendly.png"))
                {
                    writer.IsInterlaced = true;

                    Pipeline.Run(reader + colorConverter + writer);
                }
    }
Exemplo n.º 25
0
 public override RawTexture Get(string name)
 {
     using (var stream = Store.GetStream(name))
     {
         if (PngReader.IsPngImage(stream))
         {
             return(loadPng(stream));
         }
         return(loadOther(stream));
     }
 }
Exemplo n.º 26
0
        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            CommonSaveFileDialog saveDialog = new CommonSaveFileDialog();

            saveDialog.ShowPlacesList            = true;
            saveDialog.AddToMostRecentlyUsedList = true;
            saveDialog.Filters.Add(new CommonFileDialogFilter("PNG images", "*.png"));
            saveDialog.DefaultFileName = DateTime.Now.ToString("yyyyMMddhhmmss") + ".png";
            if (saveDialog.ShowDialog(this) == CommonFileDialogResult.Ok)
            {
                using (FileStream newFileStream = new FileStream(saveDialog.FileName, FileMode.OpenOrCreate, FileAccess.ReadWrite),
                       oldFileStream = new FileStream(soureFilePath, FileMode.Open, FileAccess.Read)) {
                    string semanticInfo = @"
    sky: blue sky.
    heart: cloud heart.
    Meaning: It means love|爱|❤.
                ";

                    ////// Reference: http://code.google.com/p/pngcs/wiki/Overview

                    // get decoder
                    pngReader = new PngReader(oldFileStream);
                    // create encoder
                    pngWriter = new PngWriter(newFileStream, pngReader.ImgInfo);
                    // copy
                    int chunkBehav = Hjg.Pngcs.Chunks.ChunkCopyBehaviour.COPY_ALL; // tell to copy all 'safe' chunks
                    pngWriter.CopyChunksFirst(pngReader, chunkBehav);              // copy some metadata from reader
                    int channels = pngReader.ImgInfo.Channels;
                    if (channels < 3)
                    {
                        throw new Exception("This example works only with RGB/RGBA images");
                    }
                    for (int row = 0; row < pngReader.ImgInfo.Rows; row++)
                    {
                        ImageLine l1 = pngReader.ReadRow(row); // format: RGBRGB... or RGBARGBA...
                        pngWriter.WriteRow(l1, row);
                    }
                    pngWriter.CopyChunksLast(pngReader, chunkBehav); // metadata after the image pixels? can happen

                    // app info
                    pngWriter.GetMetadata().SetText(Hjg.Pngcs.Chunks.PngChunkTextVar.KEY_Software, "Semantic Image");
                    // semantic info
                    Hjg.Pngcs.Chunks.PngChunk chunk = pngWriter.GetMetadata().SetText(Key_SemanticInfo, semanticInfo, false, false);
                    chunk.Priority = true;

                    pngWriter.End(); // dont forget this
                    pngReader.End();

                    oldFileStream.Close();
                    newFileStream.Close();
                }
            }
        }
Exemplo n.º 27
0
        //---------------------------------------------------------------------
        public bool load(string file_name)
        {
            string path_png = file_name.ToLower();

            if (!path_png.EndsWith(".png"))
            {
                path_png += ".png";
            }

            mPngReader = FileHelper.CreatePngReader(path_png);

            return(mPngReader != null);
        }
Exemplo n.º 28
0
 /// <summary>
 /// Combines image channels from multiple sources
 /// </summary>
 private static void CombineChannels()
 {
     using (var writer = ImageWriter.Create("../../../../_Output/PipelineCombineChannels.jpg"))
         using (var combiner = new Aurigma.GraphicsMill.RgbChannelCombiner())
             using (var readerR = new PngReader("../../../../_Output/Chicago_R.png"))
                 using (var readerG = new PngReader("../../../../_Output/Chicago_G.png"))
                     using (var readerB = new PngReader("../../../../_Output/Chicago_B.png"))
                     {
                         combiner.R = readerR;
                         combiner.G = readerG;
                         combiner.B = readerB;
                         Pipeline.Run(combiner + writer);
                     }
 }
Exemplo n.º 29
0
        public static void testCrcEquals(string image1, long crc)
        {
            PngReader png1 = FileHelper.CreatePngReader(image1);

            PngHelperInternal.InitCrcForTests(png1);
            png1.ReadRow(png1.ImgInfo.Rows - 1);
            png1.End();
            long crc1 = PngHelperInternal.GetCrctestVal(png1);

            if (crc1 != crc)
            {
                fatalError("different crcs", png1);
            }
        }
Exemplo n.º 30
0
        /// <summary>
        /// Decodes a raw file buffer of PNG data into raw image buffer, with width and height saved.
        /// </summary>
        /// <param name="stream">Png bytes.</param>
        public ImageLines Deserialize(Stream stream)
        {
            if (stream is null)
            {
                throw new System.ArgumentNullException(nameof(stream));
            }

            using var png = new PngReader(stream);
            png.SetUnpackedMode(true);
            var image = png.ReadRowsByte();

            png.End();
            return(image);
        }