In order to keep the image not distorted when it is reduced, You need to recalculate the size of the thumbnail. The default size of the thumbnail must be greater than or equal to the width. Otherwise, the calculation rules should change.
Today I suddenly want to understand it. Remember it here and use it later. /// <Summary>
/// Obtain the thumbnail size
/// </Summary>
/// <Param name = "oldsize"> Original size </Param>
/// <Param name = "desiredsize"> Target size </Param>
/// <Returns> </returns>
Public Static Size getsacaledsize (size oldsize, size desiredsize)
{
If (Oldsize. Height = 0 | Oldsize. Width = 0 )
Throw New Exception ( " The PIC's width and height not set. " );
Size outsize= NewSize ();
BoolFlag= False;
// If width> length, the width is scaled by width = desiredwidth.
// If the width is <= long, the height is scaled by the length. The height is desiredheight.
If (Oldsize. Width <= Desiredsize. Width && Oldsize. Height <= Desiredsize. Height)
{
Outsize = Oldsize;
Flag = True ;
}
If ( ! Flag)
{
If (Oldsize. Width > Oldsize. Height)
{
Outsize. Width = Desiredsize. width;
Double Ratio = ( Double ) Desiredsize. Width / Oldsize. width;
Outsize. Height = Convert. toint32 (oldsize. Height * Ratio );
Flag = True ;
}
}
If ( ! Flag)
{
Outsize. Height = Desiredsize. height;
Double Ratio = ( Double ) Desiredsize. Height / Oldsize. height;
Outsize. Width = Convert. toint32 (oldsize. Width * Ratio );
}
ReturnOutsize;
}
Unit TestCode:
/// <Summary>
/// This test is used to test the thumbnail sizes under several different sizes.Algorithm.
/// </Summary>
[Testfixture]
Public Class Photocachetestfixture
{
[Test]
Public Void Cachesizetest ()
{
Photos P = New Photos ();
// common situations, the size that grows in width.
P. photoheight = 1200 ;
P. photowidth = 1600 ;
Size sizesacled=P. sacledsize (scaledpicsize. instance. size130x130 );
Console. writeline ( " 1600x1200 " );
Console. writeline (sizesacled. width );
Console. writeline (sizesacled. Height );
Console. writeline ( " ++ " );
Assert. istrue (sizesacled. Width <= 130 );
Assert. istrue (sizesacled. Height <= 130 );
// the source image is smaller than the thumbnail size. returns the original size directly.
P. photowidth = 100 ;
P. photoheight = 80 ;
Size size2=P. sacledsize (scaledpicsize. instance. size130x130 );
Console. writeline ("100x80");
Console. writeline (size2.width );
Console. writeline (size2.height );
Console. writeline ("++");
assert. istrue (size2.width <= 130 );
assert. istrue (size2.height <= 130 );
//Long Version of the image size.
P. photowidth= 80;
P. photoheight= 140;
Size size3=P. sacledsize (scaledpicsize. instance. size130x130 );
console. writeline ( " 80x140 " );
console. writeline (size3.width);
console. writeline (size3.height);
console. writeline ( " ++ " );
Assert. istrue (size3.width<= 130);
Assert. istrue (size3.height<= 130);
}
}