把一个bitmap在内存中的数据块 搬到另一个bitmap中

这些纯粹学习代码没啥实际用处

bitmap快速复制数据的方法,比setPixel快

static void  void Main(string[] args)
{
    //截屏代码
    Rectangle rec = Screen.PrimaryScreen.Bounds;
    Bitmap img = new Bitmap(rec.Width, rec.Height);
    Graphics gph = Graphics.FromImage(img);
    gph.CopyFromScreen(new Point(0, 0), new Point(0, 0), rec.Size);

    //将bitmap锁定到系统内存中
    System.Drawing.Imaging.BitmapData bmpData = img.LockBits(rec, System.Drawing.Imaging.ImageLockMode.ReadWrite, System.Drawing.Imaging.PixelFormat.Format16bppRgb555);
    // 获取起始行的地址.
    IntPtr ptr = bmpData.Scan0;
    // 定义一个数组用来保存bitmap的数据.
    int bytes = bmpData.Stride * img.Height;
    byte[] rgbValues = new byte[bytes];
    // 把rgb值拷贝到数组中
    System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes);
    img.UnlockBits(bmpData);

    //将数据拷到另一个bitmap中
    Bitmap img2 = new Bitmap(rec.Width, rec.Height);
    Graphics gph2 = Graphics.FromImage(img2);
    System.Drawing.Imaging.BitmapData bmpData2 = img2.LockBits(rec, System.Drawing.Imaging.ImageLockMode.ReadWrite, System.Drawing.Imaging.PixelFormat.Format16bppRgb555);
    IntPtr ptr2 = bmpData2.Scan0;
    System.Runtime.InteropServices.Marshal.Copy(rgbValues, 0, ptr2, bytes);
    img2.UnlockBits(bmpData2);
    img2.Save("asd.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);                                                                                                      
}                                                                                                                                                                           
posted @ 2011-03-09 17:07  assassinx  阅读(2940)  评论(0编辑  收藏  举报