Allow an Image to be accessed by several threads

前端 未结 2 1918
说谎
说谎 2021-01-05 02:13

I\'m trying to do some image processing in C#. I want to use some threads to do parallel computations on several zones in my image. Threads are actually getting and setting

2条回答
  •  醉梦人生
    2021-01-05 02:43

    Another solution would be to create a temporary container with the information about the Bitmap such as width, height, stride, buffer and pixel format. Once you need to access the Bitmap in parallel just create it based on the information in the temporary container.

    For this we need an extension method to get the buffer and stride of a Bitmap:

    public static Tuple ToBufferAndStride(this Bitmap bitmap)
    {
        BitmapData bitmapData = null;
    
        try
        {
            bitmapData = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), 
                ImageLockMode.ReadOnly, bitmap.PixelFormat);
    
            return new Tuple(bitmapData.Scan0, bitmapData.Stride);
        }
        finally
        {
            if (bitmapData != null)
                bitmap.UnlockBits(bitmapData);
        }
    }
    

    This extension method will be used inside the temporary container:

    public class BitmapContainer
    {
        public PixelFormat Format { get; }
    
        public int Width { get; }
    
        public int Height { get; }
    
        public IntPtr Buffer { get; }
    
        public int Stride { get; set; }
    
        public BitmapContainer(Bitmap bitmap)
        {
            if (bitmap == null)
                throw new ArgumentNullException(nameof(bitmap));
    
            Format = bitmap.PixelFormat;
            Width = bitmap.Width;
            Height = bitmap.Height;
    
            var bufferAndStride = bitmap.ToBufferAndStride();
            Buffer = bufferAndStride.Item1;
            Stride = bufferAndStride.Item2;
        }
    
        public Bitmap ToBitmap()
        {
            return new Bitmap(Width, Height, Stride, Format, Buffer);
        }
    }
    

    Now you can use the BitmapContainer in a method executed in parallel:

    BitmapContainer container = new BitmapContainer(bitmap);
    
    Parallel.For(0, 10, i =>
    {
        Bitmap parallelBitmap = container.ToBitmap();
        // ...
    });
    

提交回复
热议问题