The Guts Of PasteOff

Ahh, my first day off. Just catching up on blogs, editing theme tunes for the Smartphone (heheh Knight Rider), playing a little Chronicles of Riddick... it's all fun. No family commitments until this evening. Sweet. Oh, and repeatedly trying to get the code samples below pasted in. Nnnngh. Sorry if this is the 18th time you're reading this.

I've been asked about the source code for PasteOff a couple of times. As usual, it's embarrassingly poor, so I figured I'd walk through the interesting bits and ignore the terrible UI code (just wait for the Avalon version! I'll make sure it has a gradient somewhere and takes 30 seconds to materialize*).

The clipboard handling is ripped straight from the MSDN library IDataObject help (though I can't actually find the same entry in the online help):

            private void GetCurrentClipboardImage()

            {

                  IDataObject data = Clipboard.GetDataObject();

                  if(data.GetDataPresent(DataFormats.Bitmap))

                  {

                        Debug.WriteLine("Bitmap present");

                        this.icon.Icon = this.WithImage;

                        GetBitmapFromClipboard(data);

                  }

                  if (data.GetDataPresent(DataFormats.Text))

                  {

                        Debug.WriteLine("Text present");

                        this.icon.Icon = this.NoImage;

                  }

            }

And that's the guts of the clipboard handling. Nice and simple.

The image handling in GetBitmapFromClipboard is a doddle too:

            private void GetBitmapFromClipboard(IDataObject data)

            {

                  Bitmap x;

                  x = (Bitmap) data.GetData(DataFormats.Bitmap, true);

                  this.theImage = x;

            }

(theImage is a System.Drawing.Image).

And the Image class has a ridiculously full-featured Save method, perfect for format conversion:

  this.theImage.Save(filename,System.Drawing.Imaging.ImageFormat.Jpeg);

As a mention, Darryn wasn't exactly glowing about the JPEG image quality when he was fiddling with his own saving routine. I avoided that with a choice of formats, but if anyone has suggestions for improving JPEG quality in .Net, I'm sure either of us would appreciate the tips.

So there you have it - everything* you need to build your own image conversion utility. Enjoy!