c# - 从几个重叠的 png 中创建一个 jpeg

标签 c# asp.net image gdi+ bitmap

所以在我的网站上,用户可以创建头像。它是由用户从多个图像中选择创建的;有一个基本的“皮肤”图像,以及与描绘头发、眼睛、嘴巴等图像重叠的 png。

我无法将用户的头像保存到项目的文件中,所以用户的头像数据存储在数据库中,并且 png 动态重叠显示给用户。

但是,我希望用户能够通过转到页面将他们的头像下载为 jpeg。

我设置了这个正常工作的小示例:

protected void Page_Load(object sender, EventArgs e)
{
    //User has skin1.png, eyes3.png, and mouth8.png
    Bitmap bit = new Bitmap(System.Drawing.Image.FromFile(Server.MapPath("/images/skin1.png")), 80, 106);

    Response.ContentType = "image/jpeg";
    bit.Save(Response.OutputStream, ImageFormat.Jpeg);
}

但是,如您所见,我只对单个图像使用此方法。我想从多个 png 创建一个位图并输出一个 jpeg。

有人可以帮忙吗?

最佳答案

您可以将图像叠加在一起绘制。 PNG 图像的透明度得到了正确处理,但由于 JPEG 图像没有任何透明度,您可能希望在其上绘制背景颜色。

请记住要小心妥善处理图形和位图对象。甚至不建议在 Web 应用程序中使用它们...

// create image to draw on
using (Bitmap bit = new Bitmap(80, 106)) {
  // fill with background
  bit.Clear(Color.White);
  // images to load
  string[] skins = new string[] { "skin1.png", "eyes3.png", "mouth8.png" };
  // create graphics object for drawing on the bitmap
  using (Graphics g = Graphics.FromImage(bit)) {
    foreach (string skin in skins) {
      // load image
      using (Image skinImage = Image.FromFile(Server.MapPath("/images/" + skin)) {
        // draw image
        g.DrawImage(skinImage, 0, 0, 80, 106);
      }
    }
  }
  Response.ContentType = "image/jpeg";
  bit.Save(Response.OutputStream, ImageFormat.Jpeg);
}

关于c# - 从几个重叠的 png 中创建一个 jpeg,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2087742/

相关文章:

c# - 在当前使用访问者模式的 C# (2.0) 中使用委托(delegate)来简化类型安全的抽象语法树

asp.net - CS0103 : The name 'Encoding' does not exist in the current context

c# - 获得正确的图像旋转

javascript - 当在纯图像网址上运行时,书签无法在 ie 中固定位置

python - 如何使用 python 中的地面控制点对未引用的航拍图像进行地理配准

c# - 从 UIViewController 派生的类中的 Monotouch Dialog 实现

c# - 如何检测笔记本电脑电源线何时断开?

c# - 无法连接到 SQL Server : "Login failed for user ".”

c# - 在 RadWindows 中选择一个 RadGrid 行(客户端)

javascript - 如何在公共(public) View 下隐藏源代码