@@ -15,16 +15,18 @@ class PNGImage {
1515 this . document = document ;
1616 if ( this . obj ) { return ; }
1717
18+ const hasAlphaChannel = this . image . hasAlphaChannel ;
19+
1820 this . obj = this . document . ref ( {
1921 Type : 'XObject' ,
2022 Subtype : 'Image' ,
21- BitsPerComponent : this . image . bits ,
23+ BitsPerComponent : hasAlphaChannel ? 8 : this . image . bits ,
2224 Width : this . width ,
2325 Height : this . height ,
2426 Filter : 'FlateDecode'
2527 } ) ;
2628
27- if ( ! this . image . hasAlphaChannel ) {
29+ if ( ! hasAlphaChannel ) {
2830 const params = this . document . ref ( {
2931 Predictor : 15 ,
3032 Colors : this . image . colors ,
@@ -71,7 +73,7 @@ class PNGImage {
7173 // in the PLTE and tRNS sections. See below for details on SMasks.
7274 return this . loadIndexedAlphaChannel ( ) ;
7375
74- } else if ( this . image . hasAlphaChannel ) {
76+ } else if ( hasAlphaChannel ) {
7577 // For PNG color types 4 and 6, the transparency data is stored as a alpha
7678 // channel mixed in with the main image data. Separate this data out into an
7779 // SMask object and store it separately in the PDF.
@@ -110,18 +112,29 @@ class PNGImage {
110112 return this . image . decodePixels ( pixels => {
111113 let a , p ;
112114 const colorCount = this . image . colors ;
113- const colorByteSize = ( colorCount * this . image . bits ) / 8 ;
114115 const pixelCount = this . width * this . height ;
115- const imgData = new Buffer ( pixelCount * colorByteSize ) ;
116- const alphaChannel = new Buffer ( pixelCount ) ;
116+ const imgData = new Buffer ( pixelCount * colorCount ) ;
117+ const alphaChannel = new Buffer ( pixelCount ) ;
117118
118119 let i = p = a = 0 ;
119120 const len = pixels . length ;
120- while ( i < len ) {
121- for ( let colorIndex = 0 ; colorIndex < colorCount ; colorIndex ++ ) {
122- imgData [ p ++ ] = pixels [ i ++ ] ;
121+ if ( this . image . bits === 8 ) {
122+ while ( i < len ) {
123+ for ( let colorIndex = 0 ; colorIndex < colorCount ; colorIndex ++ ) {
124+ imgData [ p ++ ] = pixels [ i ++ ] ;
125+ }
126+ alphaChannel [ a ++ ] = pixels [ i ++ ] ;
127+ }
128+ } else {
129+ // copy only most significant byte (MSB) - PNG data is always stored in network byte order (MSB first)
130+ while ( i < len ) {
131+ for ( let colorIndex = 0 ; colorIndex < colorCount ; colorIndex ++ ) {
132+ imgData [ p ++ ] = pixels [ i ++ ] ;
133+ i ++ ;
134+ }
135+ alphaChannel [ a ++ ] = pixels [ i ++ ] ;
136+ i ++ ;
123137 }
124- alphaChannel [ a ++ ] = pixels [ i ++ ] ;
125138 }
126139
127140 this . imgData = zlib . deflateSync ( imgData ) ;
0 commit comments