2016-04-01 4 views
-2

У меня Bitmaps с соотношением сторон, как следующее или могут быть в любой пропорции ..Обрезка растрового изображения до 1: 1 Соотношение сторон

enter image description here

enter image description here

Когда пользователь указывает option Мне нужен способ обрезать окружающие части с этих изображений, чтобы получить изображение с соотношением сторон 1: 1. Как это

enter image description here

Я думаю, что я возьму центральную точку в этих изображениях и вырежьте стороны ..

Я нашел этот метод в веб-платформе .. но Bitmap не имеет метод 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; 
     } 

Пожалуйста, советы способ решения этого вопроса.

+1

Существует перегрузка DrawImage, которая принимает исходный прямоугольник. Используйте это для рисования в целевом растровом изображении! – TaW

+0

Вы просите преобразовать прямоугольник изображения в квадрат? –

+0

@IvanStoev да .. вид – techno

ответ

1

Вы можете использовать что-то вроде этого:

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; 
} 

Это обрезку от центра. Если вы хотите обрезать снизу/справа, просто используйте var sourceRect = new Rectangle(0, 0, size, size);.

+0

Спасибо:) ............. – techno