/// <summary> /// Creates an empty <see cref="TgaImage"/> with the given specification. /// </summary> /// <param name="width">The width in pixels.</param> /// <param name="height">The height in pixels.</param> /// <param name="format">The <see cref="TgaFormat"/> to create the image in.</param> public TgaImage(int width, int height, TgaFormat format) { if (width < 0 || width > ushort.MaxValue) { throw new ArgumentOutOfRangeException(nameof(width)); } if (height < 0 || height > ushort.MaxValue) { throw new ArgumentOutOfRangeException(nameof(height)); } header = new TgaHeader { ImageType = 2, ColorMapSpec = new TgaColorMapSpec { }, ImageSpec = new TgaImageSpec { ImageWidth = (ushort)width, ImageHeight = (ushort)height, BitsPerPixel = 16, AlphaWidthAndDirection = (byte)(format == TgaFormat.Argb4 ? 36 : 32), } }; data = new TgaImageData { ColorMapData = new byte[0], ImageId = new byte[0], PixelData = new byte[width * height * 2], }; }
/// <summary> /// Creates a TGA format image from a <see cref="Bitmap"/>. /// </summary> /// <param name="bitmap">The <see cref="Bitmap"/> to create the image from.</param> /// <param name="format">The <see cref="TgaFormat"/> to use.</param> /// <returns>The converted image's TGA representation.</returns> public static TgaImage FromBitmap(Bitmap bitmap, TgaFormat format) { if (bitmap == null) { throw new ArgumentNullException(nameof(bitmap)); } var img = new TgaImage(bitmap.Width, bitmap.Height, format); var data = bitmap.LockBits(new Rectangle(Point.Empty, bitmap.Size), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb); unsafe { byte *scan0 = (byte *)data.Scan0.ToPointer(); for (int y = 0; y < img.Height; ++y) { for (int x = 0; x < img.Width; ++x) { byte *rawData = scan0 + y * data.Stride + x * 4; var col = Color.FromArgb(((int *)rawData)[0]); img.SetPixel(x, y, col); } } } return(img); }