如何将未知尺寸的图像调整到特定尺寸,而不会有太大的变形?

时间:2010-06-23 10:06:00

标签: .net image resize

我想从用户那里获取图片并将其重新调整为特定尺寸,但问题是: 我不知道用户的图像大小,我必须将其重新调整到一定的大小,但变形是这里的负担。

我该如何解决这个问题?根据那个算法有什么算法吗? 或者.net中是否有任何源代码? 最好的问候。

1 个答案:

答案 0 :(得分:1)

就变形而言,您可以使用裁剪和调整大小的组合。您的用户可以帮助您进行裁剪。

我通过.net resize an image

的简单Google搜索在Code Project上找到了此代码
imgPhoto = FixedSize(imgPhotoVert, 300, 300);
imgPhoto.Save(WorkingDirectory + 
    @"\images\imageresize_3.jpg", ImageFormat.Jpeg);
imgPhoto.Dispose();
....
static Image FixedSize(Image imgPhoto, int Width, int Height)
{
    int sourceWidth = imgPhoto.Width;
    int sourceHeight = imgPhoto.Height;
    int sourceX = 0;
    int sourceY = 0;
    int destX = 0;
    int destY = 0; 

    float nPercent = 0;
    float nPercentW = 0;
    float nPercentH = 0;

    nPercentW = ((float)Width/(float)sourceWidth);
    nPercentH = ((float)Height/(float)sourceHeight);
    if(nPercentH < nPercentW)
    {
        nPercent = nPercentH;
        destX = System.Convert.ToInt16((Width - 
                      (sourceWidth * nPercent))/2);
    }
    else
    {
        nPercent = nPercentW;
        destY = System.Convert.ToInt16((Height - 
                      (sourceHeight * nPercent))/2);
    }

    int destWidth  = (int)(sourceWidth * nPercent);
    int destHeight = (int)(sourceHeight * nPercent);

    Bitmap bmPhoto = new Bitmap(Width, Height, 
                      PixelFormat.Format24bppRgb);
    bmPhoto.SetResolution(imgPhoto.HorizontalResolution, 
                     imgPhoto.VerticalResolution);

    Graphics grPhoto = Graphics.FromImage(bmPhoto);
    grPhoto.Clear(Color.Red);
    grPhoto.InterpolationMode = 
            InterpolationMode.HighQualityBicubic;

    grPhoto.DrawImage(imgPhoto, 
        new Rectangle(destX,destY,destWidth,destHeight),
        new Rectangle(sourceX,sourceY,sourceWidth,sourceHeight),
        GraphicsUnit.Pixel);

    grPhoto.Dispose();
    return bmPhoto;
}