加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 08:46:22 所属栏目:百科 来源:网络整理
导读:我正在使用JCrop来裁剪图像.如果我向用户显示实际图像,它工作正常.但是,如果我显示调整大小图像而不是实际图像,那么我将获得调整大小图像的坐标. 然后,我如何基于它裁剪图像?在这里,我正在传递保存图像的图像路径. 简而言之,如果为715 * 350,如果保存图像大
我正在使用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,Width,Height),X,Y,Height,System.Drawing.GraphicsUnit.Pixel);

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

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

                        return ms.GetBuffer();
                    }
                }
            }

解决方法

您显示的代码用于调整大小,而不是用于裁剪(在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,256,256);
            using (Bitmap croppedBitmap = source.Clone(cropzone,source.PixelFormat))
            {
                croppedBitmap.Save(destination.FullName,ImageFormat.Png);
            }
        }
    }
}

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

>刚刚裁剪时,没有涉及调整大小的操作.所以SmoothingMode,InterpolationMode,PixelOffsetMode参数在这里没用.
>关于MemoryStream,最好在using语句中使用它.它避免了对Close()和Dispose()的手动调用,并保证无论发生什么事情都会被调用.关于Flush()方法,它在MemoryStream类上为just does nothing.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读