Как "обрезать" картинку?
От: Аноним  
Дата: 10.09.06 18:22
Оценка:
Мне для генерации thumbnail необходимо обрезать в пропорции 3х4 и затем создать уменьшенную копию картинки
Как это можно выполнить средствами .NET?
Re: Как "обрезать" картинку?
От: kpumuk Украина http://kpumuk.info/
Дата: 10.09.06 20:02
Оценка:
#Имя: FAQ.Crop.Image
Здравствуйте, <Аноним>, Вы писали:

А>Мне для генерации thumbnail необходимо обрезать в пропорции 3х4 и затем создать уменьшенную копию картинки

А>Как это можно выполнить средствами .NET?

public static Image CropImage(Image sourceImage, int targetWidth, int targetHeight)
{
        int sourceWidth = sourceImage.Width;
        int sourceHeight = sourceImage.Height;
        int sourceX = 0, sourceY = 0;
        int targetX = 0, targetY = 0;

        float ratio, ratioWidth, ratioHeight;

        ratioWidth = ((float)targetWidth / (float)sourceWidth);
        ratioHeight = ((float)targetHeight / (float)sourceHeight);

        if (ratioHeight < ratioWidth)
        {
                ratio = ratioWidth;
                targetY = (int)((targetHeight - sourceHeight * ratio) / 2);
        }
        else
        {
                ratio = ratioHeight;
                targetX = (int)((targetWidth - sourceWidth * ratio) / 2);
        }

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

        Bitmap targetImage = new Bitmap(targetWidth, targetHeight, PixelFormat.Format24bppRgb);
        targetImage.SetResolution(sourceImage.HorizontalResolution, sourceImage.VerticalResolution);

        using (Graphics g = Graphics.FromImage(targetImage))
        {
            g.CompositingQuality = CompositingQuality.HighQuality;
            g.SmoothingMode = SmoothingMode.HighQuality;
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;

            g.DrawImage(sourceImage,
                                    new Rectangle(targetX, targetY, destWidth, destHeight),
                                    new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight),
                                    GraphicsUnit.Pixel);
        }
        
        return targetImage;
}
... << RSDN@Home 1.1.4 stable SR1 rev. 568>>
Re[2]: Как "обрезать" картинку?
От: kpumuk Украина http://kpumuk.info/
Дата: 10.09.06 20:11
Оценка:
Здравствуйте, kpumuk, Вы писали:

K> return targetImage


Забыл точку с запятой
... << RSDN@Home 1.1.4 stable SR1 rev. 568>>
Re[2]: Как "обрезать" картинку?
От: Аноним  
Дата: 10.09.06 20:50
Оценка:
Спасибо большое, действительно полезная вещь
 
Подождите ...
Wait...
Пока на собственное сообщение не было ответов, его можно удалить.