从文件中裁剪图像并在 C# 中重新保存

Jon*_*ill 1 c# graphics image

以前从未真正使用过图形。我环顾四周,并从解决我问题的一小部分的答案中拼凑出一些解决方案。但都没有奏效。

我想从文件中加载图像,该图像的大小始终为 320x240。然后我想将其裁剪以获得 240x240 的图像,并修剪每侧外部 40px。完成此操作后,我想另存为新图像。

    private void croptoSquare(string date)
    {
        //Location of 320x240 image
        string fileName = Server.MapPath("~/Content/images/" + date + "contactimage.jpg");

        //New rectangle of final size (I think maybe Point is where I would eventually specify where the crop square site i.e. (40, 0))
        Rectangle cropRect = new Rectangle(new Point(0, 0), new Size(240, 240));
        //Create a Bitmap with correct height/width.
        Bitmap target = new Bitmap(cropRect.Width, cropRect.Height);

        //Load image from file
        using (Image image = Image.FromFile(fileName))
        {
            //Create Graphics object from image
            using (Graphics graphic = Graphics.FromImage(image))
            {
                //Not sure what this does, I found it on a post.
                graphic.DrawImage(image, 
                    cropRect, 
                    new Rectangle(0, 0, target.Width, target.Height),
                    GraphicsUnit.Pixel);

                fileName = Server.MapPath("~/Content/images/" + date + "contactimagecropped.jpg");
                image.Save(fileName);
            }

        }
    }
Run Code Online (Sandbox Code Playgroud)

目前它只是重新保存相同的图像,我不知道为什么。我已将目标矩形指定为 240x240,将源矩形指定为 320x240。

正如我所说,我基本上对使用图形对象一无所知,所以我认为这是公然的。

谁能告诉我如何实现我想要的?

Cha*_*haz 5

private void croptoSquare(string date)
{
    //Location of 320x240 image
    string fileName = Server.MapPath("~/Content/images/" + date + "contactimage.jpg");

    // Create a new image at the cropped size
    Bitmap cropped = new Bitmap(240,240);

    //Load image from file
    using (Image image = Image.FromFile(fileName))
    {
        // Create a Graphics object to do the drawing, *with the new bitmap as the target*
        using (Graphics g = Graphics.FromImage(cropped) )
        {
            // Draw the desired area of the original into the graphics object
            g.DrawImage(image, new Rectangle(0, 0, 240, 240), new Rectangle(40, 0, 240, 240), GraphicsUnit.Pixel);
            fileName = Server.MapPath("~/Content/images/" + date + "contactimagecropped.jpg");
            // Save the result
            cropped.Save(fileName);  
        }
     }

}
Run Code Online (Sandbox Code Playgroud)