Exemple #1
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();
        }
Exemple #2
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);
            }
        }
Exemple #3
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();
        }
Exemple #4
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);
        }
Exemple #5
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);
        }
        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);
        }
        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);
        }
        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);
            }
Exemple #10
0
 public static void fatalError(String s, PngReader png1)
 {
     try {
         png1.End();
     } catch (Exception) {
     }
     throw new PngjException(s);
 }
Exemple #11
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);
        }
Exemple #12
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);;
        }
        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();
                }
            }
        }
Exemple #14
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);
        }
Exemple #15
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);
            }
        }
Exemple #16
0
        public static Unity3DTileIndex LoadFromPNG(Stream stream)
        {
#if IMAGE_SHARP_PNG
            //requires extra dependency DLLs which bloat the webgl build
            using (var png = SixLabors.ImageSharp.Image.Load <Rgba64>(stream))
                var index = new Unity3DTileIndex(png.Width, png.Height);
            {
                for (int r = 0; r < png.Height; r++)
                {
                    for (int c = 0; c < png.Width; c++)
                    {
                        var pixel = png[c, r];
                        index[0, r, c] = pixel.R;
                        index[1, r, c] = pixel.G;
                        index[2, r, c] = pixel.B;
                    }
                }
            }
            return(index);
#elif PNGCS_PNG
            var png = new PngReader(stream);
            png.SetUnpackedMode(true);
            var info = png.ImgInfo;
            if (info.Channels != 3)
            {
                throw new Exception("expected 3 channel PNG, got " + info.Channels);
            }
            var index = new Unity3DTileIndex(info.Cols, info.Rows);
            var buf   = new int[3 * info.Cols];
            for (int r = 0; r < info.Rows; r++)
            {
                png.ReadRow(buf, r);
                for (int c = 0; c < info.Cols; c++)
                {
                    index[0, r, c] = (uint)buf[3 * c + 0];
                    index[1, r, c] = (uint)buf[3 * c + 1];
                    index[2, r, c] = (uint)buf[3 * c + 2];
                }
            }
            png.End();
            return(index);
#else
            return(null);
#endif
        }
Exemple #17
0
        private static TRet ReadChunk <TRet, TChunk>(string filePath, string chunkId, Func <TChunk, TRet> valueFunc)
            where TChunk : PngChunk
        {
            PngReader pngr = null;

            try
            {
                pngr = FileHelper.CreatePngReader(filePath);

                TChunk chunk = (TChunk)pngr.GetChunksList().GetById1(chunkId);

                return(valueFunc(chunk));
            }
            finally
            {
                pngr?.End();
            }
        }
Exemple #18
0
        /// <summary>If <paramref name="outFilePath" /> is NULL then file is written in-place.</summary>
        //public static void WriteZTxtChunk(string inFilePath, string outFilePath, string text)
        //{
        //  PngChunk CreateChunk(ImageInfo imgInfo)
        //  {
        //    PngChunkZTXT chunk = new PngChunkZTXT(imgInfo);
        //    chunk.SetKeyVal(data);
        //    chunk.Priority = true;

        //    return chunk;
        //  }

        //  using (var inStream = OpenInputStream(inFilePath, outFilePath == null))
        //    WriteChunk(inStream, outFilePath ?? inFilePath, CreateChunk);
        //}

        private static void WriteChunk(Stream inStream, string outFilePath, Func <ImageInfo, PngChunk> chunkFunc)
        {
            PngReader pngr = new PngReader(inStream);
            PngWriter pngw = FileHelper.CreatePngWriter(outFilePath, pngr.ImgInfo, true);

            pngw.CopyChunksFirst(pngr, ChunkCopyBehaviour.COPY_ALL);
            pngw.GetChunksList().Queue(chunkFunc(pngw.ImgInfo));

            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();
        }
