views:

537

answers:

3

I am currently working on a simple Silverlight app that will allow people to upload an image, crop, resize and rotate it and then load it via a webservice to a CMS.

Cropping and resizing is done, however rotation is causing some problems. The image gets cropped and is off centre after the rotation.

WriteableBitmap wb = new WriteableBitmap(destWidth, destHeight);

RotateTransform rt = new RotateTransform();
rt.Angle = 90;
rt.CenterX = width/2;
rt.CenterY = height/2;

//Draw to the Writeable Bitmap
Image tempImage2 = new Image();
tempImage2.Width = width;
tempImage2.Height = height;
tempImage2.Source = rawImage;

wb.Render(tempImage2,rt);
wb.Invalidate();
rawImage = wb;

message.Text = "h:" + rawImage.PixelHeight.ToString();
message.Text += ":w:" + rawImage.PixelWidth.ToString();

//Finally set the Image back
MyImage.Source = wb;
MyImage.Width = destWidth;
MyImage.Height = destHeight;

The code above only needs to rotate by 90° at this time so I'm just setting destWidth and destHeight to the height and width of the original image.

A: 

If the image isn't square you will get cropping.

I know this won't give you exactly the right result, you'll need to crop it afterwards, but it will create a bitmap big enough in each direction to take the rotated image.

    //Draw to the Writeable Bitmap
    Image tempImage2 = new Image();
    tempImage2.Width = Math.Max(width, height);
    tempImage2.Height = Math.Max(width, height);
    tempImage2.Source = rawImage;
ChrisF
+1  A: 

It looks like your target image is the same size as your source image. If you want to rotate over 90 degrees, your width and height should be exchanged:

WriteableBitmap wb = new WriteableBitmap(destHeight, destWidth);

Also, if you rotate about the centre of the original image, part of it will end up outside the boundaries. You could either include some translation transforms, or simply rotate the image about a different point:

rt.CenterX = rt.CenterY = Math.Min(width / 2, height / 2);

Try it with a piece of rectangular paper to see why that makes sense.

Thomas
If I could give you more reputation I would! Been banging my head against this problem too long. Should've just grabbed a bit of A4 from the start!
Tim Saunders
A: 

I just want to congratulate Thomas on his answer. It is only correct answer to this problem on the whole internet. I have been banging my head against this problem for a whole day. Man, what are you made of??

On a side note, i just want to add that the solution only works on angle 90, it doesn't work on angle 270

Fadi