图像镜像翻转

来源:互联网 发布:毕向东java教程百度云 编辑:程序博客网 时间:2024/05/09 08:19
  1. /// <summary>  
  2. /// 水平镜像  
  3. /// </summary>  
  4. /// <param name="bmp"></param>  
  5. /// <returns></returns>  
  6. public static Bitmap MirrorH(Bitmap bmp)  
  7. {  
  8.     if (bmp == null)  
  9.         return bmp;  
  10.   
  11.     Rectangle bmpRect = new Rectangle(0, 0, bmp.Width, bmp.Height);  
  12.     BitmapData bmpData = bmp.LockBits(bmpRect, ImageLockMode.ReadWrite, bmp.PixelFormat);  
  13.     int bytes = bmpData.Stride * bmp.Height;  
  14.     byte[] rgbValues = new byte[bytes];  
  15.     IntPtr ptr = bmpData.Scan0;  
  16.     Marshal.Copy(ptr, rgbValues, 0, bytes);  
  17.   
  18.     byte[] newRgbValues = new byte[bytes];  
  19.     for (int y = 0; y < bmp.Height; y++)  
  20.     {  
  21.         for (int x = 0; x < bmp.Width * 3; x += 3)  
  22.         {  
  23.             newRgbValues[y * bmpData.Stride + (bmp.Width - 1) * 3 - x] = rgbValues[y * bmpData.Stride + x];  
  24.             newRgbValues[y * bmpData.Stride + (bmp.Width - 1) * 3 - x + 1] = rgbValues[y * bmpData.Stride + x + 1];  
  25.             newRgbValues[y * bmpData.Stride + (bmp.Width - 1) * 3 - x + 2] = rgbValues[y * bmpData.Stride + x + 2];  
  26.         }  
  27.     }  
  28.   
  29.     Marshal.Copy(newRgbValues, 0, ptr, bytes);  
  30.     bmp.UnlockBits(bmpData);  
  31.   
  32.     return bmp;  
  33. }  
  34.   
  35. /// <summary>  
  36. /// 垂直镜像  
  37. /// </summary>  
  38. /// <param name="bmp"></param>  
  39. /// <returns></returns>  
  40. public static Bitmap MirrorV(Bitmap bmp)  
  41. {  
  42.     if (bmp == null)  
  43.         return bmp;  
  44.   
  45.     Rectangle bmpRect = new Rectangle(0, 0, bmp.Width, bmp.Height);  
  46.     BitmapData bmpData = bmp.LockBits(bmpRect, ImageLockMode.ReadWrite, bmp.PixelFormat);  
  47.     int bytes = bmpData.Stride * bmp.Height;  
  48.     byte[] rgbValues = new byte[bytes];  
  49.     IntPtr ptr = bmpData.Scan0;  
  50.     Marshal.Copy(ptr, rgbValues, 0, bytes);  
  51.   
  52.     byte[] newRgbValues = new byte[bytes];  
  53.     for (int y = 0; y < bmp.Height; y++)  
  54.     {  
  55.         for (int x = 0; x < bmp.Width * 3; x++)  
  56.         {  
  57.             newRgbValues[(bmp.Height - y - 1) * bmpData.Stride + x] = rgbValues[y * bmpData.Stride + x];  
  58.         }  
  59.     }  
  60.   
  61.     Marshal.Copy(newRgbValues, 0, ptr, bytes);  
  62.     bmp.UnlockBits(bmpData);  
  63.   
  64.     return bmp;  


原创粉丝点击