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 a clone with specified pixel format. More of it, the original method 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, PixelFormat format ) : Bitmap
source System.Drawing.Bitmap Source image.
format PixelFormat Pixel format of result image.
return System.Drawing.Bitmap
        public static Bitmap Clone( Bitmap source, PixelFormat format )
        {
            // copy image if pixel format is the same
            if ( source.PixelFormat == format )
                return Clone( source );

            int width = source.Width;
            int height = source.Height;

            // create new image with desired pixel format
            Bitmap bitmap = new Bitmap( width, height, format );

            // draw source image on the new one using Graphics
            Graphics g = Graphics.FromImage( bitmap );
            g.DrawImage( source, 0, 0, width, height );
            g.Dispose( );

            return bitmap;
        }

Same methods

Image::Clone ( Bitmap source ) : 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