Browse Source

Merge pull request #131 from cosmo0/rotateinside

Adds "inside rotation" filter/method

Former-commit-id: 21483ea0ff11b36e63858c49292a3a91f50dee7d
Former-commit-id: e9cedf7f10726633e765ce27eac77e55796a17f3
af/merge-core
James South 11 years ago
parent
commit
3e0c77f628
  1. 32
      src/ImageProcessor.UnitTests/ImageFactoryUnitTests.cs
  2. 1
      src/ImageProcessor.UnitTests/ImageProcessor.UnitTests.csproj
  3. 54
      src/ImageProcessor.UnitTests/Imaging/Helpers/ImageMathsUnitTests.cs
  4. 18
      src/ImageProcessor/ImageFactory.cs
  5. 2
      src/ImageProcessor/ImageProcessor.csproj
  6. 170
      src/ImageProcessor/Imaging/Helpers/ImageMaths.cs
  7. 30
      src/ImageProcessor/Imaging/RotateInsideLayer.cs
  8. 25
      src/ImageProcessor/Processors/Rotate.cs
  9. 153
      src/ImageProcessor/Processors/RotateInside.cs
  10. 3
      src/ImageProcessor/Properties/AssemblyInfo.cs

32
src/ImageProcessor.UnitTests/ImageFactoryUnitTests.cs

@ -466,6 +466,38 @@ namespace ImageProcessor.UnitTests
}
}
/// <summary>
/// Tests that the image's inside is rotated
/// </summary>
[Test]
public void ImageIsRotatedInside()
{
foreach (ImageFactory imageFactory in this.ListInputImages())
{
Image original = (Image)imageFactory.Image.Clone();
imageFactory.RotateInside(new RotateInsideLayer { Angle = 45, KeepImageDimensions = true });
imageFactory.Image.Width.Should().Be(original.Width, "because the rotated image dimensions should not have changed");
imageFactory.Image.Height.Should().Be(original.Height, "because the rotated image dimensions should not have changed");
}
}
/// <summary>
/// Tests that the image's inside is rotated and resized
/// </summary>
[Test]
public void ImageIsRotatedInsideAndResized()
{
foreach (ImageFactory imageFactory in this.ListInputImages())
{
Image original = (Image)imageFactory.Image.Clone();
imageFactory.RotateInside(new RotateInsideLayer { Angle = 45, KeepImageDimensions = false });
imageFactory.Image.Width.Should().NotBe(original.Width, "because the rotated image dimensions should have changed");
imageFactory.Image.Height.Should().NotBe(original.Height, "because the rotated image dimensions should have changed");
}
}
/// <summary>
/// Tests that the images hue has been altered.
/// </summary>

1
src/ImageProcessor.UnitTests/ImageProcessor.UnitTests.csproj

@ -64,6 +64,7 @@
<Compile Include="Imaging\ColorUnitTests.cs" />
<Compile Include="Imaging\CropLayerUnitTests.cs" />
<Compile Include="Imaging\FastBitmapUnitTests.cs" />
<Compile Include="Imaging\Helpers\ImageMathsUnitTests.cs" />
</ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
<ItemGroup>

54
src/ImageProcessor.UnitTests/Imaging/Helpers/ImageMathsUnitTests.cs

