In a nutshell, the goal of the following code is to resize the image based on the size of the target and the multiplier (1x, 2x, 3x). This works great, except that I have not determined that some images rotate.
public void ResizeImage(TargetSize targetSize, ResizeMultiplier multiplier, Stream input, Stream output)
{
using (var image = Image.FromStream(input))
{
var scaleFactor = targetSize.CalculateScaleFactor(image.Width, image.Height);
scaleFactor /= (int)multiplier;
var newWidth = (int)Math.Floor(image.Width / scaleFactor);
var newHeight = (int)Math.Floor(image.Height / scaleFactor);
using (var newBitmap = new Bitmap(newWidth, newHeight))
{
using (var imageScaler = Graphics.FromImage(newBitmap))
{
imageScaler.CompositingQuality = CompositingQuality.HighQuality;
imageScaler.SmoothingMode = SmoothingMode.HighQuality;
imageScaler.InterpolationMode = InterpolationMode.HighQualityBicubic;
var imageRectangle = new Rectangle(0, 0, newWidth, newHeight);
imageScaler.DrawImage(image, imageRectangle);
newBitmap.Save(output, image.RawFormat);
}
}
}
}
public class TargetSize
{
private readonly int _width;
private readonly int _height;
public TargetSize(int width, int height)
{
_height = height;
_width = width;
}
public decimal CalculateScaleFactor(int width, int height)
{
var heightScaleFactor = decimal.Divide(height, _height);
var widthScaleFactor = decimal.Divide(width, _width);
return widthScaleFactor > heightScaleFactor ? heightScaleFactor : widthScaleFactor;
}
}
[Test]
public void ResizeImage_Persistant_Single()
{
using (var fileStream = File.OpenRead(@"TestData\dog.jpg"))
{
using (var outputStream = new MemoryStream())
{
_sut.ResizeImage(new TargetSize(200, 200), ResizeMultiplier.Medium, fileStream, outputStream);
using (var newImage = Image.FromStream(outputStream))
{
newImage.Save(@"TestData\ImageResizerTests.ResizeImage_Persistant_Single.jpg");
}
}
}
}
For example, this image:
scales accordingly, but this image:
turned upside down. It is worth noting that the image also turned upside down when it was in the preview area to upload it to this site. The fact (which I obviously just discovered) strongly makes me think that something is funny with the image. No matter what my code should handle it.
Imgur "" ( , ), Google . ( FireFox ) Save Image As..., . , ... , 180 . , , ...
, - .
:
, /, . , 180 . ( 90 270 ). , newWidth
, newHeight
, scaleFactor
, targetSize
(private variables) image.Height/image.Width
, 180 .
, . ; Windows, Windows, Macintosh, FireFox .. iOS , . , , .