Exemple #19
0
        public static Texture2D FromPng(Stream stream, Texture2D texture = null)
        {
            var pngr = new PngReader(stream);

            var ms = new MemoryStream();

            int channels = pngr.ImgInfo.Channels;
            int w        = pngr.ImgInfo.Cols;
            int h        = pngr.ImgInfo.Rows;
            var bytes    = new byte[w * h * channels];

            int count = 0;

            for (int row = 0; row < pngr.ImgInfo.Rows; row++)
            {
                ImageLine l1 = pngr.ReadRowInt(row);           // Format: RGBRGB... or RGBARGBA...
                for (int j = 0; j < pngr.ImgInfo.Cols; j++)
                {
                    byte R = (byte)l1.Scanline[j * channels];
                    byte G = (byte)l1.Scanline[j * channels + 1];
                    byte B = (byte)l1.Scanline[j * channels + 2];
                    byte A = (byte)l1.Scanline[j * channels + 3];

                    bytes[count++] = B;
                    bytes[count++] = G;
                    bytes[count++] = R;
                    bytes[count++] = A;
                }
            }

            ms.Close();
            pngr.End();

            if (texture == null)
            {
                texture = new Texture2D(GameClass.Graphics, w, h);
            }

            texture.SetData(bytes);

            return(texture);
        }
Exemple #20
0
        public static void SaveToPng(string FileName, string ToFileName, string XamlFileName)
        {
            PngReader pngr = FileHelper.CreatePngReader(FileName);
            PngWriter pngw = FileHelper.CreatePngWriter(ToFileName, pngr.ImgInfo, true);

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

            mychunk.Content  = File.ReadAllText(XamlFileName);
            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();
        }
        public static void testRead(String file)
        {
            // register with factory chunk
            PngChunk.FactoryRegister(PngChunkSERI.ID, typeof(PngChunkSERI));
            // read all file
            PngReader pngr = FileHelper.CreatePngReader(file);

            pngr.ReadSkippingAllRows();
            pngr.End();
            // we assume there can be at most one chunk of this type...
            PngChunk chunk = pngr.GetChunksList().GetById1(PngChunkSERI.ID); // This would work even if not registered, but then PngChunk would be of type PngChunkUNKNOWN

            Console.Out.WriteLine(chunk);
            // the following would fail if we had not register the chunk
            PngChunkSERI chunkprop = (PngChunkSERI)chunk;
            string       name      = chunkprop.GetObj().name;
            int          age       = chunkprop.GetObj().age;

            Console.Out.WriteLine("Done. Name: " + name + " age=" + age);
        }
Exemple #22
0
        public static PngInfo GetInfo(Stream stream)
        {
            if (stream == null)
            {
                throw new ArgumentNullException("stream");
            }
            PngReader pngReader = new PngReader(stream);

            pngReader.ShouldCloseStream = false;
            pngReader.End();
            PngInfo result = default(PngInfo);

            result.Width  = pngReader.ImgInfo.Cols;
            result.Height = pngReader.ImgInfo.Rows;
            if (pngReader.ImgInfo.BitDepth == 8 && pngReader.ImgInfo.Channels == 4)
            {
                result.Format = Format.RGBA8;
            }
            else if (pngReader.ImgInfo.BitDepth == 8 && pngReader.ImgInfo.Channels == 3)
            {
                result.Format = Format.RGB8;
            }
            else if (pngReader.ImgInfo.BitDepth == 8 && pngReader.ImgInfo.Channels == 2 && pngReader.ImgInfo.Greyscale)
            {
                result.Format = Format.LA8;
            }
            else if (pngReader.ImgInfo.BitDepth == 8 && pngReader.ImgInfo.Channels == 1 && pngReader.ImgInfo.Greyscale)
            {
                result.Format = Format.L8;
            }
            else
            {
                if (pngReader.ImgInfo.BitDepth != 8 || pngReader.ImgInfo.Channels != 1 || !pngReader.ImgInfo.Indexed)
                {
                    throw new InvalidOperationException("Unsupported PNG pixel format.");
                }
                result.Format = Format.Indexed;
            }
            return(result);
        }
