开发者

JPG cropping in batch to generate square thumbnails

I am looking for a light weight batch tool for cropping image files. The cropping to be done around the center since the aspect ration can be 3:4 or 4:3 This means for 开发者_StackOverflowtaller images, crop will happen at top and at bottom to generate the square image. For wider images, crop will happen at the left and right to generate the square image.

Anyone has used such a tool? I am using .NET 4.0 and C#

I am not looking for ImageMagick or nConvert.


This fist creates an in-memory Bitmap square sized to the square that fits in the original. Then scales that down to thumbSize.

string imagefolder = @"C:\Users\russ\Originals";
string thumbfolder = @"C:\Users\russ\Squares";
int thumbSize = 100;

foreach (string file in System.IO.Directory.GetFiles(imagefolder, "*.jpg"))
{
    using (Image original  = Bitmap.FromFile(file))
    {
        Size size = new Size(
            Math.Min(original.Width, original.Height),
            Math.Min(original.Width, original.Height)
        );
        int translateX = (size.Width - original.Width) / 2;
        int translateY = (size.Height - original.Height) / 2;

        using (Bitmap square = new Bitmap(size.Width, size.Height))
        {
            using (Graphics g = Graphics.FromImage(square))
            {
                 g.DrawImage(original, translateX, translateY, original.Width, original.Height);
            }

            using (Bitmap thumb = new Bitmap(thumbSize, thumbSize))
            {
                using (Graphics g2 = Graphics.FromImage(thumb))
                {
                    g2.DrawImage(square, 0, 0, thumbSize, thumbSize);
                }
                string thumbFile = Path.Combine(thumbfolder, Path.GetFileName(file));
                thumb.Save(thumbFile, ImageFormat.Jpeg);
            }

        }
    }
}


Take a look at ImageMagick.NET. Imagemagick is a set of command-line tools and libraries for linux, and seems someone has ported it to windows/.NET. I've never used the crop functionality, but sure it does what you need. More info and usage seems to be here, the old page of the project.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