【问题标题】:How to Set my X and Y Of Pic To save an image C#如何设置我的图片的 X 和 Y 来保存图像 C#
【发布时间】:2017-05-21 01:04:27
【问题描述】:

例如我有一张图片(这张图片有一个 X:467 Y:300)我只需要从 X:0 Y:0 到 X:200 Y:45 我使用此代码进行裁剪,但我丢失了 X 的数据:0 Y:0 到 X:200 Y:45 我不知道该怎么办

bmp.Save("@image.png", ImageFormat.Png);
        Image img = new Bitmap("@image.png");
        Rectangle source = new Rectangle(0, 0, ww, hh);
        Image cropped = CropImage(img, source);
        cropped.Save(Path.GetDirectoryName("@image.png") + "croppped" + Path.GetExtension("@image.png"));
    }

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

【问题讨论】:

  • 无法重现,您的CropImage 似乎工作正常。这是您的实际代码还是您有机会为矩形参数提供不同的值?
  • @C.Evenhuis 是的,这是我的原始代码有没有办法在不使用原始图像的情况下制作图像?
  • @C.Evenhuis 它的工作但我丢失了一些数据
  • 我想告诉你的是,当我加载一个随机图像并通过你的 CropImage 方法运行它时,它正在做我期望它做的事情 - 没有来自 left 或 top 丢失。我无法修复看起来(至少对我而言)不会被破坏的代码。
  • @C.Evenhuis 我只想在保存位图之前设置大小而不是裁剪图像

标签: c# image bitmap crop


【解决方案1】:

从 cmets 了解到,您希望在将原始图像保存到磁盘之前裁剪图像。在这种情况下,您可以直接将图像提供给裁剪方法:

    // bmp.Save("@image.png", ImageFormat.Png);
    // Image img = new Bitmap("@image.png");
    Rectangle source = new Rectangle(0, 0, ww, hh);
    Image cropped = CropImage(bmp, source); // <-- bmp supplied to crop method directly
    cropped.Save(Path.GetDirectoryName("@image.png") + "croppped" + Path.GetExtension("@image.png"));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-02-02
    • 2012-04-09
    • 2011-03-11
    • 1970-01-01
    • 1970-01-01
    • 2018-11-02
    • 2014-05-13
    相关资源
    最近更新 更多