Create jpeg from multiple overlapping png

Thus, on my site a user can create an avatar. It is created by the user by selecting multiple images; there is a basic "skin image" and png that overlap an image that depicts hair, eyes, mouth, etc.

I can’t save the user avatar in the project files, so the user avatar data is stored in the database, and png are superimposed on the fly and displayed to the user.

However, I would like the user to be able to upload his avatar as jpeg by going to the page.

I have this small example that works correctly:

  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);
 }

But, as you can see, it only works for me for one image. I would like to create a bitmap from several png and output jpeg.

Can anyone help?

+4
source share
2 answers

You can simply draw images on top of each other. The transparency of PNG images is handled correctly, but since JPEG images do not have transparency, you want the background color to be drawn.

Remember that you need to properly dispose of objects Graphics and Bitmap. They are not even recommended for use in a web application ...

// 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); } 
+5
source

I think you want to look at Graphics.FromImage when you overlap images. I guess there are no special effects (just overlapping and positioning each layer). So you might have something like this:

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

Continue this with other layers. (It might be faster to have a Using loop around the starting section of Graphics gfxAvatar , as there are several levels. Then, once this is done, you can convert it to JPG using the bit.Save method.

+3
source

All Articles