@ -0,0 +1,54 @@
namespace ImageProcessor.UnitTests.Imaging.Helpers
{
using System.Drawing;
using FluentAssertions;
using ImageProcessor.Imaging.Helpers;
using NUnit.Framework;
/// <summary>
/// Test harness for the image math unit tests
/// </summary>
public class ImageMathsUnitTests
{
/// <summary>
/// Tests that the bounding rectangle of a rotated image is calculated
/// </summary>
/// <param name="width">The width of the image.</param>
/// <param name="height">The height of the image.</param>
/// <param name="angle">The rotation angle.</param>
/// <param name="expectedWidth">The expected width.</param>
/// <param name="expectedHeight">The expected height.</param>
[Test]
[TestCase(100, 100, 45, 141, 141)]
[TestCase(100, 100, 30, 137, 137)]
[TestCase(100, 200, 50, 217, 205)]
public void BoundingRotatedRectangleIsCalculated(int width, int height, float angle, int expectedWidth, int expectedHeight)
{
Rectangle result = ImageMaths.GetBoundingRotatedRectangle(width, height, angle);
result.Width.Should().Be(expectedWidth, "because the rotated width should have been calculated");
result.Height.Should().Be(expectedHeight, "because the rotated height should have been calculated");
}
/// <summary>
/// Tests that the zoom needed for an "inside" rotation is calculated
/// </summary>
/// <param name="imageWidth">Width of the image.</param>
/// <param name="imageHeight">Height of the image.</param>
/// <param name="angle">The rotation angle.</param>
/// <param name="expected">The expected zoom.</param>
[Test]
[TestCase(100, 100, 45, 1.41f)]
[TestCase(100, 100, 15, 1.22f)]
[TestCase(100, 200, 45, 2.12f)]
[TestCase(200, 100, 45, 2.12f)]
[TestCase(600, 450, 20, 1.39f)]
[TestCase(600, 450, 45, 1.64f)]
public void RotationZoomIsCalculated(int imageWidth, int imageHeight, float angle, float expected)
{
float result = ImageMaths.ZoomAfterRotation(imageWidth, imageHeight, angle);
result.Should().BeApproximately(expected, 0.01f, "because the zoom level after rotation should have been calculated");
}
}
}

18
src/ImageProcessor/ImageFactory.cs

@ -895,6 +895,24 @@ namespace ImageProcessor
return this;
}
/// <summary>
/// Rotates the image inside its area; keeps the area straight.
/// </summary>
/// <param name="rotateLayer">The rotation layer parameters.</param>
/// <returns>
/// The current instance of the <see cref="T:ImageProcessor.ImageFactory" /> class.
/// </returns>
public ImageFactory RotateInside(RotateInsideLayer rotateLayer)
{
if (this.ShouldProcess)
{
RotateInside rotate = new RotateInside { DynamicParameter = rotateLayer };
this.CurrentImageFormat.ApplyProcessor(rotate.ProcessImage, this);
}
return this;
}
/// <summary>
/// Adds rounded corners to the current image.
/// </summary>

2
src/ImageProcessor/ImageProcessor.csproj

@ -214,6 +214,7 @@
<Compile Include="Imaging\Filters\Photo\IMatrixFilter.cs" />
<Compile Include="Imaging\ResizeMode.cs" />
<Compile Include="Imaging\Resizer.cs" />
<Compile Include="Imaging\RotateInsideLayer.cs" />
<Compile Include="Imaging\RoundedCornerLayer.cs" />
<Compile Include="Imaging\TextLayer.cs" />
<Compile Include="Processors\Alpha.cs" />
@ -233,6 +234,7 @@
<Compile Include="Processors\Overlay.cs" />
<Compile Include="Processors\Pixelate.cs" />
<Compile Include="Processors\ReplaceColor.cs" />
<Compile Include="Processors\RotateInside.cs" />
<Compile Include="Processors\RoundedCorners.cs" />
<Compile Include="Processors\Saturation.cs" />
<Compile Include="Processors\Flip.cs" />

170
src/ImageProcessor/Imaging/Helpers/ImageMaths.cs

