6

私はこれに数回出くわし、そこに置くのが良いと思いました。最適な画像のサイズ変更および/またはトリミング ロジックは何ですか。アイデアは、ターゲット画像、寸法、トリミングフラグを使用して何らかのメソッドが呼び出されるということです。これにより、目的の画像が返されるか、保存されます。

私のは以下です。VB から C# に変換されたので、小さなバグはありますが、私たちが見ているのはロジックです。

// INIT
// On/off
bool WeAreCropping = true;

// Get some dimensions
int TargetWidth = RequestedWidth;
int TargetHeight = RequestedHeight;
int SourceWidth = SourceImage.Width;
int SourceHeight = SourceImage.Height;
int ResizeWidth = TargetWidth;
int ResizeHeight = TargetHeight;

// GET RESIZE VALUES
// Are we cropping?
if (WeAreCropping) {

    // Get source and target aspect ratio
    double SourceAspectRatio = SourceWidth / SourceHeight;
    double TargetAspectRatio = TargetWidth / TargetHeight;

    // Compare aspect ratios to find out if we should we resize by 
    // width or height or nothing
    if (TargetAspectRatio < SourceAspectRatio) {
        ResizeWidth = TargetHeight / SourceHeight * SourceWidth;
    }
    else if (TargetAspectRatio > SourceAspectRatio) {
        ResizeHeight = TargetWidth / SourceWidth * SourceHeight;
    }
    else {
      // Same aspect ratio
    }


}
else {

    // If the target image is bigger than the source
    if (TargetWidth > SourceWidth && TargetHeight > SourceHeight) {
        TargetWidth = SourceWidth;
        TargetHeight = SourceHeight;
    }

    double Ratio = 0;

    // What ratio should we resize it by
    if (SourceWidth / TargetWidth > SourceHeight / TargetHeight) {
        Ratio = SourceWidth / TargetWidth;
    }
    else {
        Ratio = SourceHeight / TargetHeight;
    }

    ResizeWidth = Math.Ceiling(SourceWidth / Ratio);

    ResizeHeight = Math.Ceiling(SourceHeight / Ratio);
}

// TIME TO DO SUMFINK
// Resize the image using ResizeWidth and ResizeHeight
// Do it

if (WeAreCropping) {
    // Crop the resized image at the center TargetWidth and TargetHeight
    // Do it
}

これはもっとエレガントにできると思うので、もっとうまくやれるかもしれません。

4

2 に答える 2

0

これはおそらく必要なものよりも少し複雑ですが、いくつかの高度なトリミング手法の例については、これを確認してください

于 2010-06-22T02:23:24.133 に答える