Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Steps to achieve what you want:</p> <ol> <li>Figure out ratio of height to width</li> <li>Scale the larger dimension down to 150px and the smaller dimension down to ratio * 150px.</li> <li>Draw the result in the middle of a 150x150 bitmap.</li> </ol> <p>This code will do exactly that (c#):</p> <pre><code>using ( Image img = Image.FromStream( FU.PostedFile.InputStream ) ) { int sourceWidth = img.Width; int sourceHeight = img.Height; int desiredHeight = 150; int desiredWidth = 150; double heightToWidthRatio = sourceHeight / ( double )sourceWidth; //This draw method will always center the image horizonally or vertically, as appropriate using ( Bitmap thumbnailBitmap = new Bitmap( desiredWidth, desiredHeight ) ) { using ( Graphics thumbnailGraph = Graphics.FromImage( thumbnailBitmap ) ) { thumbnailGraph.CompositingQuality = CompositingQuality.HighQuality; thumbnailGraph.SmoothingMode = SmoothingMode.HighQuality; thumbnailGraph.InterpolationMode = InterpolationMode.HighQualityBicubic; float destWidth = ( heightToWidthRatio &gt; 1f ) ? ( float )( desiredWidth / heightToWidthRatio ) : desiredWidth; float destHeight = ( heightToWidthRatio &gt; 1f ) ? desiredHeight : ( float )( desiredHeight * heightToWidthRatio ); float destX = ( desiredWidth - destWidth ) / 2f; float destY = ( desiredHeight - destHeight ) / 2f; thumbnailGraph.DrawImage( img, new RectangleF( destX, destY, destWidth, destHeight ), new Rectangle( sourceWidth, sourceHeight, sourceWidth, sourceHeight ), GraphicsUnit.Pixel ); } } } </code></pre> <p>Continue to write out the file as you have been, previously. The important part is the four float values in the middle and the fact that it uses a RectangleF in the DrawImage function, to truly center, even on fractional values. If you do not want that behavior due to excessive antialiasing, just Math.Floor the values and continue to use Rectangle and ints.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload