I'm trying to optimize out image transformation code. We currently allow our users to upload and crop images, but we're working on adding rotation into the mix, and the resulting images must be resized into three different sizes, with watermarks applied.
The code I took over repeatedly generated bitmaps in each step; this means allocating about 7 bitmaps in memory. I'm trying another solution, which I find more suitable: creating a transformation matrix that applies as many of the operations as possible, and reduce the number of bitmap creations.
For instance, I could apply a rotation like this:
public static void Rotate(Graphics target, Bitmap original, double angle)
{
// Move rotation point to the center of the bitmap.
target.TranslateTransform((float)original.Width / 2, (float)original.Height / 2);
// Do the actual rotation.
target.RotateTransform(Convert.ToSingle(angle));
// Move it back again.
target.TranslateTransform(-(float)original.Width / 2, -(float)original.Height / 2);
}
which would alter the transformation matrix in target
to apply a rotation. Similarly, I should be able to scale (resize) the image using Graphics.ScaleTransform
without needing to allocate additional memory.
My question, then, is whether there's a way to crop the image without having to draw on a bitmap? I've looked at Graphics.SetClip
, but can't quite get my head around how to use it to accomplish my goal.
If you have any examples of this, I would be most grateful.