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