简体   繁体   English

如何将Parallel.ForEach与图像对象一起使用?

[英]How to use Parallel.ForEach with image object?

Now my method is : 现在我的方法是:

public static byte[] ImageToByte(Image img)
{
    byte[] byteArray = new byte[0];
    using (MemoryStream stream = new MemoryStream())
    {
        img.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp);
        stream.Close();
        byteArray = stream.ToArray();
    }

    return byteArray;
}

after read this . 看完这篇 And i still confuse and can't find a way to use this. 而且我仍然感到困惑,无法找到使用此方法的方法。

So my question is how to use Parallel.ForEach or Parallel anything with my method. 所以我的问题是如何在我的方法中使用Parallel.ForEach或Parallel任何东西。

my goal is to speed this method by using more cores of CPU to speed this up anything advice? 我的目标是通过使用更多的CPU内核来加快此方法的速度。

ps. ps。 I not serious if i can do the parallel with my method and that not speed up anything I just want to try this and record the result Thank all your guy . 我不认真,如果我可以使用我的方法进行并行操作并且不加快速度,那么我只想尝试一下并记录结果,谢谢大家。

You can only use the parallel processing if you have multiple images. 如果您有多个图像,则只能使用并行处理。

Imagine going through seperate images in a for each loop you could do this: 想象一下在每个循环中遍历单独的图像,您可以这样做:

Parallel.ForEach(images, img =>
    {
        byte[] byteArray = new byte[0];
        using (MemoryStream stream = new MemoryStream())
        {
            img.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp);
            stream.Close();
            byteArray = stream.ToArray();
        }
    });

If you really want to speed up the code you could do : 如果您真的想加速代码,可以执行以下操作:

            BitmapData d = image.LockBits(new Rectangle(0, 0, image.Width, image.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
            int length = Math.Abs(d.Stride) * image.Height;
            byte[] buff = new byte[length]; 
            Marshal.Copy(d.Scan0, buff, 0, length);
            image.UnlockBits(d);

            return buff;

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

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