问题
I have a picturebox and want to change the image color to sepia i know what to do so far in terms of setting it to grayscale then filtering it but the final part is my downfall can someone help set this to sepia for me by suggesting what i should do from the comments that i have provided thanks a lot
回答1:
Your code can be boiled down to:
private void button1_Click(object sender, EventArgs e)
{
Bitmap sepiaEffect = (Bitmap)pictureBox.Image.Clone();
for (int yCoordinate = 0; yCoordinate < sepiaEffect.Height; yCoordinate++)
{
for (int xCoordinate = 0; xCoordinate < sepiaEffect.Width; xCoordinate++)
{
Color color = sepiaEffect.GetPixel(xCoordinate, yCoordinate);
double grayColor = ((double)(color.R + color.G + color.B)) / 3.0d;
Color sepia = Color.FromArgb((byte)grayColor, (byte)(grayColor * 0.95), (byte)(grayColor * 0.82));
sepiaEffect.SetPixel(xCoordinate, yCoordinate, sepia);
}
}
pictureBox.Image = sepiaEffect;
}
This, however, is a pretty slow set of nested loops. A faster approach is to create a ColorMatrix that represents how to transform the colors and then redraw the image into a new Bitmap passing it thru an ImageAttributes using the ColorMatrix:
private void button2_Click(object sender, EventArgs e)
{
float[][] sepiaValues = {
new float[]{.393f, .349f, .272f, 0, 0},
new float[]{.769f, .686f, .534f, 0, 0},
new float[]{.189f, .168f, .131f, 0, 0},
new float[]{0, 0, 0, 1, 0},
new float[]{0, 0, 0, 0, 1}};
System.Drawing.Imaging.ColorMatrix sepiaMatrix = new System.Drawing.Imaging.ColorMatrix(sepiaValues);
System.Drawing.Imaging.ImageAttributes IA = new System.Drawing.Imaging.ImageAttributes();
IA.SetColorMatrix(sepiaMatrix);
Bitmap sepiaEffect = (Bitmap)pictureBox.Image.Clone();
using (Graphics G = Graphics.FromImage(sepiaEffect))
{
G.DrawImage(pictureBox.Image, new Rectangle(0, 0, sepiaEffect.Width, sepiaEffect.Height), 0, 0, sepiaEffect.Width, sepiaEffect.Height, GraphicsUnit.Pixel, IA);
}
pictureBox.Image = sepiaEffect;
}
I got the sepia tone values from this article.
来源:https://stackoverflow.com/questions/19542174/changing-images-in-the-picturebox-to-sepia