@@ -33,25 +33,40 @@ public static void WritePixels<TPixel>(Configuration configuration, Stream strea
3333 {
3434 WriteGrayscale ( configuration , stream , image ) ;
3535 }
36- else
36+ else if ( componentType == PbmComponentType . Short )
3737 {
3838 WriteWideGrayscale ( configuration , stream , image ) ;
3939 }
40+ else
41+ {
42+ throw new ImageFormatException ( "Component type not supported for Grayscale PBM." ) ;
43+ }
4044 }
4145 else if ( colorType == PbmColorType . Rgb )
4246 {
4347 if ( componentType == PbmComponentType . Byte )
4448 {
4549 WriteRgb ( configuration , stream , image ) ;
4650 }
47- else
51+ else if ( componentType == PbmComponentType . Short )
4852 {
4953 WriteWideRgb ( configuration , stream , image ) ;
5054 }
55+ else
56+ {
57+ throw new ImageFormatException ( "Component type not supported for Color PBM." ) ;
58+ }
5159 }
5260 else
5361 {
54- WriteBlackAndWhite ( configuration , stream , image ) ;
62+ if ( componentType == PbmComponentType . Bit )
63+ {
64+ WriteBlackAndWhite ( configuration , stream , image ) ;
65+ }
66+ else
67+ {
68+ throw new ImageFormatException ( "Component type not supported for Black & White PBM." ) ;
69+ }
5570 }
5671 }
5772
@@ -164,8 +179,6 @@ private static void WriteBlackAndWhite<TPixel>(Configuration configuration, Stre
164179 using IMemoryOwner < L8 > row = allocator . Allocate < L8 > ( width ) ;
165180 Span < L8 > rowSpan = row . GetSpan ( ) ;
166181
167- int previousValue = 0 ;
168- int startBit = 0 ;
169182 for ( int y = 0 ; y < height ; y ++ )
170183 {
171184 Span < TPixel > pixelSpan = pixelBuffer . DangerousGetRowSpan ( y ) ;
@@ -177,28 +190,19 @@ private static void WriteBlackAndWhite<TPixel>(Configuration configuration, Stre
177190
178191 for ( int x = 0 ; x < width ; )
179192 {
180- int value = previousValue ;
181- for ( int i = startBit ; i < 8 ; i ++ )
193+ int value = 0 ;
194+ int stopBit = Math . Min ( 8 , width - x ) ;
195+ for ( int i = 0 ; i < stopBit ; i ++ )
182196 {
183197 if ( rowSpan [ x ] . PackedValue < 128 )
184198 {
185199 value |= 0x80 >> i ;
186200 }
187201
188202 x ++ ;
189- if ( x == width )
190- {
191- previousValue = value ;
192- startBit = ( i + 1 ) & 7 ; // Round off to below 8.
193- break ;
194- }
195203 }
196204
197- if ( startBit == 0 )
198- {
199- stream . WriteByte ( ( byte ) value ) ;
200- previousValue = 0 ;
201- }
205+ stream . WriteByte ( ( byte ) value ) ;
202206 }
203207 }
204208 }
0 commit comments