Grid Pixelate

The algorithm processes an image creating the effect of an image with larger pixels.

   



									Public Shared Sub ApplyGridPixelate(ByRef bmp As Bitmap, squareSize As Size)
	Dim TempBmp As Bitmap = DirectCast(bmp.Clone(), Bitmap)

	Dim bmpData As BitmapData = bmp.LockBits(New Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb)
	Dim TempBmpData As BitmapData = TempBmp.LockBits(New Rectangle(0, 0, TempBmp.Width, TempBmp.Height), ImageLockMode.[ReadOnly], PixelFormat.Format24bppRgb)

	Dim ptr As IntPtr = bmpData.Scan0
	Dim TempPtr As IntPtr = TempBmpData.Scan0

	Dim stopAddress As Integer = CInt(ptr) + bmpData.Stride * bmpData.Height

	Dim Val As Integer = 0
	Dim i As Integer = 0, X As Integer = 0, Y As Integer = 0
	Dim BmpStride As Integer = bmpData.Stride
	Dim BmpWidth As Integer = bmp.Width
	Dim BmpHeight As Integer = bmp.Height
	Dim SqrWidth As Integer = squareSize.Width
	Dim SqrHeight As Integer = squareSize.Height
	Dim XVal As Integer = 0, YVal As Integer = 0

	While CInt(ptr) <> stopAddress
		X = i Mod BmpWidth
		Y = i \ BmpWidth

		XVal = (SqrWidth - X Mod SqrWidth)
		YVal = (SqrHeight - Y Mod SqrHeight)

		If XVal = SqrWidth Then
			XVal = X + -X
		ElseIf XVal > 0 AndAlso XVal < BmpWidth Then
			XVal = X + XVal
		End If

		If YVal = SqrHeight Then
			YVal = Y + -Y
		ElseIf YVal > 0 AndAlso YVal < BmpHeight Then
			YVal = Y + YVal
		End If

		If XVal >= 0 AndAlso XVal < BmpWidth AndAlso YVal >= 0 AndAlso YVal < BmpHeight Then
			Val = (YVal * BmpStride) + (XVal * 3)

			Marshal.WriteByte(ptr, Marshal.ReadByte(TempPtr + Val))
			Marshal.WriteByte(ptr + 1, Marshal.ReadByte(TempPtr + Val + 1))
			Marshal.WriteByte(ptr + 2, Marshal.ReadByte(TempPtr + Val + 2))
		End If

		ptr += 3
		i += 1
	End While

	bmp.UnlockBits(bmpData)
	TempBmp.UnlockBits(TempBmpData)
End Sub
								


Example

									DIm b As Bitmap = CType(Image.FromFile("rose.jpg"), Bitmap)
ApplyGridPixelate(b, new Size(15, 15))