Exemple #23
0
        public static ResourceDictionary LoadFromPng(string FileName)
        {
            // read all file
            PngReader pngr = FileHelper.CreatePngReader(FileName);

            pngr.ReadSkippingAllRows();
            pngr.End();
            // we assume there can be at most one chunk of this type...
            PngChunk chunk = pngr.GetChunksList().GetById1(PngChunkSKIN.ID); // This would work even if not registered, but then PngChunk would be of type PngChunkUNKNOWN

            if (chunk != null)
            {
                // the following would fail if we had not register the chunk
                PngChunkSKIN  chunkprop = (PngChunkSKIN)chunk;
                ParserContext pc        = new ParserContext();
                pc.XamlTypeMapper = XamlTypeMapper.DefaultMapper;
                //  pc.XmlSpace

                //MimeObjectFactory s;

                var rd1 = (ResourceDictionary)XamlReader.Parse(chunkprop.Content);

                // Application.Current.Resources.MergedDictionaries.Add(rd1);

                //  var rd2 = (ResourceDictionary)XamlReader.Parse(chunkprop.Content);

                ////  Application.Current.Resources.MergedDictionaries.Add(rd2);

                //  if (rd1 == rd2) {
                //  }

                return(rd1);
            }
            else
            {
                return(null);
            }
        }
Exemple #24
0
        /// <summary>
        /// Load from file.
        /// </summary>
        /// <param name="pngFilePath">Full file path.</param>
        public PngData(string pngFilePath)
        {
            if (!File.Exists(pngFilePath))
            {
                throw new Exception($"Png file '{pngFilePath}' not exists.");
            }

            LoadedImageName = Path.GetFileNameWithoutExtension(pngFilePath);
            PngReader source = FileHelper.CreatePngReader(pngFilePath);

            pixelWidth  = source.ImgInfo.Cols;
            pixelHeight = source.ImgInfo.Rows;
            dataWidth   = pixelWidth * 4; // auto convert ot argb
            dataHeight  = pixelHeight;
            Info        = new ImageInfo(source.ImgInfo.Cols, source.ImgInfo.Rows, 8, true);

            imgData = new byte[dataHeight, dataWidth];
            //ConsoleEx.WriteDebug($"Load image '{LoadedImageName}'");

            if (source.ImgInfo.Channels == 1)
            {
                LoadGrayscaleImage(source);
            }
            else if (source.ImgInfo.Channels == 3)
            {
                LoadNoAlphaImage(source);
            }
            else if (source.ImgInfo.Channels == 4)
            {
                LoadRGBAImage(source);
            }
            else
            {
                throw new Exception($"Not support image format (Channels: {source.ImgInfo.Channels.ToString()}).");
            }

            source.End();
        }
Exemple #25
0
        private void WriteSvgToChunk(string tmpOcclusionFilePath, string svg)
        {
            using (Stream inStream = ToMemoryStream(tmpOcclusionFilePath))
            {
                PngReader pngr = new PngReader(inStream);
                PngWriter pngw = FileHelper.CreatePngWriter(tmpOcclusionFilePath, pngr.ImgInfo, true);

                pngw.CopyChunksFirst(pngr, ChunkCopyBehaviour.COPY_ALL_SAFE);

                CreateChunk(pngw, svg);

                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();
            }
        }
Exemple #26
0
        public string GetHeader(string icon)
        {
            string ztxt = string.Empty;

            PngReader pngr = FileHelper.CreatePngReader(FileName);

            width  = pngr.ImgInfo.Cols;
            height = pngr.ImgInfo.Rows;
            ChunksList clist = pngr.GetChunksList();

            /*The File should only have one zTxt, this chunk stores our DMI information such as
             * sprite width, height, iconstates, directionals and frames among other things.
             */
            foreach (PngChunkZTXT desc in clist.GetById("zTXt"))
            {
                ztxt = desc.GetVal();
                break;
            }
            pngr.ShouldCloseStream = true;
            pngr.End();

            return(ztxt);
        }
Exemple #27
0
        private static void additionalTestPalette(string orig, string truecolor)
        {
            // covnert to true color 8 bits and check equality
            PngReader    pngr  = FileHelper.CreatePngReader(orig);
            PngChunkPLTE plte  = pngr.GetMetadata().GetPLTE();
            PngChunkTRNS trns  = pngr.GetMetadata().GetTRNS();
            string       copy  = TestsHelper.addSuffixToName(orig, "_tccopy");
            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);
            }
            pngr.End();
            pngw.End();
            TestsHelper.testEqual(copy, truecolor);
            System.IO.File.Delete(copy);
        }
