【问题标题】:Creating a jpeg from several overlapping png's从几个重叠的 png 中创建一个 jpeg
【发布时间】:2023-03-22 06:36:02
【问题描述】:

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

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

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

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

protected void Page_Load(object sender, EventArgs e) { //用户有skin1.png,eyes3.png,和mouth8.png 位图位 = new Bitmap(System.Drawing.Image.FromFile(Server.MapPath("/images/skin1.png")), 80, 106); Response.ContentType = "图像/jpeg"; bit.Save(Response.OutputStream, ImageFormat.Jpeg); }

但是,如您所见,我只对单个图像进行了此操作。我想从多个 png 中创建一个位图并输出一个 jpeg。

有人可以帮忙吗?

【问题讨论】:

    标签: c# asp.net image gdi+ bitmap


    【解决方案1】:

    您可以将图像相互叠加。 PNG 图像的透明度得到了正确处理,但由于 JPEG 图像没有任何透明度,因此您需要在其上绘制背景颜色。

    记住要小心正确地处理 Graphics 和 Bitmap 对象。甚至不建议在 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);
    }
    

    【讨论】:

      【解决方案2】:

      我认为您想在重叠图像时查看Graphics.FromImage。我假设没有任何特殊效果(只是重叠和定位每一层)。 所以你可以有这样的东西:

      Graphics gfxAvatar = Graphics.FromImage(bit) //bit is your base image
      
      gfxAvatar.DrawImage(secondLayer, new Point(X,Y)); //Draw secondLayer at X, Y
      

      继续其他层。 (因为有多个层,所以在初始 Graphics gfxAvatar 部分周围有一个 Using 循环可能会更快。完成后,您可以使用 bit.Save 方法将其转换为 JPG。

      【讨论】:

      • 需要注意的一点是 GDI+ 是否正确处理/呈现透明 PNG 图像。如果没有,则需要选择透明颜色并将图像呈现为透明位图。
      • 非常好! OP可能想看看msdn.microsoft.com/en-us/library/ms172507.aspx
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-08-20
      • 1970-01-01
      • 1970-01-01
      • 2020-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多