How to download PNG and export to TGA, saving alpha in C #?

I am writing a tool to automate some of our assets for the game. What I want to do is take a folder with PNG files, combine them into a texture atlas, and then export the atlas as TGA and UV cords in XML.

I'm not sure which method I should use to load PNG files in C #, since there seem to be several. What is the recommended method for loading images in C # that gives access to color / alpha data, so I can extract it in TGA?

I also have TGA creation code in C ++, which I plan to move to C #, but I wonder if there is anything that is already available in .Net to create / save TGA?

Thanks for reading.

+6
c # png alpha tga
source share
2 answers

Download PNG file to. Bit Bitmap is very simple:

Bitmap bmp = (Bitmap)Bitmap.FromFile("c:\wherever\whatever.png"); // yes, the (Bitmap) cast is necessary. Don't ask me why. 

After downloading Bitmap, you can access all your information (including information about alpha channels) most effectively using the Bitmap LockBits method (there are many LockBits code samples in StackOverflow).

Update : here is a sample code that shows how to use LockBits to access pixel pixels of Bitmap data:

 System.Drawing.Imaging.BitmapData data = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, bmp.PixelFormat); unsafe { // important to use the BitmapData object Width and Height // properties instead of the Bitmap's. for (int x = 0; x < data.Width; x++) { int columnOffset = x * 4; for (int y = 0; y < data.Height; y++) { byte* row = (byte*)data.Scan0 + (y * data.Stride); byte B = row[columnOffset]; byte G = row[columnOffset + 1]; byte R = row[columnOffset + 2]; byte alpha = row[columnOffset + 3]; } } } bmp.UnlockBits(data); 

You need to set the "Allow unsafe code" compiler option for your project to use this code. You can also use the GetPixel (x, y) Bitmap method, but it is surprisingly slow.

+8
source share

I do not have a sample code, but I can give you a guide

  • Download PNG using Image.FromFile () .. NET supports PNG loading
  • Open the file descriptor in your container. Create XmlDocument..NET does not support targy, so you need to manually write it.
  • Lock the bitmap to get pixels. GetPixel () is very slow. I think the method is called LockBits (). You get a pointer to the surface to read pixels.
  • Write to Targa. Targa is a container format, so any bitmap must match.
  • Save UV as Xml.

Targa format

Do you want to use the palette? Since you are making a game, I would recommend that you calculate the palette for your bitmaps and put it in a targy to reduce the file size.

Oh, before I forget, .NET doesn't use RGBA, instead pixels are BGRA. Do not ask me why, but it is.

+1
source share

All Articles