画像の幅/高さ/ストライドとバッファがあります。
この情報をSystem.Drawing.Bitmapに変換するにはどうすればよいですか?これらの4つがあれば、元の画像を取り戻すことはできますか?
画像の幅/高さ/ストライドとバッファがあります。
この情報をSystem.Drawing.Bitmapに変換するにはどうすればよいですか?これらの4つがあれば、元の画像を取り戻すことはできますか?
Bitmap
あなたが持っているすべてのものを必要とするコンストラクターのオーバーロードがあります(プラスPixelFormat
):
public Bitmap(int width, int height, int stride, PixelFormat format, IntPtr scan0);
これは機能する可能性があります(たとえばargs.Buffer
、 blittable 型の配列の場合):byte
Bitmap bitmap;
var gch = System.Runtime.InteropServices.GCHandle.Alloc(args.Buffer, GCHandleType.Pinned);
try
{
bitmap = new Bitmap(
args.Width, args.Height, args.Stride,
System.Drawing.Imaging.PixelFormat.Format24bppRgb,
gch.AddrOfPinnedObject());
}
finally
{
gch.Free();
}
アップデート:
Bitmap
おそらく、コンストラクターがそれを行わないように思われるため、新しく作成された画像バイトを手動でコピーする方が良いでしょうbyte[]
。画像データの配列がガベージコレクションされると、あらゆる種類の悪いことが起こる可能性があります。
var bitmap = new Bitmap(args.Width, args.Height, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
var data = bitmap.LockBits(
new Rectangle(0, 0, args.Width, args.Height),
System.Drawing.Imaging.ImageLockMode.WriteOnly,
System.Drawing.Imaging.PixelFormat.Format24bppRgb);
if(data.Stride == args.Stride)
{
Marshal.Copy(args.Buffer, 0, data.Scan0, args.Stride * args.Height);
}
else
{
int arrayOffset = 0;
int imageOffset = 0;
for(int y = 0; y < args.Height; ++y)
{
Marshal.Copy(args.Buffer, arrayOffset, (IntPtr)(((long)data.Scan0) + imageOffset), data.Stride);
arrayOffset += args.Stride;
imageOffset += data.Stride;
}
}
bitmap.UnlockBits(data);
これは、バッファがバイト[]、幅と高さ+ピクセルフォーマット(ストライド)の場合に機能するはずです
public Bitmap CreateBitmapFromRawDataBuffer(int width, int height, PixelFormat imagePixelFormat, byte[] buffer)
{
Size imageSize = new Size(width, height);
Bitmap bitmap = new Bitmap(imageSize.Width, imageSize.Height, imagePixelFormat);
Rectangle wholeBitmap = new Rectangle(0, 0, bitmap.Width, bitmap.Height);
// Lock all bitmap's pixels.
BitmapData bitmapData = bitmap.LockBits(wholeBitmap, ImageLockMode.WriteOnly, imagePixelFormat);
// Copy the buffer into bitmapData.
System.Runtime.InteropServices.Marshal.Copy(buffer, 0, bitmapData.Scan0, buffer.Length);
// Unlock all bitmap's pixels.
bitmap.UnlockBits(bitmapData);
return bitmap;
}