Exemple #28
0
        private static void PngWriter(MemoryStream memoryStream, FileStream fileStream, bool modelpng = false)
        {
            PngReader          pngReader    = new PngReader(fileStream);
            EngineBinaryWriter binaryWriter = new EngineBinaryWriter(memoryStream, false);

            binaryWriter.Write(false);
            pngReader.ShouldCloseStream  = false;
            pngReader.ChunkLoadBehaviour = ChunkLoadBehaviour.LOAD_CHUNK_NEVER;
            pngReader.MaxTotalBytesRead  = 9223372036854775807L;
            ImageLines imageLines = pngReader.ReadRowsByte();

            pngReader.End();
            Image image = new Image(pngReader.ImgInfo.Cols, pngReader.ImgInfo.Rows);
            int   n     = 0;

            for (int i = 0; i < image.Height; i++)
            {
                byte[] array = imageLines.ScanlinesB[i];
                int    num   = 0;
                for (int j = 0; j < image.Width; j++)
                {
                    byte r = array[num++];
                    byte g = array[num++];
                    byte b = array[num++];
                    byte a = array[num++];
                    image.Pixels[n++] = new Color(r, g, b, a);
                }
            }
            List <Image> list = new List <Image>();

            if (IsPowerOf2(image.Width) && IsPowerOf2(image.Height))
            {
                list.AddRange(Image.GenerateMipmaps(image, 2147483647));
            }
            else
            {
                list.Add(image);
                modelpng = true;
            }
            if (modelpng)
            {
                goto IL_00;
            }
            binaryWriter.Write(image.Width);
            binaryWriter.Write(image.Height);
            binaryWriter.Write(1);
            for (int i = 0; i < image.Height; i++)
            {
                byte[] array = imageLines.ScanlinesB[i];
                int    num   = 0;
                for (int j = 0; j < image.Width; j++)
                {
                    byte r = array[num++];
                    byte g = array[num++];
                    byte b = array[num++];
                    byte a = array[num++];
                    binaryWriter.Write(new Color(r, g, b, a).PackedValue);
                }
            }
            return;

IL_00:
            binaryWriter.Write(list[0].Width);
            binaryWriter.Write(list[0].Height);
            binaryWriter.Write(list.Count);
            foreach (Image current in list)
            {
                for (int j = 0; j < current.Pixels.Length; j++)
                {
                    binaryWriter.Write(current.Pixels[j].PackedValue);
                }
            }
        }
