How to crop an image using C#?

后端 未结 14 845
忘掉有多难
忘掉有多难 2020-11-22 05:16

How can I write an application that will crop images in C#?

相关标签:
14条回答
  • 2020-11-22 06:10

    I was looking for a easy and FAST function with no additional libary to do the job. I tried Nicks solution, but i needed 29,4 sec to "extract" 1195 images of an atlas file. So later i managed this way and needed 2,43 sec to do the same job. Maybe this will be helpful.

    // content of the Texture class
    public class Texture
    {
        //name of the texture
        public string name { get; set; }
        //x position of the texture in the atlas image
        public int x { get; set; }
        //y position of the texture in the atlas image
        public int y { get; set; }
        //width of the texture in the atlas image
        public int width { get; set; }
        //height of the texture in the atlas image
        public int height { get; set; }
    }
    
    Bitmap atlasImage = new Bitmap(@"C:\somepicture.png");
    PixelFormat pixelFormat = atlasImage.PixelFormat;
    
    foreach (Texture t in textureList)
    {
         try
         {
               CroppedImage = new Bitmap(t.width, t.height, pixelFormat);
               // copy pixels over to avoid antialiasing or any other side effects of drawing
               // the subimages to the output image using Graphics
               for (int x = 0; x < t.width; x++)
                   for (int y = 0; y < t.height; y++)
                       CroppedImage.SetPixel(x, y, atlasImage.GetPixel(t.x + x, t.y + y));
               CroppedImage.Save(Path.Combine(workingFolder, t.name + ".png"), ImageFormat.Png);
         }
         catch (Exception ex)
         {
              // handle the exception
         }
    }
    
    0 讨论(0)
  • 2020-11-22 06:12

    You can use Graphics.DrawImage to draw a cropped image onto the graphics object from a bitmap.

    Rectangle cropRect = new Rectangle(...);
    Bitmap src = Image.FromFile(fileName) as Bitmap;
    Bitmap target = new Bitmap(cropRect.Width, cropRect.Height);
    
    using(Graphics g = Graphics.FromImage(target))
    {
       g.DrawImage(src, new Rectangle(0, 0, target.Width, target.Height), 
                        cropRect,                        
                        GraphicsUnit.Pixel);
    }
    
    0 讨论(0)
提交回复
热议问题