1+ using System . IO ;
2+ using System . Windows . Media ;
3+ using System . Windows . Media . Imaging ;
4+
5+ string fileName ;
6+ start :
7+ if ( args . Length == 1 ) fileName = args [ 0 ] ;
8+ else
9+ {
10+ Console . WriteLine ( "请输入要转换的ppm,留空认为\" binary.ppm\" :" ) ;
11+ fileName = Console . ReadLine ( ) ;
12+ if ( string . IsNullOrWhiteSpace ( fileName ) ) fileName = "binary.ppm" ;
13+ }
14+ int resX , resY ;
15+ try
16+ {
17+ using StreamReader openText = File . OpenText ( fileName ) ;
18+ string MagicNumber = openText . ReadLine ( ) ;
19+ if ( MagicNumber != "P6" )
20+ {
21+ Console . WriteLine ( "Magic number is not P6. It's " + MagicNumber ) ;
22+ return ;
23+ }
24+ string [ ] res = openText . ReadLine ( ) . Split ( ' ' ) ;
25+ resX = Convert . ToInt32 ( res [ 0 ] ) ;
26+ resY = Convert . ToInt32 ( res [ 1 ] ) ;
27+ }
28+ catch ( FileNotFoundException )
29+ {
30+ Console . WriteLine ( fileName + "文件未找到." ) ;
31+ goto start ;
32+ }
33+ using var inputFS = File . OpenRead ( fileName ) ;
34+ int enterCount = 3 ;
35+ while ( enterCount > 0 )
36+ {
37+ if ( inputFS . ReadByte ( ) == '\n ' ) enterCount -- ;
38+ }
39+ WriteableBitmap bitmap = new ( resX , resY , 96 , 96 , PixelFormats . Rgb24 , null ) ;
40+ bitmap . Lock ( ) ;
41+ Span < byte > sp ;
42+ unsafe
43+ {
44+ void * bufferPtr = ( void * ) bitmap . BackBuffer ;
45+ sp = new ( bufferPtr , resX * resY * 3 ) ;
46+ }
47+ inputFS . Read ( sp ) ;
48+ bitmap . Unlock ( ) ;
49+ PngBitmapEncoder encoder = new ( ) ;
50+ encoder . Frames . Add ( BitmapFrame . Create ( bitmap ) ) ;
51+ string outputName = Path . ChangeExtension ( fileName , "png" ) ;
52+ using FileStream outputFS = new ( outputName , FileMode . Create ) ;
53+ encoder . Save ( outputFS ) ;
54+ Console . WriteLine ( outputName + "输出完毕." ) ;
0 commit comments