Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficient image manipulation in C#

Tags:

I'm using the System.Drawing classes to generate thumbnails and watermarked images from user-uploaded photos. The users are also able to crop the images using jCrop after uploading the original. I've taken over this code from someone else, and am looking to simplify and optimize it (it's being used on a high-traffic website).

The previous guy had static methods that received a bitmap as a parameter and returned one as well, internally allocating and disposing a Graphics object. My understanding is that a Bitmap instance contains the entire image in memory, while Graphics is basically a queue of draw operations, and that it is idempotent.

The process currently works as follows:

  • Receive the image and store it in a temporary file.
  • Receive crop coordinates.
  • Load the original bitmap into memory.
  • Create a new bitmap from the original, applying the cropping.
  • Do some crazy-ass brightness adjusting on the new bitmap, maybe (?) returning a new bitmap (I'd rather not touch this; pointer arithmetics abound!), lets call this A.
  • Create another bitmap from the resulting one, applying the watermark (lets call this B1)
  • Create a 175x175 thumbnail bitmap from A.
  • Create a 45x45 thumbnail bitmap from A.

This seems like a lot of memory allocations; my question is this: is it a good idea to rewrite portions of the code and reuse the Graphics instances, in effect creating a pipeline? In effect, I only need 1 image in memory (the original upload), while the rest can be written directly to disk. All the generated images will need the crop and brightness transformations, and a single transformation that is unique to that version, effectively creating a tree of operations.

Any thought or ideas?

Oh, and I should probably mention that this is the first time I'm really working with .NET, so if something I say seems confused, please bear with me and give me some hints.