C# – Can Graphics.DrawImage unintentionally trim an image

c++graphicstiff

I'm using code that takes a bitmap and converts it to 24 BPP so that I can use it in a program that specifically requires that file format. Here is the code:

    using (Bitmap tempImage = new Bitmap(pageToScan.FullPath))
    {
       if (tempImage.PixelFormat != System.Drawing.Imaging.PixelFormat.Format24bppRgb)
       {
          using (Bitmap tempImage2 = new Bitmap(tempImage.Size.Width, tempImage.Size.Height,
             System.Drawing.Imaging.PixelFormat.Format24bppRgb))
          {
             using (Graphics g = Graphics.FromImage(tempImage2))
             {
                g.DrawImage(tempImage, new Point(0, 0));
             }
             RecognizeBitmap(pageToScan, tempImage2); //Thanks to Tim on this refactoring.
          }
       }
       else
          RecognizeBitmap(pageToScan, tempImage);
    }

I have two questions about the code above:

  1. With a particular image, I think
    that this clipped the rightmost 200
    pixels right off of tempImage2. Is
    this possible? How might this
    happen, and how can I stop it? A
    friend of mine suggested that it
    might have to do with the stride of
    the TIFF file being used.
  2. Is there a
    faster way to convert an image to 24
    BPP in memory?

Best Solution

A better way is to use the Bitmap.Clone method. This takes a PixelFormat as a parameter:

using (Bitmap tempImage = new Bitmap(pageToScan.FullPath))    
{           
    if (tempImage.PixelFormat != System.Drawing.Imaging.PixelFormat.Format24bppRgb)
    {
        Rectangle r = new Rectangle(0, 0, tempImage.Width, tempImage.Height);
        RecognizeBitmap(pageToScan, tempImage.Clone(r, PixelFormat.Format24bppRgb);          
    }
    else                  
    {
        RecognizeBitmap(pageToScan, tempImage);    
    }
}