【问题标题】:c# when crop an image black border appearc#裁剪图像时出现黑色边框
【发布时间】:2017-11-03 11:11:11
【问题描述】:

对不起我的英语。我试图在拖动后裁剪图像。它有效,但我的问题是,黑色粗体边框出现在裁剪图像上。不知道怎么解决。

这是我的代码:

using (Bitmap sourceBitmap = new Bitmap(fullSizeImage))
{
    Rectangle cropRect = new Rectangle(0, 0, sourceWidth, sourceHeight);
    using (Bitmap newBitMap = new Bitmap(cropRect.Width, cropRect.Height))
    {
       using (Graphics g = Graphics.FromImage(newBitMap))
       {
           g.SmoothingMode = SmoothingMode.HighQuality;
           g.PixelOffsetMode = PixelOffsetMode.HighQuality;
           g.CompositingQuality = CompositingQuality.HighQuality;
           g.CompositingMode = CompositingMode.SourceCopy;
           g.DrawImage(sourceBitmap, new Rectangle(0, pp, sourceWidth, sourceHeight), cropRect, GraphicsUnit.Pixel);
           g.InterpolationMode = InterpolationMode.HighQualityBicubic;
           ImageCodecInfo codec = ImageCodecInfo.GetImageEncoders()[4];
           EncoderParameters parameters = new EncoderParameters(1);
           parameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L);
           newBitMap.Save(filePath);
        }
    }
}

这是裁剪后的图片:

【问题讨论】:

    标签: c# asp.net-mvc crop rectangles drawrectangle


    【解决方案1】:

    您的目标图像具有相同的物理尺寸,因为您使用相同的物理尺寸来创建它:

    Rectangle cropRect = new Rectangle(0, 0, sourceWidth, sourceHeight);
    

    当您将原始图像绘制到这个新位图中时,您使用偏移量pp 绘制它,但仍然具有相同的高度和宽度(因此您只裁剪了底部和右侧)。此偏移量仅从该 y 坐标向下“着色”新位图的内存,因此您有黑色边框。

    【讨论】:

    • 我把我的代码改成了这样: RectanglecropRect = new Rectangle(0, 0, sourceWidth, sourceHeight-pp);和 g.DrawImage(sourceBitmap, new Rectangle(0, pp,cropRect.Width,cropRect.Height),cropRect,GraphicsUnit.Pixel);但我仍然看到这种黑色。也许我没听清楚,因为我的英语不够好
    • 不要在(0, pp, 绘制,而是在(0, 0, 绘制。那是左上角。
    • 我还是做错了什么:/我想要这样:如果我将图像拖到顶部,则从底部裁剪图像;如果我将图像拖到底部,则从顶部裁剪图像。现在黑色边框不会出现,但不会像我想要的那样裁剪。代码是这样的: RectanglecropRect = new Rectangle(0, pp, sourceWidth, sourceHeight); g.DrawImage(sourceBitmap, new Rectangle(0, 0,cropRect.Width,cropRect.Height-pp),cropRect,GraphicsUnit.Pixel);
    • 对,所以不要在第二个参数destRect上使用pp偏移量。这个矩形应该是新图像的整个表面。使用第三个参数sourceRect 上的pp 偏移量来定义要从中绘制的区域。此外,您的 cropRect 变量应为 sourceHeight - pp,以使其更小。
    • 要从顶部或底部裁剪,您必须从右下角减去pp(裁剪底部sourceWidth, sourceHeight - pp)或在左上角添加pp(从顶0, pp)
    猜你喜欢
    • 2020-03-20
    • 2013-05-18
    • 2014-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多