Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public static Bitmap Rotate(this Bitmap sourceBitmap, double degrees)
- {
- //sourceBitmap = NormalizationTools.CreateNonIndexedImage(sourceBitmap);
- var angle = degrees * Math.PI / 180.0;
- var cos = Math.Cos(angle);
- var sin = Math.Sin(angle);
- var width = sourceBitmap.Width;
- var height = sourceBitmap.Height;
- var xOffset = width / 2;
- var yOffset = height / 2;
- // copy image to byte array
- var sourceData = sourceBitmap.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadOnly,
- PixelFormat.Format24bppRgb);
- var stride = sourceData.Stride;
- var pixelBuffer = new byte[sourceData.Stride * sourceData.Height];
- Marshal.Copy(sourceData.Scan0, pixelBuffer, 0, pixelBuffer.Length);
- sourceBitmap.UnlockBits(sourceData);
- // create buffer for image with back background
- var resultBuffer = new byte[pixelBuffer.Length];
- for (int i = 0; i < resultBuffer.Length; ++i)
- {
- resultBuffer[i] = 255;
- }
- // process rotation
- for (int row = 0; row < height; ++row)
- {
- for (int col = 0; col < width; ++col)
- {
- var index = row * stride + col * 3;
- var x = (int)Math.Round((col - xOffset) * cos - (row - yOffset) * sin) + xOffset;
- var y = (int)Math.Round((col - xOffset) * sin + (row - yOffset) * cos) + yOffset;
- var newIndex = y * stride + x * 3;
- if (y >= 0 && y < height && x >= 0 && x < width)
- {
- if (newIndex + 5 < resultBuffer.Length)
- {
- resultBuffer[newIndex + 3] = resultBuffer[newIndex] = pixelBuffer[index];
- resultBuffer[newIndex + 4] = resultBuffer[newIndex + 1] = pixelBuffer[index + 1];
- resultBuffer[newIndex + 5] = resultBuffer[newIndex + 2] = pixelBuffer[index + 2];
- }
- else
- {
- resultBuffer[newIndex] = pixelBuffer[index];
- resultBuffer[newIndex + 1] = pixelBuffer[index + 1];
- resultBuffer[newIndex + 2] = pixelBuffer[index + 2];
- }
- }
- }
- }
- // create new bitmap
- var resultBitmap = new Bitmap(width, height);
- var resultData = resultBitmap.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.WriteOnly,
- PixelFormat.Format24bppRgb);
- Marshal.Copy(resultBuffer, 0, resultData.Scan0, resultBuffer.Length);
- resultBitmap.UnlockBits(resultData);
- return resultBitmap;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement