User Tools

Site Tools


notes:csharp:snippets

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revision Previous revision
Next revision
Previous revision
notes:csharp:snippets [2016/11/01]
admin
notes:csharp:snippets [2020/08/26] (current)
Line 52: Line 52:
 } }
 </code> </code>
 +
 +
 +Image scaling: the following pseudo-csharp code scales an input image to fit into a target bounding rectangle:
 +<code csharp>
 +// Scale an image into a bounding rectangle specified by:
 +// - left-upper corner (x1,y1)
 +// - right-bottom corner (x2,y2)
 +int x1, y1, x2, y2; 
 +
 +// Input image size.
 +float img_Height, img_Width;
 +
 +// Calculate the size of the bounding rectangle.
 +// These variables will be adjusted to reflect the target size 
 +// of the image.
 +float w = x2 - x1;
 +float h = y2 - y1;
 +
 +// Calculate helper ratios.
 +float img_hw = img_Height / img_Width;
 +float img_wh = img_Width / img_Height;
 +
 +// Both the width and the height of the image are outside or inside the bounding rectangle.
 +if (img_Width < w && img_Height < h // within the bounding rectangle
 +    || 
 +    img_Width > w && img_Height > h) // outside of the bounding rectangle
 +{
 +    // Scale the width or the height of the image.
 +
 +    // Ratios image-to-boundingRectangle
 +    float rw = img_Width / w;
 +    float rh = img_Height / h;
 +
 +    // Scale accordingly.
 +    if (rw > rh)
 +        h = w * img_hw;
 +    else
 +        w = h * img_wh;
 +}
 +else if (img_Height > h && img_Width < w) // height outside of bounding rectangle
 +{
 +    w = h * img_wh;
 +}
 +else if (img_Width > w && img_Height < h) // width outside of bounding rectangle
 +{
 +    h = w * img_hw;
 +}
 +
 +// Output size of the image: w and h
 +</code>
 +
  
notes/csharp/snippets.1478041750.txt.gz ยท Last modified: 2020/08/26 (external edit)