본문 바로가기

C#/Image | Video

C# lock 없이 비트맵 이미지 픽셀 Get/Set

C# lock 없이 비트맵 이미지 픽셀 Get/Set

 

 

using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
 
public class DirectBitmap : IDisposable
{
    public Bitmap Bitmap { get; private set; }
    public Int32[] Bits { get; private set; }
    public bool Disposed { get; private set; }
    public int Height { get; private set; }
    public int Width { get; private set; }
 
    protected GCHandle BitsHandle { get; private set; }
 
    public DirectBitmap(int width, int height)
    {
        Width = width;
        Height = height;
        Bits = new Int32[width * height];
        BitsHandle = GCHandle.Alloc(Bits, GCHandleType.Pinned);
        Bitmap = new Bitmap(width, height, width * 4, PixelFormat.Format32bppPArgb, BitsHandle.AddrOfPinnedObject());
    }
 
    public void SetPixel(int x, int y, Color colour)
    {
        int index = x + (y * Width);
        int col = colour.ToArgb();
 
        Bits[index] = col;
    }
 
    public Color GetPixel(int x, int y)
    {
        int index = x + (y * Width);
        int col = Bits[index];
        Color result = Color.FromArgb(col);
 
        return result;
    }
 
    public void Dispose()
    {
        if (Disposed) return;
        Disposed = true;
        Bitmap.Dispose();
        BitsHandle.Free();
    }
}

'C# > Image | Video' 카테고리의 다른 글

C# Byte To ImageSource  (0) 2020.07.30
이미지 EXIF 정보 가져오기, 이미지 회전 후 저장  (0) 2020.07.27
C# Image To Byte  (0) 2020.07.27
C# 화면 캡쳐 Capture  (0) 2020.07.27