Skip to content

Instantly share code, notes, and snippets.

@ksasao
Last active May 25, 2023 03:56
Show Gist options
  • Save ksasao/7ef49d2baefddd5bc47d20e06adfc614 to your computer and use it in GitHub Desktop.
Save ksasao/7ef49d2baefddd5bc47d20e06adfc614 to your computer and use it in GitHub Desktop.
byte[] のデータをグレースケールビットマップ画像として保存。widthが4の倍数ではないケースを考慮。
// https://symfoware.blog.fc2.com/blog-entry-2195.html
// のコードで Width が 4の倍数ではない場合も考慮
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Drawing.Imaging;
namespace GrayScale
{
internal class Program
{
static void Main(string[] args)
{
int width = 255;
int height = 256;
// byte[]にグレースケールのデータを生成
byte[] data = new byte[width * height];
for (int h = 0; h < height; h++)
{
for (int w = 0; w < width; w++)
{
data[h * width + w] = (byte)(w & 0xFF); // 横方向のグラデーション
// data[h * width + w] = (byte)(h & 0xFF); // 縦方向のグラデーション
}
}
// Format8bppIndexedを指定してBitmapオブジェクトを作成
// Bitmapオブジェクトは IDisposable のため、usingブロックで囲むか、
// 利用後に Dispose() が必要
using (Bitmap img = new Bitmap(width, height, PixelFormat.Format8bppIndexed))
{
// カラーパレットを設定
ColorPalette pal = img.Palette;
for (int i = 0; i < 256; ++i)
{
pal.Entries[i] = Color.FromArgb(i, i, i);
}
img.Palette = pal;
// BitmapDataに用意したbyte配列を一気に書き込む
BitmapData bmpdata = img.LockBits(
new Rectangle(0, 0, width, height),
ImageLockMode.WriteOnly,
PixelFormat.Format8bppIndexed
);
// 4バイト境界を考慮するため
// 横1ラインごとにデータをコピー
// https://learn.microsoft.com/ja-jp/dotnet/api/system.drawing.imaging.bitmapdata.stride
for (int h = 0; h < height; h++)
{
Marshal.Copy(data, width * h, bmpdata.Scan0 + bmpdata.Stride * h, width);
}
img.UnlockBits(bmpdata);
// png形式で保存
img.Save("test.png", ImageFormat.Png);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment