Last active
April 20, 2021 11:10
-
-
Save ksasao/f841b85d7521f49306fb to your computer and use it in GitHub Desktop.
C# で Bitmap を高速に直接操作するためのあれこれ http://d.hatena.ne.jp/ksasao/20131216/1387134321 も参照
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <summary> | |
/// Bitmapをbyte[]に変換する | |
/// </summary> | |
/// <param name="bitmap">変換元の32bitARGB Bitmap</param> | |
/// <returns>1 pixel = 4 byte (+3:A, +2:R, +1:G, +0:B) に変換したbyte配列</returns> | |
public byte[] BitmapToByteArray(Bitmap bmp) | |
{ | |
Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height); | |
System.Drawing.Imaging.BitmapData bmpData = | |
bmp.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite, | |
PixelFormat.Format32bppArgb); | |
// Bitmapの先頭アドレスを取得 | |
IntPtr ptr = bmpData.Scan0; | |
// 32bppArgbフォーマットで値を格納 | |
int bytes = bmp.Width * bmp.Height * 4; | |
byte[] rgbValues = new byte[bytes]; | |
// Bitmapをbyte[]へコピー | |
Marshal.Copy(ptr, rgbValues, 0, bytes); | |
bmp.UnlockBits(bmpData); | |
return rgbValues; | |
} | |
/// <summary> | |
/// byte[]をBitmapに変換する | |
/// </summary> | |
/// <param name="byteArray">1 pixel = 4 byte (+3:A, +2:R, +1:G, +0:B) に変換したbyte配列</param> | |
/// <param name="bmp">変換先のBitmap。あらかじめ必要な大きさを確保しておく必要がある</param> | |
/// <returns>変換先のBitmap</returns> | |
public Bitmap ByteArrayToBitmap(byte[] rgbValues, Bitmap bmp) | |
{ | |
Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height); | |
System.Drawing.Imaging.BitmapData bmpData = | |
bmp.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite, | |
PixelFormat.Format32bppArgb); | |
// Bitmapの先頭アドレスを取得 | |
IntPtr ptr = bmpData.Scan0; | |
// Bitmapへコピー | |
Marshal.Copy(rgbValues, 0, ptr, rgbValues.Length); | |
bmp.UnlockBits(bmpData); | |
return bmp; | |
} | |
public byte[] To32bitARGBArray(Bitmap bmp) | |
{ | |
byte[] bmp32Data = null; | |
using (Bitmap bmp32 = new Bitmap(bmp.Width, bmp.Height)) | |
{ | |
// bmp が 32bitARGB 形式ではない場合でも 32bitARGBに変換 | |
using (Graphics g = Graphics.FromImage(bmp32)) | |
{ | |
g.DrawImage(bmp, | |
new Rectangle(0, 0, bmp32.Width, bmp32.Height), | |
new Rectangle(0, 0, bmp.Width, bmp.Height), | |
GraphicsUnit.Pixel); | |
} | |
bmp32Data = BitmapToByteArray(bmp32); | |
} | |
return bmp32Data; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment