AForge.Imaging.Image.Clone C# (CSharp) Method

Clone() public static method

Clone image.
The original Bitmap.Clone() does not produce the desired result - it does not create an actual clone (it does not create a copy of the image). That is why this method was implemented to provide the functionality.
public static Clone ( Bitmap source ) : Bitmap
source System.Drawing.Bitmap Source image.
return System.Drawing.Bitmap
        public static Bitmap Clone( Bitmap source )
        {
            // lock source bitmap data
            BitmapData sourceData = source.LockBits(
                new Rectangle( 0, 0, source.Width, source.Height ),
                ImageLockMode.ReadOnly, source.PixelFormat );

            // create new image
            Bitmap destination = Clone( sourceData );

            // unlock source image
            source.UnlockBits( sourceData );

            //
            if (
                ( source.PixelFormat == PixelFormat.Format1bppIndexed ) ||
                ( source.PixelFormat == PixelFormat.Format4bppIndexed ) ||
                ( source.PixelFormat == PixelFormat.Format8bppIndexed ) ||
                ( source.PixelFormat == PixelFormat.Indexed ) )
            {
                ColorPalette srcPalette = source.Palette;
                ColorPalette dstPalette = destination.Palette;

                int n = srcPalette.Entries.Length;

                // copy pallete
                for ( int i = 0; i < n; i++ )
                {
                    dstPalette.Entries[i] = srcPalette.Entries[i];
                }

                destination.Palette = dstPalette;
            }

            return destination;
        }

Same methods

Image::Clone ( Bitmap source, PixelFormat format ) : Bitmap
Image::Clone ( BitmapData sourceData ) : Bitmap

Usage Example

 public static Bitmap OpenImage(this TextStructure filePath)
 {
     try
     {
         using (var bitmap = new Bitmap(filePath.Value))
         {
             return(Image.Clone(bitmap, PixelFormat.Format24bppRgb));
         }
     }
     catch (Exception ex)
     {
         throw new Exception($"Could not open the image file '{filePath.Value}'. Message: {ex.Message}", ex);
     }
 }
All Usage Examples Of AForge.Imaging.Image::Clone