Lately I had to do some image scaling for a .NET compact framework project. While the actual scaling can easily be done by means of the Smart Device Framework (OpenNETCF), the process of deciding whether to adjust the image to the screen’s height or the width takes a  little more effort than on a regular (landscape) computer, due to the multitude of possible screen/picture aspect-ratio combinations (most phones let the user switch between landscape and portrait mode). The following code solves theses issues (IBitmapImage and ImageUtils are OpenNETCF classes):

private IBitmapImage scaleImageToDisplay(Image img, Stream s)
{
float ScreenRatio = this.targetWidth / (float)this.targetHeight;
float ImgRatio = img.Width / (float)img.Height;
 
if (ImgRatio > 1.0f)
{
if (ScreenRatio > ImgRatio)
return ImageUtils.CreateThumbnail(s, new System.Drawing.Size((int)Math.Round(this.targetHeight * ImgRatio, 0), this.targetHeight));
else
return ImageUtils.CreateThumbnail(s, new System.Drawing.Size(this.targetWidth, (int)Math.Round(this.targetWidth / ImgRatio, 0)));
}
else
{
if (ScreenRatio < ImgRatio)
return ImageUtils.CreateThumbnail(s, new System.Drawing.Size(this.targetWidth, (int)Math.Round(this.targetWidth / ImgRatio, 0)));
else
return ImageUtils.CreateThumbnail(s, new System.Drawing.Size((int)Math.Round(this.targetHeight * ImgRatio, 0), this.targetHeight));
}
 
return null;
}

Tags: , , , , ,

 Feed for this Entry

Something to say?