简体   繁体   English

在C#中裁剪图像

[英]Crop an image in C#

I am doing sort of a limited graphics editor in a desktop application in c# 3.5 GDI. 我在c#3.5 GDI的桌面应用程序中执行某种受限的图形编辑器。 the user first selects an image which is shown in a picturebox control which is smaller in size so image resizing is done to fit the picture. 用户首先选择在图片框控件中显示的尺寸较小的图像,然后进行图像调整大小以适合该图片。

For cropping, the user selects the area to crop. 对于裁剪,用户选择要裁剪的区域。 there are a number of example on the net that explains how to crop the image but none of them explains the case when the area is selected on a thumbnail but the cropping is done on the original image ie some kind of mapping is done between the two images. 网络上有很多示例,它们说明了如何裁剪图像,但都没有一个示例说明在缩略图上选择区域但在原始图像上进行裁剪的情况,即在两者之间进行了某种映射图片。

all the graphic editor provide similar functionality. 所有的图形编辑器都提供类似的功能。 can you direct me to a link which explains how to do this? 您可以将我定向到一个说明如何执行此操作的链接吗?

Sounds to me like you need to calculate the crop rectangle on the original image yourself based on the relative sizes of the picture and the thumbnail. 在我看来,您需要根据图片和缩略图的相对大小自己计算原始图像上的裁剪矩形。

public static class CoordinateTransformationHelper
{
    public static Point ThumbToOriginal(this Point point, Size thumb, Size source)
    {
        Point rc = new Point();
        rc.X = (int)((double)point.X / thumb.Width * source.Width);
        rc.Y = (int)((double)point.Y / thumb.Height * source.Height);
        return rc;
    }

    public static Size ThumbToOriginal(this Size size, Size thumb, Size source)
    {
        Point pt = new Point(size);
        Size rc = new Size(pt.ThumbToOriginal(thumb, source));
        return rc;
    }

    public static Rectangle ThumbToOriginal(this Rectangle rect, Size thumb, Size source)
    {
        Rectangle rc = new Rectangle();
        rc.Location = rect.Location.ThumbToOriginal(thumb, source);
        rc.Size = rect.Size.ThumbToOriginal(thumb, source);
        return rc;
    }
}

Usage example: 用法示例:

Size thumb = new Size(10, 10);
Size source = new Size(100, 100);
Console.WriteLine(new Point(4, 4).ThumbToOriginal(thumb, source));
Console.WriteLine(new Rectangle(4, 4, 5, 5).ThumbToOriginal(thumb, source));

here's a really easy method to crop a System.Drawing.Image 这是裁剪System.Drawing.Image的一种非常简单的方法

public static Image CropImage(Image image, Rectangle area)
{
    Image cropped = null;

    using (Bitmap i = new Bitmap(image))
    using (Bitmap c = i.Clone(area, i.PixelFormat))
        cropped = (Image)c;

    return cropped;
}

pass in an Image and the area that you want to crop and that should do it 传递图像和您想要裁剪的区域,应该这样做

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM