2016-04-01 13 views
-2

Iは、次の又は任意のアスペクト比であってもよいようなアスペクト比を有するビットマップを持って..は1ビットマップをトリミング:1のアスペクト比

enter image description here

enter image description here

をユーザが指定するとオプション私は1:1アスペクト比の画像が生成されるようにこれらの画像から周囲の部分を切り取る方法が必要です。 この

enter image description here

のように私は、私は、Webプラットフォームでは、この方法を発見した

..私はこれらのイメージに中心点を取ると側面をトリミングすると思います..しかし、ビットマップはありません。 a Crop方法

public static WebImage BestUsabilityCrop(WebImage image, decimal targetRatio) 
     { 
      decimal currentImageRatio = image.Width/(decimal)image.Height; 
      int difference; 

      //image is wider than targeted 
      if (currentImageRatio > targetRatio) 
      { 
       int targetWidth = Convert.ToInt32(Math.Floor(targetRatio * image.Height)); 
       difference = image.Width - targetWidth; 
       int left = Convert.ToInt32(Math.Floor(difference/(decimal)2)); 
       int right = Convert.ToInt32(Math.Ceiling(difference/(decimal)2)); 
       image.Crop(0, left, 0, right); 
      } 
      //image is higher than targeted 
      else if (currentImageRatio < targetRatio) 
      { 
       int targetHeight = Convert.ToInt32(Math.Floor(image.Width/targetRatio)); 
       difference = image.Height - targetHeight; 
       int top = Convert.ToInt32(Math.Floor(difference/(decimal)2)); 
       int bottom = Convert.ToInt32(Math.Ceiling(difference/(decimal)2)); 
       image.Crop(top, 0, bottom, 0); 
      } 
      return image; 
     } 

この問題に取り組む方法をアドバイスしてください。これは、中心からトリミングん

public static Image Crop(Image source) 
{ 
    if (source.Width == source.Height) return source; 
    int size = Math.Min(source.Width, source.Height); 
    var sourceRect = new Rectangle((source.Width - size)/2, (source.Height - size)/2, size, size); 
    var cropped = new Bitmap(size, size); 
    using (var g = Graphics.FromImage(cropped)) 
     g.DrawImage(source, 0, 0, sourceRect, GraphicsUnit.Pixel); 
    return cropped; 
} 

+1

ソース矩形をとるDrawImageオーバーロードがあります。これを使用して適切なターゲットビットマップに描画します。 – TaW

+0

画像矩形を四角形に変換するよう求めていますか? –

+0

@IvanStoev yeah .. kind of – techno

答えて

1

あなたはこのようなものを使用することができます。下部/右から切り抜きたい場合は、var sourceRect = new Rectangle(0, 0, size, size);を使用してください。

+0

ありがとう:)............. – techno

関連する問題