如何在图像C#中设置宽度和高度

时间:2016-12-31 06:09:38

标签: c# image bitmap drawing

我有一个图像,我只需要裁剪

  • 例如我的图像的像素是(257,50)
  • 我只需要(200,20)那张Pic我不需要那张照片 我该怎么做?
  • List item

1 个答案:

答案 0 :(得分:1)

您可以从How to crop/resize image

尝试此功能
private Bitmap CropImage(Image originalImage, Rectangle sourceRectangle,
                    Rectangle? destinationRectangle = null)
    {
        if (destinationRectangle == null)
        {
            destinationRectangle = new Rectangle(Point.Empty, sourceRectangle.Size);
        }

        var croppedImage = new Bitmap(destinationRectangle.Value.Width,
            destinationRectangle.Value.Height);
        using (var graphics = Graphics.FromImage(croppedImage))
        {
            graphics.DrawImage(originalImage, destinationRectangle.Value,
                sourceRectangle, GraphicsUnit.Pixel);
        }
        return croppedImage;
    }

    /// <summary>
    /// Button click to choose an image and test
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void btnCrop_Click(object sender, EventArgs e)
    {
        OpenFileDialog ofd = new OpenFileDialog();
        if (ofd.ShowDialog() == DialogResult.OK)
        {
            string imageFile = ofd.FileName;

            Image img = new Bitmap(imageFile);
            Rectangle source = new Rectangle(0, 0, 120, 20);
            Image cropped = CropImage(img, source);
            // Save cropped image here
            cropped.Save(Path.GetDirectoryName(imageFile) + "\\croppped." + Path.GetExtension(imageFile));
        }
    }