@ -12,7 +12,6 @@ namespace ImageProcessor.Imaging.Helpers
{
using System;
using System.Drawing;
using ImageProcessor.Imaging.Colors;
/// <summary>
@ -20,6 +19,27 @@ namespace ImageProcessor.Imaging.Helpers
/// </summary>
public static class ImageMaths
{
/// <summary>
/// Gets a <see cref="Rectangle"/> representing the child centered relative to the parent.
/// </summary>
/// <param name="parent">
/// The parent <see cref="Rectangle"/>.
/// </param>
/// <param name="child">
/// The child <see cref="Rectangle"/>.
/// </param>
/// <returns>
/// The centered <see cref="Rectangle"/>.
/// </returns>
public static RectangleF CenteredRectangle(Rectangle parent, Rectangle child)
{
float x = (parent.Width - child.Width) / 2.0F;
float y = (parent.Height - child.Height) / 2.0F;
int width = child.Width;
int height = child.Height;
return new RectangleF(x, y, width, height);
}
/// <summary>
/// Restricts a value to be within a specified range.
/// </summary>
@ -53,6 +73,20 @@ namespace ImageProcessor.Imaging.Helpers
return value;
}
/// <summary>
/// Returns the given degrees converted to radians.
/// </summary>
/// <param name="angleInDegrees">
/// The angle in degrees.
/// </param>
/// <returns>
/// The <see cref="double"/> representing the degree as radians.
/// </returns>
public static double DegreesToRadians(double angleInDegrees)
{
return angleInDegrees * (Math.PI / 180);
}
/// <summary>
/// Gets the bounding <see cref="Rectangle"/> from the given points.
/// </summary>
@ -70,6 +104,40 @@ namespace ImageProcessor.Imaging.Helpers
return new Rectangle(topLeft.X, topLeft.Y, bottomRight.X - topLeft.X, bottomRight.Y - topLeft.Y);
}
/// <summary>
/// Calculates the new size after rotation.
/// </summary>
/// <param name="width">The width of the image.</param>
/// <param name="height">The height of the image.</param>
/// <param name="angle">The angle of rotation.</param>
/// <returns>The new size of the image</returns>
public static Rectangle GetBoundingRotatedRectangle(int width, int height, float angle)
{
double widthAsDouble = width;
double heightAsDouble = height;
double radians = DegreesToRadians(angle);
double radiansSin = Math.Sin(radians);
double radiansCos = Math.Cos(radians);
double width1 = (heightAsDouble * radiansSin) + (widthAsDouble * radiansCos);
double height1 = (widthAsDouble * radiansSin) + (heightAsDouble * radiansCos);
// Find dimensions in the other direction
radiansSin = Math.Sin(-radians);
radiansCos = Math.Cos(-radians);
double width2 = (heightAsDouble * radiansSin) + (widthAsDouble * radiansCos);
double height2 = (widthAsDouble * radiansSin) + (heightAsDouble * radiansCos);
// Get the external vertex for the rotation
Rectangle result = new Rectangle(
0,
0,
Convert.ToInt32(Math.Max(Math.Abs(width1), Math.Abs(width2))),
Convert.ToInt32(Math.Max(Math.Abs(height1), Math.Abs(height2))));
return result;
}
/// <summary>
/// Finds the bounding rectangle based on the first instance of any color component other
/// than the given one.
@ -101,12 +169,15 @@ namespace ImageProcessor.Imaging.Helpers
case RgbaComponent.R:
delegateFunc = (fastBitmap, x, y, b) => fastBitmap.GetPixel(x, y).R != b;
break;
case RgbaComponent.G:
delegateFunc = (fastBitmap, x, y, b) => fastBitmap.GetPixel(x, y).G != b;
break;
case RgbaComponent.A:
delegateFunc = (fastBitmap, x, y, b) => fastBitmap.GetPixel(x, y).A != b;
break;
default:
delegateFunc = (fastBitmap, x, y, b) => fastBitmap.GetPixel(x, y).B != b;
break;
@ -188,24 +259,31 @@ namespace ImageProcessor.Imaging.Helpers
}
/// <summary>
/// Gets a <see cref="Rectangle"/> representing the child centered relative to the parent.
/// Rotates one point around another
/// <see href="http://stackoverflow.com/questions/13695317/rotate-a-point-around-another-point"/>
/// </summary>
/// <param name="parent">
/// The parent <see cref="Rectangle"/>.
/// </param>
/// <param name="child">
/// The child <see cref="Rectangle"/>.
/// <param name="pointToRotate">The point to rotate.</param>
/// <param name="angleInDegrees">The rotation angle in degrees.</param>
/// <param name="centerPoint">The centre point of rotation. If not set the point will equal
/// <see cref="Point.Empty"/>
/// </param>
/// <returns>
/// The centered <see cref="Rectangle"/>.
/// </returns>
public static RectangleF CenteredRectangle(Rectangle parent, Rectangle child)
/// <returns>Rotated point</returns>
public static Point RotatePoint(Point pointToRotate, double angleInDegrees, Point? centerPoint = null)
{
float x = (parent.Width - child.Width) / 2.0F;
float y = (parent.Height - child.Height) / 2.0F;
int width = child.Width;
int height = child.Height;
return new RectangleF(x, y, width, height);
Point center = centerPoint ?? Point.Empty;
double angleInRadians = DegreesToRadians(angleInDegrees);
double cosTheta = Math.Cos(angleInRadians);
double sinTheta = Math.Sin(angleInRadians);
return new Point
{
X =
(int)((cosTheta * (pointToRotate.X - center.X)) -
((sinTheta * (pointToRotate.Y - center.Y)) + center.X)),
Y =
(int)((sinTheta * (pointToRotate.X - center.X)) +
((cosTheta * (pointToRotate.Y - center.Y)) + center.Y))
};
}
/// <summary>
@ -221,55 +299,33 @@ namespace ImageProcessor.Imaging.Helpers
{
return new[]
{
new Point(rectangle.Left, rectangle.Top),
new Point(rectangle.Right, rectangle.Top),
new Point(rectangle.Right, rectangle.Bottom),
new Point(rectangle.Left, rectangle.Top),
new Point(rectangle.Right, rectangle.Top),
new Point(rectangle.Right, rectangle.Bottom),
new Point(rectangle.Left, rectangle.Bottom)
};
}
/// <summary>
/// Returns the given degrees converted to radians.
/// Calculates the zoom needed after the rotation.
/// </summary>
/// <param name="angleInDegrees">
/// The angle in degrees.
/// </param>
/// <returns>
/// The <see cref="double"/> representing the degree as radians.
/// </returns>
public static double DegreesToRadians(double angleInDegrees)
/// <param name="imageWidth">Width of the image.</param>
/// <param name="imageHeight">Height of the image.</param>
/// <param name="angle">The angle.</param>
/// <remarks>
/// Based on <see href="http://math.stackexchange.com/questions/1070853/"/>
/// </remarks>
/// <returns>The zoom needed</returns>
public static float ZoomAfterRotation(int imageWidth, int imageHeight, float angle)
{
return angleInDegrees * (Math.PI / 180);
}
double radians = angle * Math.PI / 180d;
double radiansSin = Math.Sin(radians);
double radiansCos = Math.Cos(radians);
/// <summary>
/// Rotates one point around another
/// <see href="http://stackoverflow.com/questions/13695317/rotate-a-point-around-another-point"/>
/// </summary>
/// <param name="pointToRotate">The point to rotate.</param>
/// <param name="angleInDegrees">The rotation angle in degrees.</param>
/// <param name="centerPoint">The centre point of rotation. If not set the point will equal
/// <see cref="Point.Empty"/>
/// </param>
/// <returns>Rotated point</returns>
public static Point RotatePoint(Point pointToRotate, double angleInDegrees, Point? centerPoint = null)
{
Point center = centerPoint ?? Point.Empty;
double widthRotated = (imageWidth * radiansCos) + (imageHeight * radiansSin);
double heightRotated = (imageWidth * radiansSin) + (imageHeight * radiansCos);
double angleInRadians = DegreesToRadians(angleInDegrees);
double cosTheta = Math.Cos(angleInRadians);
double sinTheta = Math.Sin(angleInRadians);
return new Point
{
X =
(int)
((cosTheta * (pointToRotate.X - center.X)) -
((sinTheta * (pointToRotate.Y - center.Y)) + center.X)),
Y =
(int)
((sinTheta * (pointToRotate.X - center.X)) +
((cosTheta * (pointToRotate.Y - center.Y)) + center.Y))
};
return (float)Math.Max(widthRotated / imageWidth, heightRotated / imageHeight);
}
}
}
}

