Friday, April 13, 2007

Texture mapping

texture mapping sample...


private void button1_Click(object sender, System.EventArgs e)
{
//ApplyTexture()

Image bgImage = new Bitmap("D:\\calvin.jpg");
Image textureImg = new Bitmap("D:\\texture1.jpg");
ApplyTexture(bgImage,textureImg,(float)1.0);


}



// using System.Drawing.Imaging;
// Modifies the ORIGINAL bitmap
// textureTransparency has to be between 0 and 1,
// with 0 being the least transparent, and 1 the most transparent
public void ApplyTexture (Image img, Image texture,
float textureTransparency)
{
if ( (img ==null) || (texture==null) )
throw new ArgumentNullException();
if (textureTransparency < 0 || textureTransparency > 1)
throw new ArgumentOutOfRangeException(
"Value must be between 0 and 1.");

// Convert the texture to grayscale before using it
MakeImageGrayscale (texture);


Bitmap txtr = new Bitmap(texture);
BitmapData bmData = txtr.LockBits(new Rectangle(0, 0,
txtr.Width, txtr.Height),
ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);
int stride = bmData.Stride;
System.IntPtr Scan0 = bmData.Scan0;
// Adjust the alpha value of each pixel in the texture bitmap.
// The white-most pixels will have the the
// most transparency (highest alpha),
// and the dark-most pixels will have the least transparency.
unsafe
{
byte * p = (byte *)(void *)Scan0;
int nOffset = stride - txtr.Width*4;


for (int y=0; y < txtr.Height; ++y)
{
for (int x=0; x < txtr.Width; ++x)
{
// p[3] is alpha - array is BGRA (blue, green ,
// red, alpha)
p[3] = (byte)(p[0] * textureTransparency);
p += 4; // Move to the next pixel
}
p += nOffset;
}
}
txtr.UnlockBits(bmData);

Graphics gr = Graphics.FromImage(img);
TextureBrush myBrush = new TextureBrush(txtr);
gr.FillRectangle (myBrush,0,0,img.Width, img.Height);

Graphics graphics = this.CreateGraphics();
graphics.DrawImage(img,0,0,img.Width,img.Height);

graphics.Dispose();
myBrush.Dispose();
gr.Dispose();

txtr.Dispose();
}



// Converts the image to grayscale
public void MakeImageGrayscale (Image img)
{
ColorMatrix cMatrix = new ColorMatrix (
new float[][] {
new float[] {0.299F, 0.299F, 0.299F, 0, 0},
new float[] {0.587F, 0.587F, 0.587F, 0, 0},
new float[] {0.114F, 0.114F, 0.114F, 0, 0},
new float[] {0, 0, 0, 1, 0},
new float[] {0, 0, 0, 1, 0}});

ImageAttributes imageAttrib = new ImageAttributes();
imageAttrib.SetColorMatrix(cMatrix);

Graphics gr = Graphics.FromImage (img);
// Apply the grayscale image attribute
gr.DrawImage (img, new Rectangle(0, 0, img.Width, img.Height),
0, 0, img.Width, img.Height, GraphicsUnit.Pixel,
imageAttrib);
gr.Dispose();
}
}

0 Comments:

Post a Comment

<< Home