public static string[,] buildMatrix(Dictionary<Color, string> dictionary, PngReader reader) { ImageInfo info = reader.ImgInfo; var matrix = new string[info.Cols, info.Rows]; for (int i = 0; i < info.Rows; i++) { ImageLine line = reader.ReadRow(i); int[] lineInts = line.Scanline; for (int j = 0, col = 0; j < lineInts.Length; j += info.Channels, col++) { int red = lineInts[j]; int green = lineInts[j + 1]; int blue = lineInts[j + 2]; int alpha = 255; if (info.Channels == 4) { alpha = lineInts[j + 3]; } Color color = new Color(red / 255f, green / 255f, blue / 255f, alpha / 255f); string val; if (dictionary.TryGetValue(color, out val)) { matrix[col, i] = val; } } } return matrix; }
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(); } } }