Skip to content

Commit

Permalink
#1031 Image Resize Rounding Bug
Browse files Browse the repository at this point in the history
  • Loading branch information
skoshelev committed Jun 1, 2016
1 parent 03146fa commit 63d7b3e
Showing 1 changed file with 17 additions and 15 deletions.
32 changes: 17 additions & 15 deletions src/Libraries/Nop.Services/Media/PictureService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -93,44 +93,46 @@ public PictureService(IRepository<Picture> pictureRepository,
protected virtual Size CalculateDimensions(Size originalSize, int targetSize,
ResizeType resizeType = ResizeType.LongestSide, bool ensureSizePositive = true)
{
var newSize = new Size();
float width, height;

switch (resizeType)
{
case ResizeType.LongestSide:
if (originalSize.Height > originalSize.Width)
{
// portrait
newSize.Width = (int)(originalSize.Width * (float)(targetSize / (float)originalSize.Height));
newSize.Height = targetSize;
// portrait
width = originalSize.Width * (targetSize / (float)originalSize.Height);
height = targetSize;
}
else
{
// landscape or square
newSize.Height = (int)(originalSize.Height * (float)(targetSize / (float)originalSize.Width));
newSize.Width = targetSize;
width = targetSize;
height = originalSize.Height * (targetSize / (float) originalSize.Width);
}
break;
case ResizeType.Width:
newSize.Height = (int)(originalSize.Height * (float)(targetSize / (float)originalSize.Width));
newSize.Width = targetSize;
width = targetSize;
height = originalSize.Height * (targetSize / (float)originalSize.Width);
break;
case ResizeType.Height:
newSize.Width = (int)(originalSize.Width * (float)(targetSize / (float)originalSize.Height));
newSize.Height = targetSize;
width = originalSize.Width * (targetSize / (float)originalSize.Height);
height = targetSize;
break;
default:
throw new Exception("Not supported ResizeType");
}

if (ensureSizePositive)
{
if (newSize.Width < 1)
newSize.Width = 1;
if (newSize.Height < 1)
newSize.Height = 1;
if (width < 1)
width = 1;
if (height < 1)
height = 1;
}

return newSize;
//we invoke Math.Round to ensure that no white background is rendered - http://www.nopcommerce.com/boards/t/40616/image-resizing-bug.aspx
return new Size((int)Math.Round(width), (int)Math.Round(height));
}

/// <summary>
Expand Down

0 comments on commit 63d7b3e

Please sign in to comment.