文章来源地址https://uudwc.com/A/JEVJ
1、GetPixel函数
C# 图片 Bitmap 的像素读取函数为:
Color GetPixel(int x, int y);
GetPixel函数检索指定坐标处像素的红、绿、蓝(RGB)颜色值。
2、SetPixel函数
图片像素设置的函数为:
void SetPixel(int x, int y, Color c);
设置此位图中指定像素的颜色。C#public void SetPixel(int x,int y,System.Drawing.Color Color);参数x Int32要设置的像素的x坐标。y Int32要设置的像素的y坐标。颜色颜色表示要分配给指定像素的颜色的颜色结构。
但这两个函数都很慢,稍微大一些的图片,无法忍受的速度!
建议使用快速方法,源代码(POWER BY 315SOFT.COM):
(请打开编译器的指针安全 safe )
using System;
using System.Text;
using System.Collections;
using System.Windows.Forms;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
namespace Legalsoft.Truffer.Draw
{
public class FastBitmap
{
internal Bitmap m_oBitmap { get; set; }
private BitmapData m_oBitmapData { get; set; }
public FastBitmap(Int32 nWidth, Int32 nHeight, PixelFormat pixelFormat)
{
m_oBitmap = new Bitmap(nWidth, nHeight, pixelFormat);
}
~FastBitmap()
{
Dispose(false);
}
public void Dispose()
{
GC.SuppressFinalize(this);
Dispose(true);
}
protected virtual void Dispose(Boolean bDisposing)
{
Unlock();
if (bDisposing)
{
m_oBitmap.Dispose();
}
}
private FastBitmap()
{
}
public Object Clone()
{
FastBitmap fbClone = new FastBitmap();
fbClone.m_oBitmap = (Bitmap)m_oBitmap.Clone();
return fbClone;
}
public Int32 Width
{
get { return m_oBitmap.Width; }
}
public Int32 Height
{
get { return m_oBitmap.Height; }
}
public void Lock()
{
m_oBitmapData = m_oBitmap.LockBits(
new Rectangle(0, 0, m_oBitmap.Width, m_oBitmap.Height),
ImageLockMode.ReadWrite,
m_oBitmap.PixelFormat
);
}
unsafe public Color GetPixel(Int32 x, Int32 y)
{
if (m_oBitmapData.PixelFormat == PixelFormat.Format32bppArgb)
{
Byte* b = (Byte*)m_oBitmapData.Scan0 + (y * m_oBitmapData.Stride) + (x * 4);
return Color.FromArgb(*(b + 3), *(b + 2), *(b + 1), *b);
}
if (m_oBitmapData.PixelFormat == PixelFormat.Format24bppRgb)
{
Byte* b = (Byte*)m_oBitmapData.Scan0 + (y * m_oBitmapData.Stride) + (x * 3);
return Color.FromArgb(*(b + 2), *(b + 1), *b);
}
return Color.Empty;
}
unsafe public void SetPixel(Int32 x, Int32 y, Color c)
{
if (m_oBitmapData.PixelFormat == PixelFormat.Format32bppArgb)
{
Byte* b = (Byte*)m_oBitmapData.Scan0 + (y * m_oBitmapData.Stride) + (x * 4);
*b = c.B;
*(b + 1) = c.G;
*(b + 2) = c.R;
*(b + 3) = c.A;
}
if (m_oBitmapData.PixelFormat == PixelFormat.Format24bppRgb)
{
Byte* b = (Byte*)m_oBitmapData.Scan0 + (y * m_oBitmapData.Stride) + (x * 3);
*b = c.B;
*(b + 1) = c.G;
*(b + 2) = c.R;
}
}
public Byte GetIntensity(Int32 x, Int32 y)
{
Color c = GetPixel(x, y);
return (Byte)((c.R * 0.30 + c.G * 0.59 + c.B * 0.11) + 0.5);
}
public void Unlock()
{
if (m_oBitmapData != null)
{
m_oBitmap.UnlockBits(m_oBitmapData);
m_oBitmapData = null;
}
}
public void Save(String strFileName, ImageFormat format)
{
m_oBitmap.Save(strFileName, format);
}
public void Save(String strFileName)
{
m_oBitmap.Save(strFileName);
}
public Bitmap GetBitmap()
{
return m_oBitmap;
}
}
}
文章来源:https://uudwc.com/A/JEVJ