你如何编程编辑.png?

时间:2012-03-26 01:02:36

标签: c# png

我有28个图像,每个图像有3个尺寸(总共84个),这些图像都是单色的,每个图像都有不同的alpha图层。我想让它们以5种不同的颜色提供。那将是420张图片。这显然是手动操作的巨大痛苦。我没有Photoshop,所以任何类型的photoshop功能都不是一个有效的答案。我有Paint.NET但调整色调对我不起作用,因为单独改变色调并不能给我我想要的颜色。

基本上我需要做的是对于图像中的每个像素,取RGBA值并用新的RGB值替换RGB并保持相同的A值。

任何人都知道如何做到这一点?我没有运气搜索StackOverflow或Google(可能使用错误的搜索条件)。

我更喜欢C#或VB.NET中的答案,但如果有人知道如何用任何语言做到这一点,我可以将它应用到C#或VB.NET。

- 编辑 -

如果有人发现这个并且正在寻找答案,这就是我根据Yorye Nathan的链接得到的。

private const int RED = 51;
private const int GREEN = 181;
private const int BLUE = 229;

private const int NEW_RED = 170;
private const int NEW_GREEN = 102;
private const int NEW_BLUE = 204;

private void Form1_Load(object sender, EventArgs e)
{
  if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
  {

    Image OriginalImage = Image.FromFile(openFileDialog1.FileName);
    Image NewImage = ColorFilter(OriginalImage);

    pictureBox1.Image = OriginalImage;
    pictureBox2.Image = NewImage;
  }

}

public static Image ColorFilter(Image originalImage)
{
  Bitmap newImage = new Bitmap(originalImage);
  BitmapData originalData = (originalImage as Bitmap).LockBits(new Rectangle(0, 0, originalImage.Width, originalImage.Height), System.Drawing.Imaging.ImageLockMode.ReadWrite, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

  BitmapData newData = (newImage as Bitmap).LockBits(new Rectangle(0, 0, originalImage.Width, originalImage.Height), ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);

  int originalStride = originalData.Stride;
  System.IntPtr originalScan0 = originalData.Scan0;

  int newStride = newData.Stride;
  System.IntPtr newScan0 = newData.Scan0;

  unsafe
  {
    byte* pOriginal = (byte*)(void*)originalScan0;
    byte* pNew = (byte*)(void*)newScan0;

    int nOffset = originalStride - originalImage.Width * 4;

    byte red, green, blue;

    for (int y = 0; y < originalImage.Height; ++y)
    {
      for (int x = 0; x < originalImage.Width; ++x)
      {
        blue = pOriginal[0];
        green = pOriginal[1];
        red = pOriginal[2];

        if (pOriginal[0] == BLUE && pOriginal[1] == GREEN && pOriginal[2] == RED)
        {
          pNew[0] = (byte)NEW_BLUE;
          pNew[1] = (byte)NEW_GREEN;
          pNew[2] = (byte)NEW_RED;
        }

        pOriginal += 4;
        pNew += 4;
      }
      pOriginal += nOffset;
      pNew += nOffset;
    }
  }
  (originalImage as Bitmap).UnlockBits(originalData);
  (newImage as Bitmap).UnlockBits(newData);
  return newImage;
}

1 个答案:

答案 0 :(得分:4)

检查此question。稍微调整像素的位替换,使其添加而不是替换它们,你就可以了。