30
src/ImageProcessor/Imaging/RotateInsideLayer.cs

@ -0,0 +1,30 @@
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ImageLayer.cs" company="James South">
// Copyright (c) James South.
// Licensed under the Apache License, Version 2.0.
// </copyright>
// <summary>
// Encapsulates the properties required to add an rotation layer to an image.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace ImageProcessor.Imaging
{
/// <summary>
/// A rotation layer to apply an inside rotation to an image
/// </summary>
public class RotateInsideLayer
{
/// <summary>
/// Gets or sets the rotation angle.
/// </summary>
public float Angle { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to keep the image dimensions.
/// If set to true, the image is zoomed inside the area.
/// If set to false, the area is resized to match the rotated image.
/// </summary>
public bool KeepImageDimensions { get; set; }
}
}

25
src/ImageProcessor/Processors/Rotate.cs

@ -104,30 +104,13 @@ namespace ImageProcessor.Processors
/// </remarks>
private Bitmap RotateImage(Image image, float rotateAtX, float rotateAtY, float angle)
{
double widthAsDouble = image.Width;
double heightAsDouble = image.Height;
Rectangle newSize = Imaging.Helpers.ImageMaths.GetBoundingRotatedRectangle(image.Width, image.Height, angle);
double radians = angle * Math.PI / 180d;
double radiansSin = Math.Sin(radians);
double radiansCos = Math.Cos(radians);
double width1 = (heightAsDouble * radiansSin) + (widthAsDouble * radiansCos);
double height1 = (widthAsDouble * radiansSin) + (heightAsDouble * radiansCos);
// Find dimensions in the other direction
radiansSin = Math.Sin(-radians);
radiansCos = Math.Cos(-radians);
double width2 = (heightAsDouble * radiansSin) + (widthAsDouble * radiansCos);
double height2 = (widthAsDouble * radiansSin) + (heightAsDouble * radiansCos);
// Get the external vertex for the rotation
int width = Convert.ToInt32(Math.Max(Math.Abs(width1), Math.Abs(width2)));
int height = Convert.ToInt32(Math.Max(Math.Abs(height1), Math.Abs(height2)));
int x = (width - image.Width) / 2;
int y = (height - image.Height) / 2;
int x = (newSize.Width - image.Width) / 2;
int y = (newSize.Height - image.Height) / 2;
// Create a new empty bitmap to hold rotated image
Bitmap newImage = new Bitmap(width, height);
Bitmap newImage = new Bitmap(newSize.Width, newSize.Height);
newImage.SetResolution(image.HorizontalResolution, image.VerticalResolution);
// Make a graphics object from the empty bitmap

153
src/ImageProcessor/Processors/RotateInside.cs

@ -0,0 +1,153 @@
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Rotate.cs" company="James South">
// Copyright (c) James South.
// Licensed under the Apache License, Version 2.0.
// </copyright>
// <summary>
// Encapsulates methods to rotate the inside of an image.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace ImageProcessor.Processors
{
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using ImageProcessor.Common.Exceptions;
using ImageProcessor.Imaging;
/// <summary>
/// Encapsulates the methods to rotate the inside of an image
/// </summary>
public class RotateInside : IGraphicsProcessor
{
/// <summary>
/// Gets or sets the DynamicParameter.
/// </summary>
public dynamic DynamicParameter { get; set; }
/// <summary>
/// Gets or sets any additional settings required by the processor.
/// </summary>
public Dictionary<string, string> Settings { get; set; }
/// <summary>
/// Processes the image.
/// </summary>
/// <param name="factory">The current instance of the <see cref="T:ImageProcessor.ImageFactory" /> class containing
/// the image to process.</param>
/// <returns>
/// The processed image from the current instance of the <see cref="T:ImageProcessor.ImageFactory" /> class.
/// </returns>
/// <remarks>
/// Based on <see href="http://math.stackexchange.com/questions/1070853/"/>
/// </remarks>
public Image ProcessImage(ImageFactory factory)
{
Bitmap newImage = null;
Image image = factory.Image;
try
{
RotateInsideLayer rotateLayer = this.DynamicParameter;
// Create a rotated image.
newImage = this.RotateImage(image, rotateLayer);
image.Dispose();
image = newImage;
}
catch (Exception ex)
{
if (newImage != null)
{
newImage.Dispose();
}
throw new ImageProcessingException("Error processing image with " + this.GetType().Name, ex);
}
return image;
}
/// <summary>
/// Rotates the inside of an image to the given angle at the given position.
/// </summary>
/// <param name="image">The image to rotate</param>
/// <param name="rotateLayer">The rotation layer.</param>
/// <remarks>
/// Based on the Rotate effect
/// </remarks>
/// <returns>The image rotated to the given angle at the given position.</returns>
private Bitmap RotateImage(Image image, RotateInsideLayer rotateLayer)
{
Size newSize = new Size(image.Width, image.Height);
float zoom = Imaging.Helpers.ImageMaths.ZoomAfterRotation(image.Width, image.Height, rotateLayer.Angle);
// if we don't keep the image dimensions, calculate the new ones
if (!rotateLayer.KeepImageDimensions)
{
newSize.Width = (int)(newSize.Width / zoom);
newSize.Height = (int)(newSize.Height / zoom);
}
// Center of the image
float rotateAtX = Math.Abs(image.Width / 2);
float rotateAtY = Math.Abs(image.Height / 2);
// Create a new empty bitmap to hold rotated image
Bitmap newImage = new Bitmap(newSize.Width, newSize.Height);
newImage.SetResolution(image.HorizontalResolution, image.VerticalResolution);
// Make a graphics object from the empty bitmap
using (Graphics graphics = Graphics.FromImage(newImage))
{
// Reduce the jagged edge.
graphics.SmoothingMode = SmoothingMode.AntiAlias;
graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
graphics.CompositingQuality = CompositingQuality.HighQuality;
if (rotateLayer.KeepImageDimensions)
{
// Put the rotation point in the "center" of the image
graphics.TranslateTransform(rotateAtX, rotateAtY);
// Rotate the image
graphics.RotateTransform(rotateLayer.Angle);
// Zooms the image to fit the area
graphics.ScaleTransform(zoom, zoom);
// Move the image back
graphics.TranslateTransform(-rotateAtX, -rotateAtY);
// Draw passed in image onto graphics object
graphics.DrawImage(image, new PointF(0, 0));
}
else
{
// calculate the difference between the center of the original image and the center of the new image
int diffX = (image.Width - newSize.Width) / 2;
int diffY = (image.Height - newSize.Height) / 2;
// Put the rotation point in the "center" of the old image
graphics.TranslateTransform(rotateAtX - diffX, rotateAtY - diffY);
// Rotate the image
graphics.RotateTransform(rotateLayer.Angle);
// Move the image back
graphics.TranslateTransform(-(rotateAtX - diffX), -(rotateAtY - diffY));
// Draw passed in image onto graphics object
graphics.DrawImage(image, new PointF(-diffX, -diffY));
}
}
return newImage;
}
}
}

3
src/ImageProcessor/Properties/AssemblyInfo.cs

@ -9,6 +9,7 @@
// --------------------------------------------------------------------------------------------------------------------
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
@ -42,3 +43,5 @@ using System.Runtime.InteropServices;
// by using the '*' as shown below:
[assembly: AssemblyVersion("2.2.0.0")]
[assembly: AssemblyFileVersion("2.2.0.0")]
[assembly: InternalsVisibleTo("ImageProcessor.UnitTests")]
Loading…
Cancel
Save