Exemple #29
0
        /// <summary> Create Color[] from PNG file </summary>
        public static ReadColorsResult ReadColors
        (
            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;
                if (info.Indexed)
                {
                    throw new System.NotImplementedException("indexed png not implemented");
                }

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

                //create pixel array:
                for (int row = 0; row < results.height; row++)
                {
                    ImageLine imageLine = reader.ReadRowInt(row);
                    var       scanline  = imageLine.Scanline;
                    if (imageLine.SampleType == ImageLine.ESampleType.INT)
                    {
                        for (int col = 0; col < results.width; col++)
                        {
                            var color = new Color();
                            for (int ch = 0; ch < channels; ch++)
                            {
                                int   raw    = scanline[col * channels + ch];
                                float rawMax = GetBitDepthMaxValue(bitDepth);
                                float value  = (float)raw / rawMax;

                                //
                                if (ch == 0)
                                {
                                    color.r = value;
                                }
                                else if (ch == 1)
                                {
                                    color.g = value;
                                }
                                else if (ch == 2)
                                {
                                    color.b = value;
                                }
                                else if (ch == 3)
                                {
                                    color.a = value;
                                }
                                else
                                {
                                    throw new System.Exception($"channel { ch } not implemented");
                                }
                            }
                            results.pixels[IndexPngToTexture(row, col, results.height, results.width)] = color;
                        }
                    }
                    else
                    {
                        throw new System.Exception($"imageLine.SampleType { imageLine.SampleType } not implemented");
                    }
                }
            }
            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.End();
                }
            }
            return(results);
        }
        private unsafe void ReadPng(Stream bitmapStream, BitmapCreateOptions createOptions, BitmapCacheOption cacheOption)
        {
            var pngr = new PngReader(bitmapStream);

            if (pngr.ImgInfo.Channels > 4 || pngr.ImgInfo.Channels < 3 || pngr.ImgInfo.BitDepth
                != 8)
            {
                throw new NotSupportedException("PNG must be RGB8/RGBA8");
            }

            var channels = pngr.ImgInfo.Channels;
            var data     = new byte[pngr.ImgInfo.Cols * pngr.ImgInfo.Rows * channels];
            var alpha    = (channels == 4);

            if (alpha)
            {
                fixed(byte *dataStart = &data[0])
                {
                    var d = dataStart;

                    for (var i = 0; i < pngr.ImgInfo.Rows; i++)
                    {
                        var line = pngr.ReadRowByte(i);
                        for (var j = 0; j < pngr.ImgInfo.Cols; j++)
                        {
                            var j2  = j * channels;
                            *   d++ = line.ScanlineB[j2 + 2];
                            *   d++ = line.ScanlineB[j2 + 1];
                            *   d++ = line.ScanlineB[j2];
                            *   d++ = line.ScanlineB[j2 + 3];
                        }
                    }

                    Source = BitmapSource.Create(pngr.ImgInfo.Cols, pngr.ImgInfo.Rows, 100, 100, PixelFormats.Bgra32, null, (IntPtr)dataStart, pngr.ImgInfo.Cols * pngr.ImgInfo.Rows * channels,
                                                 pngr.ImgInfo.Cols * channels);
                }

                //for (int i = 0; i < pngr.ImgInfo.Rows; i++)
                //{
                //    var i1 = i * pngr.ImgInfo.Cols * channels;
                //    ImageLine line = pngr.ReadRowInt(i);
                //    for (int j = 0; j < pngr.ImgInfo.Cols; j++)
                //    {
                //        var j1 = i1 + j * channels;
                //        var j2 = j * channels;
                //        data[j1+2] = (byte)line.Scanline[j2++];
                //        data[j1 + 1] = (byte)line.Scanline[j2++];
                //        data[j1] = (byte)line.Scanline[j2++];
                //        data[j1 + 3] = (byte)line.Scanline[j2];
                //    }
                //}
                //Source = BitmapSource.Create(pngr.ImgInfo.Cols, pngr.ImgInfo.Rows, 100, 100, PixelFormats.Bgra32, null, data, pngr.ImgInfo.Cols * channels);
                //Source = BitmapSource.Create(pngr.ImgInfo.Cols, pngr.ImgInfo.Rows, 100, 100, PixelFormats.Bgra32, null, data, stride);
            }
            else
            {
                fixed(byte *dataStart = &data[0])
                {
                    var d = dataStart;

                    for (var i = 0; i < pngr.ImgInfo.Rows; i++)
                    {
                        var line = pngr.ReadRowInt(i);
                        for (var j = 0; j < pngr.ImgInfo.Cols; j++)
                        {
                            var j2  = j * channels;
                            *   d++ = (byte)line.Scanline[j2 + 2];
                            *   d++ = (byte)line.Scanline[j2 + 1];
                            *   d++ = (byte)line.Scanline[j2];
                        }
                    }
                    Source = BitmapSource.Create(pngr.ImgInfo.Cols, pngr.ImgInfo.Rows, 100, 100, PixelFormats.Bgr24, null, data, pngr.ImgInfo.Cols * channels);
                }
            }
            pngr.End();

            //double dpi = 96;
            //int width = 128;
            //int height = 128;
            //byte[] pixelData = new byte[width * height];

            //for (int y = 0; y < height; ++y)
            //{
            //    int yIndex = y * width;
            //    for (int x = 0; x < width; ++x)
            //    {
            //        pixelData[x + yIndex] = (byte)(x + y);
            //    }
            //}
            //Source = BitmapSource.Create(width, height, dpi, dpi,
            //        PixelFormats.Gray8, null, pixelData, width);
            //Source = source;
            Source.Freeze();
        }