C# ã§ä½ã¬ãã«ç»å転é
C# ã«ã¯ Bitmap ã¯ã©ã¹ãç¨æããã¦ããã®ã ããã©ããã¡ãã£ã¨ã°ããã¢ã«ãã¡ãã¬ã³ãã ã®å ç®åæã ã®ä¹ç®åæã ã®ãæ¯è¼çé«éã«å¦çããå¿
è¦ãåºã¦ããã®ã§ãã¡ã¢ãªãç´æ¥å¼ã£ã¦ãã«ããã«ããã¦ã¿ããã¨ã«ãã¾ããã
ããããããããæå¤ã«é ãæ©ã¾ãã¦ããã¾ãã
ã¾ãç»åã®ãã¼ãã§ãããããã¯ç°¡åã§ãã
Bitmap bitmap = new Bitmap(filename); BitmapData data = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb); this.pixels = new byte[data.Stride * data.Height]; Marshal.Copy(data.Scan0, this.pixels, 0, this.pixels.Length); bitmap.UnlockBits(data);
ããã§ã¤ã¡ã¼ã¸ã®ãã¼ã¿ã ARGB8888 ã®å½¢å¼ã§åããã®ã§ããã¨ã¯ pixels ãé©å½ã«å¼ãã°ã¤ã¡ã¼ã¸ã®æä½ãå¯è½ã«ãªãã¾ãã
ã§ã次ã¯ããããæç»ããæ¹æ³ã
DirectX ã OpenGL ã使ããã¨ã¯æã£ã¦ããªãã®ã§ãGraphics.DrawImage() ã使ã£ã¦ç»é¢ã«æç»ãããã¨ã«ãªãã¾ãã
Graphics.DrawImage() ã§ä½¿ç¨ããã¤ã¡ã¼ã¸ã¯ Image ã¯ã©ã¹ãªã®ã§ãBitmap ããåå¾ãã pixels ããåã³ Bitmapï¼Imageï¼ã¯ã©ã¹ã«å¤æãã¦ããå¿
è¦ãããã¾ãã
ããã¯ã
Bitmap(int width, int height, int stride, PixelFormat format, IntPtr scan0);
ããã¤ã使ãã¨ãscan0 ããã®ã¾ã¾ä½¿ã£ã¦è»¢éãã¦ãããã®ã§ãã³ãã¼ãçºçããªããããæ¯è¼çé«éã« Bitmap ãçæã§ãã¾ãã
ãã ããã® scan0 㯠IntPtr ãªã®ã§ãbyte[] ã§ãã pixels ããIntPtr ã«å¤æãã¦ããå¿
è¦ãããã¾ãã
Marshal.UnsafeAddrOfPinnedArrayElement ã使ãã°ããã¯å¯è½ã§ããã
IntPtr scan0 = Marshal.UnsafeAddrOfPinnedArrayElement(pixels, 0)
ããã ãã 㨠scan0 ã¯ãã¬ã¼ãã¸ã³ã¬ã¯ã¿ã«ãã£ã¦ã³ã³ãã¯ã·ã§ã³ãè¡ããã¦ãã¾ãå¯è½æ§ãããã®ã§ããããæå¹ã§ããä¿è¨¼ã¯ããã¾ããã
ãªã®ã§ãid:yaneurao:20060424 ã®æ¹æ³ã使ã£ã¦ãä¸æçã«ã³ã³ãã¯ã·ã§ã³ãåé¿ãã¦ããã¾ãã
èªåã ã£ããå¤é¨ããçæã§ããªãããã«ã³ã³ã¹ãã©ã¯ã¿ã¯ internal ã«ãã¦ãDispose() ã®ãå¿ããè¤æ°å Dispose() ãããã®ãèæ
®ã«å
¥ãã¦æ¸ããªããã£ã¦ãã¨ã§ã¡ãã£ã¨æ¹å¤ã
class UnsafePointer : IDisposable { private GCHandle handle; private IntPtr ptr; internal UnsafePointer(GCHandle handle, IntPtr ptr) { this.handle = handle; this.ptr = ptr; } ~UnsafePointer() { Dispose(); } public IntPtr IntPtr { get { return ptr; } } #region IDisposable ã¡ã³ã public void Dispose() { lock (this) { if (this.handle.IsAllocated) { this.handle.Free(); } } } #endregion }
ã§ãããã¤ã使ã£ã¦ Bitmap ãçæãã¦ç»é¢ã«æç»ãã¾ãã
public void DrawBySystemGraphics(Graphics graphics, Point dstPoint) { using (UnsafePointer ptr = Converter.ArrayToUnsafePointer(pixels, 0)) { Bitmap bitmap = new Bitmap(this.Width, this.Height, this.Stride, this.PixelFormat, ptr.IntPtr); graphics.DrawImage(bitmap, dstPoint); } }
以ä¸ã
ã§ãä»èªåãé ãæ©ã¾ãã¦ãã®ã¯ãã¡ã¢ãªä¸ã®ä½ç½®ãå¤ããå¯è½æ§ãããããããã® Bitmap ãå¤é¨ã«åºããã¨ã¯å±éºããã¦åºæ¥ãªãã¨ãããã¨ã
Graphics ã使ã£ã¦æç»ããã¨ãããããããã¡ã½ãããä½ã£ã¦ãããªãã¨ãããªãã
ããã¨ãã¦ãã
public Bitmap ToBitmap() { Bitmap bitmap = null; using (UnsafePointer ptr = Converter.ArrayToUnsafePointer(pixels, 0)) { Bitmap tmp = new Bitmap(this.Width, this.Height, this.Stride, this.PixelFormat, ptr.IntPtr); bitmap = (System.Drawing.Bitmap)tmp.Clone(); } return bitmap; }
ãããéçã ããã
Bitmap ãå¤é¨ã«åºãããããããã DrawBySystemGraphics() ã¨ãä½ããªãã¦ãããã楽ãªãã ãã©ããã®æ¹æ³ããªããªãâ¦â¦ã
ä½ã¨ããªããªãããªãâ¦â¦ï¼;´Ðï½ï¼