c#数字图像处理(八)图像平移

使图像沿水平方向和垂直方向移动

        /// <summary>
        /// 图像平移
        /// </summary>
        private void translation_Click(object sender, EventArgs e)
        {
            if (curBitmap!=null)
            {
                translation traForm = new translation();
                if (traForm.ShowDialog()==DialogResult.OK)
                {
                    Rectangle rect = new Rectangle(0, 0, curBitmap.Width, curBitmap.Height);
                    BitmapData bmpData = curBitmap.LockBits(rect, ImageLockMode.ReadWrite, curBitmap.PixelFormat);
                    IntPtr ptr = bmpData.Scan0;
                    int bytes = bmpData.Stride * bmpData.Height;
                    byte[] grayValues = new byte[bytes];
                    Marshal.Copy(ptr, grayValues, 0, bytes);

                    //得到两个方向的图像平移量
                    int x = Convert.ToInt32(traForm.GetXOFFset);
                    int y = Convert.ToInt32(traForm.GetYOffset);

                    byte[] tempArray = new byte[bytes];
                    //临时初始化为白色(255)像素
                    for (int i = 0; i < bytes; i++)
                    {
                        tempArray[i] = 255;
                    }
                    
                    for (int j = 0; j < curBitmap.Height; j++)
                    {//保证纵向平移不出界
                        if ((j + y) < curBitmap.Height && (j + y) > 0)
                        {
                            for (int i = 0; i < curBitmap.Width * 3; i += 3)
                            {
                                if ((i + x * 3) < curBitmap.Width * 3 && (i + x * 3) > 0)
                                {//保证横向平移不出界
                                    tempArray[(i + x * 3) + 0 + (j + y) * bmpData.Stride] = grayValues[i + 0 + j * bmpData.Stride];
                                    tempArray[i + x * 3 + 1 + (j + y) * bmpData.Stride] = grayValues[i + 1 + j * bmpData.Stride];
                                    tempArray[i + x * 3 + 2 + (j + y) * bmpData.Stride] = grayValues[i + 2 + j * bmpData.Stride];
                                }
                            }
                        }
                    }


                    //数组复制,返回平移图像
                    grayValues = (byte[])tempArray.Clone();
                    Marshal.Copy(grayValues, 0, ptr, bytes);
                    curBitmap.UnlockBits(bmpData);
                }
                Invalidate();
            }
        

要注意像素格式PixelFormat,如24位灰度图像是1440万色,但是我们书上给的算法是对8为进行处理,可以采用分割的思想将24位拆开成3个8位,由这三个8为所保存的数据组合为24位,在处理的时候就将他们分开处理但是要整体观看

 

 

 

posted @ 2018-03-27 10:48  微光-倾城  阅读(2363)  评论(0编辑  收藏  举报