代码之家  ›  专栏  ›  技术社区  ›  Bryan Denny

在C中合并JPG和GDI#

  •  2
  • Bryan Denny  · 技术社区  · 16 年前

    我的场景:

    • 我有一张彩色背景图片JPG。
    • 我有一个白色背景上的黑色文本JPG。

    我想在彩色背景图像上叠加黑色文本和白色背景的图像,即白色背景变得透明,可以看到它下面的彩色背景。

    如何在C#中使用GDI来实现这一点?

    谢谢!

    3 回复  |  直到 16 年前
        1
  •  2
  •   Community Mohan Dere    8 年前

    GalacticCowboy

    using (Bitmap background = (Bitmap)Bitmap.FromFile(backgroundPath))
    {
         using (Bitmap foreground = (Bitmap)Bitmap.FromFile(foregroundPath))
         {
              // check if heights and widths are the same
              if (background.Height == foreground.Height & background.Width == foreground.Width)
              {
                   using (Bitmap mergedImage = new Bitmap(background.Width, background.Height))
                   {
                        for (int x = 0; x < mergedImage.Width; x++)
                        {
                             for (int y = 0; y < mergedImage.Height; y++)
                             {
                                  Color backgroundPixel = background.GetPixel(x, y);
                                  Color foregroundPixel = foreground.GetPixel(x, y);
                                  Color mergedPixel = Color.FromArgb(backgroundPixel.ToArgb() & foregroundPixel.ToArgb());
                                  mergedImage.SetPixel(x, y, mergedPixel);
                              }
                        }
                        mergedImage.Save("filepath");
                   }
    
              }
         }
    }
    

        2
  •  1
  •   GalacticCowboy    16 年前

    如果图像大小相同,则迭代它们并“与”每个像素的颜色。对于白色像素,您应该得到其他图像的颜色,对于黑色像素,您应得到黑色。

    如果它们的大小不同,请先按比例缩放。

    我是凭空想象出来的,但大致如下:

    Color destColor = Color.FromArgb(pixel1.ToArgb() & pixel2.ToArgb());
    
        3
  •  1
  •   arbiter    16 年前

    Image BackImage = Image.FromFile(backgroundPath);
    using (Graphics g = Graphics.FromImage(BackImage))
    {
        using (ForeImage = Image.FromFile(foregroundPath))
        {   
            ImageAttributes imageAttr = new ImageAttributes();
            imageAttr.SetColorKey(Color.FromArgb(245, 245, 245), Color.FromArgb(255, 255, 255),
                ColorAdjustType.Default);
            g.DrawImage(ForeImage, new Rectangle(0, 0, BackImage.Width, BackImage.Height),
                0, 0, BackImage.Width, BackImage.Height, GraphicsUnit.Pixel, imageAttr);
        }
    }
    

    SetColorKey方法将使指定范围内的颜色透明,因此您可以使白色位图像素透明,包括所有受jpeg压缩伪影影响的像素。

        4
  •  -1
  •   Muad'Dib    16 年前