@@ -126,7 +126,8 @@ public override Image Save(string path, Image image)
126
126
byte [ ] bytes ;
127
127
128
128
// Encode in webP format.
129
- if ( EncodeLossly ( ( Bitmap ) image , this . Quality , out bytes ) )
129
+ // If Quality is 100, encode losslessly instead of lossily
130
+ if ( this . Quality == 100 ? EncodeLosslessly ( ( Bitmap ) image , out bytes ) : EncodeLossly ( ( Bitmap ) image , this . Quality , out bytes ) )
130
131
{
131
132
File . WriteAllBytes ( path , bytes ) ;
132
133
}
@@ -147,7 +148,8 @@ public override Image Save(Stream stream, Image image)
147
148
byte [ ] bytes ;
148
149
149
150
// Encode in webP format.
150
- if ( EncodeLossly ( ( Bitmap ) image , this . Quality , out bytes ) )
151
+ // If Quality is 100, encode losslessly instead of lossily
152
+ if ( this . Quality == 100 ? EncodeLosslessly ( ( Bitmap ) image , out bytes ) : EncodeLossly ( ( Bitmap ) image , this . Quality , out bytes ) )
151
153
{
152
154
using ( MemoryStream memoryStream = new MemoryStream ( bytes ) )
153
155
{
@@ -271,5 +273,50 @@ private static bool EncodeLossly(Bitmap bitmap, int quality, out byte[] webpData
271
273
272
274
return encoded ;
273
275
}
276
+
277
+ /// <summary>
278
+ /// Losslessly encodes the image in bitmap.
279
+ /// </summary>
280
+ /// <param name="bitmap">
281
+ /// Bitmap with the image
282
+ /// </param>
283
+ /// <param name="webpData">
284
+ /// The byte array containing the encoded image data.
285
+ /// </param>
286
+ /// <returns>
287
+ /// True if success; False otherwise
288
+ /// </returns>
289
+ private static bool EncodeLosslessly ( Bitmap bitmap , out byte [ ] webpData )
290
+ {
291
+ webpData = null ;
292
+ BitmapData bmpData = bitmap . LockBits ( new Rectangle ( 0 , 0 , bitmap . Width , bitmap . Height ) , ImageLockMode . ReadOnly , PixelFormat . Format32bppArgb ) ;
293
+ IntPtr unmanagedData = IntPtr . Zero ;
294
+ bool encoded ;
295
+
296
+ try
297
+ {
298
+ // Attempt to losslessly encode the image.
299
+ int size = NativeMethods . WebPEncodeLosslessBGRA ( bmpData . Scan0 , bitmap . Width , bitmap . Height , bmpData . Stride , out unmanagedData ) ;
300
+
301
+ // Copy image compress data to output array
302
+ webpData = new byte [ size ] ;
303
+ Marshal . Copy ( unmanagedData , webpData , 0 , size ) ;
304
+ encoded = true ;
305
+ }
306
+ catch
307
+ {
308
+ encoded = false ;
309
+ }
310
+ finally
311
+ {
312
+ // Unlock the pixels
313
+ bitmap . UnlockBits ( bmpData ) ;
314
+
315
+ // Free memory
316
+ NativeMethods . WebPFree ( unmanagedData ) ;
317
+ }
318
+
319
+ return encoded ;
320
+ }
274
321
}
275
322
}
0 commit comments