2016-10-05 229 views
1

我正在嘗試生成城市:天際線的高度圖,並將它們導入爲16位灰度PNG。如何在C#中創建16位灰度PNG?

我創建了一個BitmapPixelFormat.Format16bppGrayScale,而是試圖通過Bitmap.Save保存,傳遞我mageFormat.Png,導致一個ExternalException

「附加信息:GDI +中發生一般性錯誤。」

此外,裝載這16位灰度PNG文件中的一個Bitmap打開該文件爲Format32bppArgb,我想靜靜地下降一半的數據。

如何在.Net/C#中使用16位灰度PNG圖像?

+0

相關,但老:https://social.msdn.microsoft.com/Forums/vstudio/en-US/10252c05-c4b6-49dc-b2a3-4c1396e2c3ab/writing -a-16bit-grayscale-image?forum = csharpgeneral – Brent

+0

你可以看看這個:http://stackoverflow.com/questions/2265910/convert-an-image-to-grayscale – Foitn

+0

並非所有的格式都在PixelFormat枚舉中不幸的是,實際上是支持的你的不是。 – TaW

回答

2

更新: Magick.NET-Q16-AnyCPU已移至https://github.com/dlemstra/Magick.NET

適用於Magick.NET-Q16-AnyCPU的NuGet軟件包https://magick.codeplex.com/完美運行。這裏是我的代碼:

namespace heightmap_generator { 
internal class Program { 
    private static int GRID_SIZE = 1081; 

    private static void Main(string[] args) { 
     using (MagickImage image = new MagickImage(@"C:\Users\Brent\AppData\Local\Colossal Order\Cities_Skylines\Addons\MapEditor\Heightmaps\benchmark.png")) { 
      image.Draw(
       new DrawableFillColor(new MagickColor(ushort.MaxValue/2, ushort.MaxValue/2, ushort.MaxValue/2)), 
       new DrawableRectangle(0, 0, GRID_SIZE, GRID_SIZE) 
      ); 
      var drawables = new List<IDrawable>(); 
      for (var y = 0; y < GRID_SIZE/50; ++y) { 
       float t = y/(GRID_SIZE/50.0f); 
       t = t*t*(3 - 2*t); //cubic hermite spline h01 
       ushort v = (ushort)(ushort.MaxValue * (5 + (t-1)*0.3)/10); 
       if (y == GRID_SIZE/50 - 1) { 
        v = (ushort) (ushort.MaxValue*0.501); 
       } 
       drawables.Add(new DrawableFillColor(new MagickColor(v, v, v))); 
       for (var x = 0; x < GRID_SIZE; ++x) { 
        if (x == GRID_SIZE/2) { 
         var v2 = (ushort) (v + ushort.MaxValue/1024); 
         drawables.Add(new DrawableFillColor(new MagickColor(v2, v2, v2))); 
         drawables.Add(new DrawableColor(x, GRID_SIZE/2 - y, PaintMethod.Point)); 
         drawables.Add(new DrawableColor(x, GRID_SIZE/2 + y, PaintMethod.Point)); 
         drawables.Add(new DrawableFillColor(new MagickColor(v, v, v))); 
        } else { 
         drawables.Add(new DrawableColor(x, GRID_SIZE/2 - y, PaintMethod.Point)); 
         drawables.Add(new DrawableColor(x, GRID_SIZE/2 + y, PaintMethod.Point)); 
        } 
       } 
      } 
      image.Draw(drawables); 
      image.Write(new FileStream(@"C:\Users\Brent\AppData\Local\Colossal Order\Cities_Skylines\Addons\MapEditor\Heightmaps\benchmark3.png", FileMode.Create)); 
     } 
    } 
} 

}