0

Hello I have heightData in memory and sometimes (when I edit it) I wanna save it to jpg. This is my code:

float multi = 0.2f;
float[,] heightData = quadTree.HeightData;
Color[] heightMapColors = new Color[heightData.Length];

for (int x = 0; x < heightData.GetLength(0); x++)
{
    for (int y = 0; y < heightData.GetLength(1); y++)
    {
         byte colorData = (byte)(heightData[x, y] / multi);

         heightMapColors[x + y * heightData.GetLength(0)].R = colorData;
         heightMapColors[x + y * heightData.GetLength(0)].G = colorData;
         heightMapColors[x + y * heightData.GetLength(0)].B = colorData;
    }
}

Texture2D heightMap = new Texture2D(device, heightData.GetLength(0), heightData.GetLength(1), false, SurfaceFormat.Color);
heightMap.SetData<Color>(heightMapColors);

using (System.IO.Stream stream = System.IO.File.OpenWrite(@"D:\test.jpg"))
{
     heightMap.SaveAsJpeg(stream, heightData.GetLength(0), heightData.GetLength(1));
}

I am 100% sure that I have data in heightMapColors, but saved jpg is only black. :/ Is it a good way how to do it or something is wrong?

Skami
  • 1,506
  • 1
  • 18
  • 29
Honza Kovář
  • 704
  • 6
  • 9

2 Answers2

2

Alpha should not be zero

     heightMapColors[x + y * heightData.GetLength(0)].R = colorData;
     heightMapColors[x + y * heightData.GetLength(0)].G = colorData;
     heightMapColors[x + y * heightData.GetLength(0)].B = colorData;
     heightMapColors[x + y * heightData.GetLength(0)].A = 255;
Blau
  • 5,742
  • 1
  • 18
  • 27
  • That might not be the problem, he seems to be saving it as a JPEG which (mostly) don't care about alpha. – Ani May 02 '12 at 20:11
  • have you tested it? because I'm almost sure is the matter – Blau May 02 '12 at 20:14
  • Ah, he seems to be putting the data into a texture which probably pre-multiplies the alpha - which is why it matters? Well that's the only explanation I can think of, anyways. Glad you got it figured out! – Ani May 02 '12 at 20:22
  • Anyway jpeg supports alpha channels too, I know are rare, but Blizzard use them in warcraft3 textures... – Blau May 02 '12 at 20:24
  • Hence the "mostly" :) I have used them myself on RARE occasions. – Ani May 02 '12 at 20:27
  • To clarify, the implementation of `Texture2D.SaveAsJpeg()` replaces any pixel that has A = 0 with Color.Transparent, thereby eliminating any data in the other color channels. – Cole Campbell May 03 '12 at 06:41
1

A JPG is probably not a good format to store a heightmap into because it is a lossy format. You should be putting it into a BMP pr PNG. That said, what is the range of your "height"? It looks like your height is a float which means it is probably not in the right range to be displayed or even converted to discrete values.

If your allowed height range is Xf to Yf, convert that to a 0 - 255 range using

byteValue = (byte)(((OldValue - OldMin) * (255 - 0)) / (OldMax - OldMin)) + 0

and then give it a shot.

Community
  • 1
  • 1
Ani
  • 10,826
  • 3
  • 27
  • 46