因此,在我的网站上,用户可以创建头像。它是由用户从多个图像中选择而创建的;有一个基本的“皮肤”图像,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。
有人可以帮忙吗?
答案 0 :(得分:5)
您可以将图像绘制在彼此之上。 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);
}
答案 1 :(得分:3)
我认为你想在重叠图像时调查Graphics.FromImage。我假设没有任何特殊效果(简单地重叠和定位每一层)。 所以你可以这样:
Graphics gfxAvatar = Graphics.FromImage(bit) //bit is your base image
gfxAvatar.DrawImage(secondLayer, new Point(X,Y)); //Draw secondLayer at X, Y
继续使用其他图层。 (由于存在多个图层,因此在初始Using
部分周围进行Graphics gfxAvatar
循环可能会更快。然后,一旦完成,您可以使用bit.Save方法将其转换为JPG。