C# crop image from center

前端 未结 6 1703
我寻月下人不归
我寻月下人不归 2020-12-09 13:48

I am developing application using .NET(4.5) MVC(4.0) C#(5.0). i want to generate image thumbnail from image that i already have. Now requirement is like it should generate t

6条回答
  •  孤城傲影
    2020-12-09 14:54

    Done this a few times before, the trick is to fit the Height of the image first, the rescale the Width to the proportion that you had to reduce the Height, then repeat from the Width if it still doesnt fit by the Width, and reducing the newer scaled Height by that additional proportion. That way you have a thumbnail that always fits, possibly some whitespace in the X or Y, but the image is still to the same proportions, not stretched.

    int originalHeight;
    int originalWidth;
    int imageHeight;
    int imageWidth;
    int requiredHeight;
    int requiredWidth;
    double scale;
    
    if(originalHeight > requiredHeight)
    {
        scale = requiredHeight / originalHeight;
        imageHeight = requiredHeight;
        imageWidth = originalHeight * scale;
    }
    
    if(imageWidth > requiredWidth)
    {
        scale = requiredWidth / imageWidth;
        imageWidth = requiredWidth;
        imageHeight = imageHeight * scale;
    }
    

    And then drawing that Image into a new Bitmap of this size using Graphics object

提交回复
热议问题