为什么这种方法很慢?

时间:2013-12-21 01:36:35

标签: c# winforms

我试图使用LockBits从Bitmap读取像素,但每次花费2-4秒。

这是方法:

public static Bitmap LockBits(Bitmap bmp)
{
    PixelFormat pxf = PixelFormat.Format24bppRgb;
    Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
    BitmapData bmpData =
    bmp.LockBits(rect, ImageLockMode.ReadWrite, pxf);
    IntPtr ptr = bmpData.Scan0;
    int numBytes = bmpData.Stride * bmp.Height;
    byte[] rgbValues = new byte[numBytes];
    Marshal.Copy(ptr, rgbValues, 0, numBytes);
    for (int counter = 0; counter < rgbValues.Length; counter += 6)
        rgbValues[counter] = (byte)tolerancenumeric;
    Marshal.Copy(rgbValues, 0, ptr, numBytes);
    bmp.UnlockBits(bmpData);
    bmp.Save(@"d:\testbmplockbits.bmp");
    return bmp;
}

这个:(byte)tolerancenumeric在我更改之前是值10所以我可以从Form1 numericupdown更改此值:

private void numericUpDown1_ValueChanged(object sender, EventArgs e)
{
    CloudEnteringAlert.tolerancenum = (int)numericUpDown1.Value;
    pictureBox1.Image = CloudEnteringAlert.LockBits(bitmapwithclouds);
}

我认为使用LockBits会让它变得更快但是当我在程序运行时单击numericupdown更改其值时,它需要2-4秒,直到值更改并且图片框中的图像正在更新。

该方法有什么问题?

2 个答案:

答案 0 :(得分:0)

使用不安全,这快速运行

using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
    Bitmap test = new Bitmap(512, 512, PixelFormat.Format24bppRgb);

    public Form1()
    {
        InitializeComponent();
        numericUpDown1.Minimum = 0; numericUpDown1.Maximum = 255;
    }

    unsafe public static Bitmap LockBits(Bitmap bmp, int tolerancenumeric)
    {
        BitmapData bmpData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadWrite, bmp.PixelFormat);

        byte* ptr = (byte*)bmpData.Scan0;
        int numBytes = bmpData.Stride * bmp.Height;

        for (int counter = 0; counter < numBytes; counter += 6)
            *(ptr + counter) = (byte)tolerancenumeric;

        bmp.UnlockBits(bmpData);
        return bmp;
    }

    private void numericUpDown1_ValueChanged(object sender, EventArgs e)
    {
        pictureBox1.Image = LockBits(test, (int)numericUpDown1.Value);
    }
}
}

答案 1 :(得分:0)

尝试在图片框上刷新:

pictureBox1.Refresh();
相关问题