使用C#时,未显示实际图像时的裁剪图像问题

6
我正在使用JCrop来裁剪图像。 如果我向用户显示实际图像,它可以正常工作。 但是,如果我展示的是缩略图而不是实际图像,那么我获取的将是缩略图的坐标。那么,基于这些坐标如何裁剪图像呢?在这里,我传递了已保存图像的路径。

简而言之,如果已保存的图像大小为715×350,则根据CSS在弹出窗口中显示其小尺寸。因此,我将获得该小尺寸图像的坐标,并将这些坐标应用在主要图像上。

我的代码:
using (System.Drawing.Image OriginalImage = System.Drawing.Image.FromFile(Img))
            {
                using (System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(Width, Height))
                {
                    bmp.SetResolution(OriginalImage.HorizontalResolution, OriginalImage.VerticalResolution);

                    using (System.Drawing.Graphics Graphic = System.Drawing.Graphics.FromImage(bmp))
                    {
                        Graphic.SmoothingMode = SmoothingMode.AntiAlias;
                        Graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
                        Graphic.PixelOffsetMode = PixelOffsetMode.HighQuality;
                        Graphic.DrawImage(OriginalImage, new System.Drawing.Rectangle(0, 0, Width, Height), X, Y, Width, Height, System.Drawing.GraphicsUnit.Pixel);

                        MemoryStream ms = new MemoryStream();
                        bmp.Save(ms, OriginalImage.RawFormat);

                        ms.Close();
                        ms.Flush();
                        ms.Dispose();

                        return ms.GetBuffer();
                    }
                }
            }
2个回答

5
您展示的代码是用于调整大小而不是裁剪(在Graphic.DrawImage()调用中,您不需要关心裁剪坐标,只需应用目标宽度/高度即可)。
要裁剪图像,您可以使用Bitmap.Clone()方法。只需将从JCrop中提取的裁剪坐标传递给它。(在下面的示例中是cropzone)。
public static async Task CropImage()
{
    var client = new WebClient();
    var sourceimg = new Uri(@"http://logonoid.com/images/stack-overflow-logo.png");
    var destination = new FileInfo(Path.Combine(Directory.GetCurrentDirectory(), "logoCropped.png"));
    if (destination.Exists)
        destination.Delete();
    using (Stream sourceStream = await client.OpenReadTaskAsync(sourceimg))
    {
        using (Bitmap source = new Bitmap(sourceStream))
        {
            Rectangle cropzone = new Rectangle(0, 0, 256, 256);
            using (Bitmap croppedBitmap = source.Clone(cropzone, source.PixelFormat))
            {
                croppedBitmap.Save(destination.FullName, ImageFormat.Png);
            }
        }
    }
}

关于您的代码的一些建议:

  • 仅进行裁剪时,不涉及调整大小操作。因此,SmoothingModeInterpolationModePixelOffsetMode参数在这里是无用的。
  • 关于MemoryStream,最好在using语句中使用它。这可以避免手动调用Close()Dispose()方法,并保证无论发生什么情况都会被调用。至于Flush()方法,在MemoryStream类上什么也不做

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接