繁体   English   中英

C#图像处理非常慢

[英]C# Image processing is very slow

在过去的几个月中,我一直在开发应用程序,它的功能之一就是可以裁剪图像。 因此,我编写了一个函数,该函数绘制一个透明的橙色矩形,以向用户显示裁剪区域,但工作速度非常慢-有人可以帮助我/向我展示一种使其更快的方法吗?

这是代码:

Image source;

private void pictureBox1_MouseDown(object sender, MouseEventArgs e) {
    mousePos = e.Location;
}

Point mousePos;

private void pictureBox1_MouseMove(object sender, MouseEventArgs e) {
    if (e.Button == MouseButtons.Left) {
        Image editSource = new Bitmap(source);
        Graphics g = Graphics.FromImage(editSource);
        SolidBrush brush = new SolidBrush(
            Color.FromArgb(128, Color.Orange.R, Color.Orange.G, Color.Orange.B));

        int width = e.X - mousePos.X;
        if (width < 0) {
            width *= -1;
        }

        int height = e.Y - mousePos.Y;
        if (height < 0) {
            height *= -1;
        }

        Size cropRectSize = new Size(width, height);
        Rectangle cropRect = new Rectangle(mousePos, cropRectSize);
        g.FillRectangle(brush, cropRect);
        pictureBox1.Image = editSource;
    }
}

使其更快的方法是不要在鼠标移动时创建位图。 如果需要在图形表面上绘制,则无需创建新的位图。

  1. 不要使用图片框。 添加您自己的用户绘制控件
  2. MouseMove使更改的区域无效
  3. 在Draw中,直接写入图形对象,不要在内存中使用位图

因此,所有关于不使用图片框的建议...我会给你一种方法来做;)

其背后的想法是仅使用鼠标移动,鼠标按下等来存储应该绘制的内容。 然后在绘制时使用存储的状态。 每当您在图片框上按下鼠标时,就会绘制一个橙色矩形(即使建议不要使用图片框,也可以将这种方法用于其他表面。)。

    Point startPoint;
    Point currentPoint;
    bool draw = false;
    private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
    {
        startPoint = e.Location;
        draw = true;
    }

    private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
    {
        draw = false;
    }

    private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
    {
        currentPoint = e.Location;
        pictureBox1.Invalidate();
    }

    private void pictureBox1_Paint(object sender, PaintEventArgs e)
    {
        if (draw)
        {
            int startX = Math.Min(startPoint.X, currentPoint.X);
            int startY = Math.Min(startPoint.Y, currentPoint.Y);
            int endX = Math.Max(startPoint.X, currentPoint.X);
            int endY = Math.Max(startPoint.Y, currentPoint.Y);
            e.Graphics.DrawRectangle(Pens.Orange, new Rectangle(startX, startY, endX-startX, endY-startY));
        }
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM