@@ -132,6 +132,37 @@ function work(options = {})
132132
133133}
134134
135+ function float32To16Array ( uint8Buffer )
136+ {
137+ const floatData = new Float32Array (
138+ uint8Buffer . buffer ,
139+ uint8Buffer . byteOffset ,
140+ uint8Buffer . byteLength / Float32Array . BYTES_PER_ELEMENT
141+ ) ;
142+
143+ const uint16Data = new Uint16Array ( floatData . length ) ;
144+
145+ for ( let i = 0 , len = floatData . length ; i < len ; i ++ )
146+ {
147+ const clamped = Math . max ( 0 , Math . min ( 1 , floatData [ i ] ) ) ;
148+ uint16Data [ i ] = Math . round ( clamped * 65535 ) ;
149+ }
150+
151+ return uint16Data ;
152+ }
153+
154+ function convertBuffer ( buffer , bits , bitsString = false )
155+ {
156+ if ( bits >= 32 && bitsString . toLowerCase ( ) === '32float' )
157+ buffer = float32To16Array ( buffer ) ;
158+ else if ( bits >= 32 )
159+ buffer = new Uint16Array ( new Uint32Array ( buffer . buffer ) ) ;
160+ else if ( bits >= 16 )
161+ buffer = new Uint16Array ( buffer . buffer ) ;
162+
163+ return buffer ;
164+ }
165+
135166async function convertImage ( path )
136167{
137168 const webpPath = fileManager . realPath ( path ) ;
@@ -156,7 +187,18 @@ async function convertImage(path)
156187 if ( ! fs . existsSync ( parentPath ) )
157188 fs . mkdirSync ( parentPath ) ;
158189
159- await image . rawToPng ( result . buffer , webpPath , result . width , result . height , result . channels , {
190+ const bits = result . bits ;
191+
192+ if ( bits > 8 && result . buffer instanceof Uint8Array )
193+ result . buffer = convertBuffer ( result . buffer , bits , result . bitsString ) ;
194+
195+ await image . rawToPng ( result . buffer , webpPath , {
196+ width : result . width ,
197+ height : result . height ,
198+ channels : result . channels ,
199+ rgb16 : bits > 8 ? true : false ,
200+ premultiplied : result . premultiplied || false ,
201+ } , {
160202 compressionLevel : 2 ,
161203 } ) ;
162204
0 commit comments