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

时间:2015-11-10 17:21:41

标签: c# image graphics

之前从未真正使用过Graphics。我已经浏览了这个问题,并将一些解决方案拼凑在一起,这些解决方案解决了我的问题的一小部分。但没有一个有效。

我想从文件中加载图像,文件的大小始终为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);
            }

        }
    }

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

正如我所说,我基本上对使用图形对象一无所知,所以我想这是明显的。

有人能告诉我如何实现我的目标吗?

2 个答案:

答案 0 :(得分:1)

答案 1 :(得分:1)

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

}