Cast Images To Collabrary Photos And Back Again

The Collabrary.PhotoClass is a specialized object to store and perform certain functions on an image. In most cases, PhotoClass objects are created by other objects in the Collabrary (ie. The Collabrary.Camera class), however there are times when you need to go between System.Drawing.Bitmap objects in your C# projects.

Note that in this demo we use the Bitmap object instead of it's more generalized class Image. This is because Bitmaps allow access to the individual pixels of an image, which is needed for some conversions. Any bitmap can be cast to an Image, and Bitmaps can be loaded and manipulated in the same way that images can be.

Collabrary.Photo to Bitmap

This is the easy part. Simply create a new Image from the Collabrary.Photo's bitmap handle as follows:

Bitmap myImage = Bitmap.FromHBitmap( myPhoto.Hbitmap );

Bitmap to Collabrary.Photo

Here's the tough part. Because this is such an involved process, we create a function to do the conversion as follows:

public static Collabrary.Photo BitmapToPhoto(System.Drawing.Bitmap b)
  System.Drawing.Imaging.BitmapData bd = b.LockBits(new Rectangle(0, 0, b.Width, b.Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
  Collabrary.Photo p = new Collabrary.PhotoClass();
  p.Resize(bd.Width, bd.Height, false);
  p.PasteBitmapData(((int) bd.Scan0), bd.Width, bd.Height, bd.Stride);
  return p;