System.Drawing.Bitmap.UnlockBits(System.Drawing.Imaging.BitmapData)

Here are the examples of the csharp api System.Drawing.Bitmap.UnlockBits(System.Drawing.Imaging.BitmapData) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

794 Examples 7

19 Source : BitmapProcess.cs
with GNU General Public License v3.0
from cymheart

static public void TileParseImage(Bitmap srcBitmap, Rectangle srcRect, Bitmap dstBitmap, Rectangle dstRect)
        {
            unsafe
            {
                Rectangle srcBitmapRect = new Rectangle(0, 0, srcBitmap.Width, srcBitmap.Height);
                Rectangle dstBitmapRect = new Rectangle(0, 0, dstBitmap.Width, dstBitmap.Height);

                //将Bitmap锁定到系统内存中,获得BitmapData
                BitmapData srcBmData = srcBitmap.LockBits(srcBitmapRect,
                    ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);

                BitmapData dstBmData = dstBitmap.LockBits(dstBitmapRect,
                   ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);

                byte* srcScan = (byte*)(void*)(srcBmData.Scan0);
                byte* srcPtr = srcScan + srcRect.Top * srcBmData.Stride + srcRect.Left * 4;

                byte* dstScan = (byte*)(void*)(dstBmData.Scan0);
                byte* dstPtr = dstScan + dstRect.Top * dstBmData.Stride + dstRect.Left * 4;
                byte* tileDstPtr;
                int pos;
                int srcpos;


                Rectangle rc = new Rectangle(0,0, srcRect.Width, srcRect.Height);
                int wn = dstRect.Width / srcRect.Width;
                int hn = dstRect.Height / srcRect.Height;

                int wCount = wn;
                int hCount = hn;

                int richWidth = dstRect.Width - wn * srcRect.Width;
                int richHeight = dstRect.Height - hn * srcRect.Height;

                if (richWidth > 0)
                    wCount++;

                if (richHeight > 0)
                    hCount++;

                int[] wlist = new int[wCount];
                int[] hlist = new int[hCount];

                for (int i = 0; i < wn; i++)
                    wlist[i] = srcRect.Width;

                if (richWidth > 0)
                    wlist[wCount - 1] = richWidth;

                for (int i = 0; i < hn; i++)
                    hlist[i] = srcRect.Height;

                if (richHeight > 0)
                    hlist[hCount - 1] = richHeight;


                for (int i = 0; i < wlist.Count(); i++)
                {
                    for (int j = 0; j < hlist.Count(); j++)
                    {
                        rc.X = i * srcRect.Width;
                        rc.Y = j * srcRect.Height;
                        rc.Width = wlist[i];
                        rc.Height = hlist[j];

                        tileDstPtr = dstPtr + rc.Top * dstBmData.Stride + rc.Left * 4;

                        for (int m = 0; m < rc.Height; m++)
                        {
                            pos = m * dstBmData.Stride;
                            srcpos = m * srcBmData.Stride;

                            for (int n = 0; n < rc.Width; n++)
                            {
                                *((int*)(tileDstPtr + pos)) = *((int*)(srcPtr + srcpos));
                                pos += 4;
                                srcpos += 4;
                            }
                        }
                    }
                }

                //解锁位图
                srcBitmap.UnlockBits(srcBmData);
                dstBitmap.UnlockBits(dstBmData);
            }
        }

19 Source : Dot9BitmapD2D.cs
with GNU General Public License v3.0
from cymheart

static public Dot9BitmapD2D CreateDot9BoxShadowBitmap(D2DGraphics g, float cornersRadius, float shadowRadius, System.Drawing.Color shadowColor)
        {
            int width = (int)(cornersRadius * 2 + shadowRadius * 4 + 2);
            int height = (int)(cornersRadius * 2 + shadowRadius * 4 + 2);

            SharpDX.Direct2D1.PixelFormat format = new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, AlphaMode.Premultiplied);
            BitmapProperties prop = new BitmapProperties(format);
            SharpDX.Direct2D1.Bitmap bitmap = new SharpDX.Direct2D1.Bitmap(g.RenderTarget, new Size2(width, height), prop);
  
            unsafe
            {
                System.Drawing.Bitmap gdibmp = new System.Drawing.Bitmap(width, height);
                System.Drawing.RectangleF rect = new System.Drawing.RectangleF(shadowRadius, shadowRadius, width - shadowRadius * 2, height - shadowRadius * 2);
                Graphics gdiGraph = Graphics.FromImage(gdibmp);
                GraphicsPath myPath = DrawUtils.CreateRoundedRectanglePath(rect, cornersRadius);
                System.Drawing.Brush brush = new SolidBrush(shadowColor);
                gdiGraph.FillPath(brush, myPath);
                brush.Dispose();

                GaussianBlur gs = new GaussianBlur((int)shadowRadius);
                gdibmp = gs.ProcessImage(gdibmp);

                System.Drawing.Rectangle bitmapRect = new System.Drawing.Rectangle(0, 0, gdibmp.Width, gdibmp.Height);
                BitmapData srcBmData = gdibmp.LockBits(bitmapRect, ImageLockMode.ReadWrite, System.Drawing.Imaging.PixelFormat.Format32bppPArgb);
                byte* ptr = (byte*)srcBmData.Scan0;
                bitmap.CopyFromMemory((IntPtr)ptr, srcBmData.Stride);
                gdibmp.UnlockBits(srcBmData);

                //  gdibmp.Save("f:\\shadow.png");
                gdibmp.Dispose();
            }

   

            int[] widthPts = new int[]
            {
                (int)(cornersRadius + shadowRadius*2 + 1 ), (int)(width - cornersRadius - shadowRadius*2 - 1)
            };

            int[] heightPts = new int[]
            {
                 (int)(cornersRadius + shadowRadius*2 + 1), (int)(width - cornersRadius - shadowRadius*2 - 1)
            };

         
            Dot9BitmapD2D dot9Bitmap = new Dot9BitmapD2D(bitmap, widthPts, heightPts);
            return dot9Bitmap;
        }

19 Source : ColorDisplace.cs
with GNU General Public License v3.0
from cymheart

static public byte[,] GetAlphaMask(Bitmap srcBitmap)
        {
            unsafe
            {
                int width = srcBitmap.Width;
                int height = srcBitmap.Height;
                byte[,] alphaMask = new byte[width, height];
                Rectangle bitmapRect = new Rectangle(0, 0, width, height);

                //将Bitmap锁定到系统内存中,获得BitmapData
                BitmapData srcBmData = srcBitmap.LockBits(bitmapRect,
                    ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);


                byte* srcScan = (byte*)(void*)(srcBmData.Scan0);

                //位图中第一个像素数据的地址。它也可以看成是位图中的第一个扫描行
                byte* srcPtr = srcScan;
                int pos;

                for (int i = 0; i < height; i++)
                {
                    pos = i * srcBmData.Stride;

                    for (int j = 0; j < width; j++)
                    {
                        alphaMask[j, i] = *(srcPtr + pos + 3);
                        pos += 4;
                    }
                }

                //解锁位图
                srcBitmap.UnlockBits(srcBmData);
  
                return alphaMask;
            }
        }

19 Source : ColorDisplace.cs
with GNU General Public License v3.0
from cymheart

static public void Displace(Bitmap srcBitmap, Color color, Rectangle rc, bool usedAlpha = false)
        {
            unsafe
            {
                Rectangle bitmapRect = new Rectangle(0, 0, srcBitmap.Width, srcBitmap.Height);

                //将Bitmap锁定到系统内存中,获得BitmapData
                BitmapData srcBmData = srcBitmap.LockBits(bitmapRect,
                    ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);


                byte* srcScan = (byte*)(void*)(srcBmData.Scan0);

                //位图中第一个像素数据的地址。它也可以看成是位图中的第一个扫描行
                byte * srcPtr = srcScan + rc.Top * srcBmData.Stride + rc.Left * 4;
                int pos;

                for (int i = 0; i < rc.Height; i++)
                {
                    pos = i * srcBmData.Stride;

                    for (int j = 0; j < rc.Width; j++)
                    {
                        *(srcPtr + pos) = color.B;
                        *(srcPtr + pos + 1) = color.G;
                        *(srcPtr + pos + 2) = color.R;

                        if (usedAlpha)
                            *(srcPtr + pos + 3) = color.A;
  
                        pos += 4;
                    }
                }

                //解锁位图
                srcBitmap.UnlockBits(srcBmData);
            }
        }

19 Source : BitmapUtil.cs
with MIT License
from czh098tom

public static Bitmap ImageSourceToBitmap(ImageSource imageSource)
        {
            BitmapSource m = (BitmapSource)imageSource;

            Bitmap bmp = new Bitmap(m.PixelWidth, m.PixelHeight, System.Drawing.Imaging.PixelFormat.Format32bppPArgb);

            BitmapData data = bmp.LockBits(
            new Rectangle(System.Drawing.Point.Empty, bmp.Size), ImageLockMode.WriteOnly, 
            System.Drawing.Imaging.PixelFormat.Format32bppPArgb);

            m.CopyPixels(Int32Rect.Empty, data.Scan0, data.Height * data.Stride, data.Stride); bmp.UnlockBits(data);

            return bmp;
        }

19 Source : Bitmaps.cs
with MIT License
from d-mod

public static void ToArray(this Bitmap bmp, out byte[] data) {
            data = new byte[bmp.Width * bmp.Height * 4];
            var bmpData = bmp.LockBits(new Rectangle(Point.Empty, bmp.Size), ImageLockMode.ReadOnly,
                PixelFormat.Format32bppArgb);
            Marshal.Copy(bmpData.Scan0, data, 0, data.Length);
            bmp.UnlockBits(bmpData);
        }

19 Source : Bitmaps.cs
with MIT License
from d-mod

public static Bitmap FromArray(byte[] data, Size size) {
            var bmp = new Bitmap(size.Width, size.Height, PixelFormat.Format32bppArgb);
            var bmpData = bmp.LockBits(new Rectangle(Point.Empty, size), ImageLockMode.WriteOnly,
                PixelFormat.Format32bppArgb);
            Marshal.Copy(data, 0, bmpData.Scan0, data.Length);
            bmp.UnlockBits(bmpData);
            return bmp;
        }

19 Source : GraphicsExtension.cs
with MIT License
from dahall

public void Dispose()
			{
				//if (lockMode != ImageLockMode.ReadOnly)
				//	Marshal.Copy(pixels, 0, bd.Scan0, Length);
				bmp.UnlockBits(bd);
				GC.SuppressFinalize(this);
			}

19 Source : FastBitmap.cs
with BSD 3-Clause "New" or "Revised" License
from DannyTheSloth

public void Unlock()
        {
            if (IsLocked)
            {
                bitmap.UnlockBits(bitmapData);
                IsLocked = false;
            }
        }

19 Source : FastBitmap.cs
with BSD 3-Clause "New" or "Revised" License
from DannyTheSloth

public void Dispose()
        {
            if (bitmap != null)
            {
                try
                {
                    bitmap.UnlockBits(bitmapData);
                }
                catch { }

                try
                {
                    bitmap.Dispose();
                }
                catch { }

                try
                {
                    bitmap = null;
                    bitmapData = null;
                }
                catch { }
            }
        }

19 Source : SimpleBitmap.cs
with BSD 3-Clause "New" or "Revised" License
from DannyTheSloth

public void Unlock()
        {
            if (!Locked)
                throw new Exception("Nothing to unlock");

            lock (ProcessingLock)
            {
                Scan0 = IntPtr.Zero;
                Scan0_int = 0;

                Info.Clear();
                bitMap.UnlockBits(bitmapData);
                bitmapData = null;
            }
        }

19 Source : UnsafeStreamCodec.cs
with BSD 3-Clause "New" or "Revised" License
from DannyTheSloth

public override unsafe void CodeImage(IntPtr Scan0, Rectangle ScanArea, Size ImageSize, PixelFormat Format,
            Stream outStream)
        {
            lock (ImageProcessLock)
            {
                byte* pScan0 = (byte*)Scan0.ToInt32();
                if (!outStream.CanWrite)
                    throw new Exception("Must have access to Write in the Stream");

                int Stride = 0;
                int RawLength = 0;
                int PixelSize = 0;

                switch (Format)
                {
                    case PixelFormat.Format24bppRgb:
                    case PixelFormat.Format32bppRgb:
                        PixelSize = 3;
                        break;

                    case PixelFormat.Format32bppArgb:
                    case PixelFormat.Format32bppPArgb:
                        PixelSize = 4;
                        break;

                    default:
                        throw new NotSupportedException(Format.ToString());
                }

                Stride = ImageSize.Width * PixelSize;
                RawLength = Stride * ImageSize.Height;

                if (EncodeBuffer == null)
                {
                    EncodedFormat = Format;
                    EncodedWidth = ImageSize.Width;
                    EncodedHeight = ImageSize.Height;
                    EncodeBuffer = new byte[RawLength];
                    fixed (byte* ptr = EncodeBuffer)
                    {
                        byte[] temp = null;
                        using (Bitmap TmpBmp = new Bitmap(ImageSize.Width, ImageSize.Height, Stride, Format, Scan0))
                        {
                            temp = jpgCompression.Compress(TmpBmp);
                        }

                        outStream.Write(BitConverter.GetBytes(temp.Length), 0, 4);
                        outStream.Write(temp, 0, temp.Length);
                        NativeMethods.memcpy(new IntPtr(ptr), Scan0, (uint)RawLength);
                    }

                    return;
                }

                long oldPos = outStream.Position;
                outStream.Write(new byte[4], 0, 4);
                int TotalDataLength = 0;

                if (EncodedFormat != Format)
                    throw new Exception("PixelFormat is not equal to previous Bitmap");

                if (EncodedWidth != ImageSize.Width || EncodedHeight != ImageSize.Height)
                    throw new Exception("Bitmap width/height are not equal to previous bitmap");

                List<Rectangle> Blocks = new List<Rectangle>();
                int index = 0;

                Size s = new Size(ScanArea.Width, CheckBlock.Height);
                Size lastSize = new Size(ScanArea.Width % CheckBlock.Width, ScanArea.Height % CheckBlock.Height);

                int lasty = ScanArea.Height - lastSize.Height;
                int lastx = ScanArea.Width - lastSize.Width;

                Rectangle cBlock = new Rectangle();
                List<Rectangle> finalUpdates = new List<Rectangle>();

                s = new Size(ScanArea.Width, s.Height);
                fixed (byte* encBuffer = EncodeBuffer)
                {
                    for (int y = ScanArea.Y; y != ScanArea.Height;)
                    {
                        if (y == lasty)
                            s = new Size(ScanArea.Width, lastSize.Height);
                        cBlock = new Rectangle(ScanArea.X, y, ScanArea.Width, s.Height);

                        if (onCodeDebugScan != null)
                            onCodeDebugScan(cBlock);

                        int offset = y * Stride + ScanArea.X * PixelSize;
                        if (NativeMethods.memcmp(encBuffer + offset, pScan0 + offset, (uint)Stride) != 0)
                        {
                            index = Blocks.Count - 1;
                            if (Blocks.Count != 0 && Blocks[index].Y + Blocks[index].Height == cBlock.Y)
                            {
                                cBlock = new Rectangle(Blocks[index].X, Blocks[index].Y, Blocks[index].Width,
                                    Blocks[index].Height + cBlock.Height);
                                Blocks[index] = cBlock;
                            }
                            else
                            {
                                Blocks.Add(cBlock);
                            }
                        }

                        y += s.Height;
                    }

                    for (int i = 0, x = ScanArea.X; i < Blocks.Count; i++)
                    {
                        s = new Size(CheckBlock.Width, Blocks[i].Height);
                        x = ScanArea.X;
                        while (x != ScanArea.Width)
                        {
                            if (x == lastx)
                                s = new Size(lastSize.Width, Blocks[i].Height);

                            cBlock = new Rectangle(x, Blocks[i].Y, s.Width, Blocks[i].Height);
                            bool FoundChanges = false;
                            int blockStride = PixelSize * cBlock.Width;

                            for (int j = 0; j < cBlock.Height; j++)
                            {
                                int blockOffset = Stride * (cBlock.Y + j) + PixelSize * cBlock.X;
                                if (NativeMethods.memcmp(encBuffer + blockOffset, pScan0 + blockOffset,
                                        (uint)blockStride) != 0)
                                    FoundChanges = true;
                                NativeMethods.memcpy(encBuffer + blockOffset, pScan0 + blockOffset,
                                    (uint)blockStride); //copy-changes
                            }

                            if (onCodeDebugScan != null)
                                onCodeDebugScan(cBlock);

                            if (FoundChanges)
                            {
                                index = finalUpdates.Count - 1;
                                if (finalUpdates.Count > 0 &&
                                    finalUpdates[index].X + finalUpdates[index].Width == cBlock.X)
                                {
                                    Rectangle rect = finalUpdates[index];
                                    int newWidth = cBlock.Width + rect.Width;
                                    cBlock = new Rectangle(rect.X, rect.Y, newWidth, rect.Height);
                                    finalUpdates[index] = cBlock;
                                }
                                else
                                {
                                    finalUpdates.Add(cBlock);
                                }
                            }

                            x += s.Width;
                        }
                    }
                }

                /*int maxHeight = 0;
                int maxWidth = 0;

                for (int i = 0; i < finalUpdates.Count; i++)
                {
                    if (finalUpdates[i].Height > maxHeight)
                        maxHeight = finalUpdates[i].Height;
                    maxWidth += finalUpdates[i].Width;
                }

                Bitmap bmp = new Bitmap(maxWidth+1, maxHeight+1);
                int XOffset = 0;*/

                for (int i = 0; i < finalUpdates.Count; i++)
                {
                    Rectangle rect = finalUpdates[i];
                    int blockStride = PixelSize * rect.Width;

                    Bitmap TmpBmp = new Bitmap(rect.Width, rect.Height, Format);
                    BitmapData TmpData = TmpBmp.LockBits(new Rectangle(0, 0, TmpBmp.Width, TmpBmp.Height),
                        ImageLockMode.ReadWrite, TmpBmp.PixelFormat);
                    for (int j = 0, offset = 0; j < rect.Height; j++)
                    {
                        int blockOffset = Stride * (rect.Y + j) + PixelSize * rect.X;
                        NativeMethods.memcpy((byte*)TmpData.Scan0.ToPointer() + offset, pScan0 + blockOffset,
                            (uint)blockStride); //copy-changes
                        offset += blockStride;
                    }

                    TmpBmp.UnlockBits(TmpData);

                    /*using (Graphics g = Graphics.FromImage(bmp))
                    {
                        g.DrawImage(TmpBmp, new Point(XOffset, 0));
                    }
                    XOffset += TmpBmp.Width;*/

                    outStream.Write(BitConverter.GetBytes(rect.X), 0, 4);
                    outStream.Write(BitConverter.GetBytes(rect.Y), 0, 4);
                    outStream.Write(BitConverter.GetBytes(rect.Width), 0, 4);
                    outStream.Write(BitConverter.GetBytes(rect.Height), 0, 4);
                    outStream.Write(new byte[4], 0, 4);

                    long length = outStream.Length;
                    long OldPos = outStream.Position;

                    if (UseJPEG)
                        jpgCompression.Compress(TmpBmp, ref outStream);
                    else
                        lzwCompression.Compress(TmpBmp, outStream);

                    length = outStream.Position - length;

                    outStream.Position = OldPos - 4;
                    outStream.Write(BitConverter.GetBytes((int)length), 0, 4);
                    outStream.Position += length;
                    TmpBmp.Dispose();
                    TotalDataLength += (int)length + 4 * 5;
                }

                /*if (finalUpdates.Count > 0)
                {
                    byte[] lele = base.jpgCompression.Compress(bmp);
                    byte[] compressed = new SafeQuickLZ().compress(lele, 0, lele.Length, 1);
                    bool Won = lele.Length < outStream.Length;
                    bool CompressWon = compressed.Length < outStream.Length;
                    Console.WriteLine(Won + ", " + CompressWon);
                }
                bmp.Dispose();*/

                outStream.Position = oldPos;
                outStream.Write(BitConverter.GetBytes(TotalDataLength), 0, 4);
                Blocks.Clear();
                finalUpdates.Clear();
            }
        }

19 Source : StreamClasses.cs
with BSD 3-Clause "New" or "Revised" License
from DannyTheSloth

private static async void StartRemoteDestkop()
        {
            while (RemoteDesktopActive)
            {
                byte[] ImageBytes = null;
                IUnsafeCodec UC = new UnsafeStreamCodec(50);
                Bitmap Image = GetDesktopImage();
                Rectangle Rect = new Rectangle(0, 0, Image.Width, Image.Height);
                Size S = new Size(Image.Width, Image.Height);
                BitmapData BD = Image.LockBits(new Rectangle(0, 0, Image.Width, Image.Height),
                    ImageLockMode.ReadWrite, Image.PixelFormat);
                using (MemoryStream MS = new MemoryStream(1000000000))
                {
                    UC.CodeImage(BD.Scan0, Rect, S,
                        Image.PixelFormat, MS);
                    ImageBytes = MS.ToArray();
                }

                List<byte> ToSend = new List<byte>();
                ToSend.Add((int)DataType.ImageType);
                ToSend.AddRange(ImageBytes);
                Networking.Networking.MainClient.Send(ToSend.ToArray());
                Image.UnlockBits(BD);
                Image.Dispose();               
            }
        }

19 Source : LandmarkImporter.cs
with MIT License
from DanzaG

private BitmapGraphics GetTile(TR2Level level, int index)
        {
            TRTexImage16 tex = level.Images16[index];

            Bitmap bmp = new Bitmap(256, 256, PixelFormat.Format32bppArgb);
            BitmapData bitmapData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb);

            List<byte> pixelCollection = new List<byte>();

            foreach (Textile16Pixel px in tex.To32BPPFormat())
            {
                pixelCollection.AddRange(px.RGB32);
            }

            Marshal.Copy(pixelCollection.ToArray(), 0, bitmapData.Scan0, pixelCollection.Count);
            bmp.UnlockBits(bitmapData);

            return new BitmapGraphics(bmp);
        }

19 Source : TextureLevelMapping.cs
with MIT License
from DanzaG

private BitmapGraphics GetBitmapGraphics(int tile)
        {
            if (!_tileMap.ContainsKey(tile))
            {
                TRTexImage16 tex = _level.Images16[tile];

                Bitmap bmp = new Bitmap(_tileWidth, _tileHeight, PixelFormat.Format32bppArgb);
                BitmapData bitmapData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb);

                List<byte> pixelCollection = new List<byte>();

                foreach (Textile16Pixel px in tex.To32BPPFormat())
                {
                    pixelCollection.AddRange(px.RGB32);
                }

                Marshal.Copy(pixelCollection.ToArray(), 0, bitmapData.Scan0, pixelCollection.Count);
                bmp.UnlockBits(bitmapData);

                _tileMap.Add(tile, new BitmapGraphics(bmp));
            }

            return _tileMap[tile];
        }

19 Source : TextureUtilities.cs
with MIT License
from DanzaG

public static Bitmap ToBitmap(this TRTexImage16 tex)
        {
            Bitmap bmp = new Bitmap(_tileSize, _tileSize, PixelFormat.Format32bppArgb);
            BitmapData bitmapData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb);

            List<byte> pixelCollection = new List<byte>();

            foreach (Textile16Pixel px in tex.To32BPPFormat())
            {
                pixelCollection.AddRange(px.RGB32);
            }

            Marshal.Copy(pixelCollection.ToArray(), 0, bitmapData.Scan0, pixelCollection.Count);
            bmp.UnlockBits(bitmapData);

            return bmp;
        }

19 Source : BitmapGraphics.cs
with MIT License
from DanzaG

public void AdjustHSB(Rectangle rect, HSBOperation operation)
        {
            // This is about 25% faster than using GetPixel/SetPixel

            BitmapData bd = Bitmap.LockBits(new Rectangle(0, 0, _width, _height), ImageLockMode.ReadWrite, Bitmap.PixelFormat);
            int bytesPerPixel = Image.GetPixelFormatSize(Bitmap.PixelFormat) / 8;
            int byteCount = bd.Stride * _height;
            byte[] pixels = new byte[byteCount];
            IntPtr ptrFirstPixel = bd.Scan0;
            Marshal.Copy(ptrFirstPixel, pixels, 0, byteCount);

            int startY = rect.Y;
            int endY = rect.Y + rect.Height;
            int startX = rect.X * bytesPerPixel;
            int endX = startX + rect.Width * bytesPerPixel;

            for (int y = startY; y < endY; y++)
            {
                int currentLine = y * bd.Stride;
                for (int x = startX; x < endX; x += bytesPerPixel)
                {
                    int b = pixels[currentLine + x];
                    int g = pixels[currentLine + x + 1];
                    int r = pixels[currentLine + x + 2];
                    int a = pixels[currentLine + x + 3];

                    Color c = Color.FromArgb(a, r, g, b);
                    c = ApplyHSBOperation(c, operation);

                    pixels[currentLine + x] = c.B;
                    pixels[currentLine + x + 1] = c.G;
                    pixels[currentLine + x + 2] = c.R;
                    pixels[currentLine + x + 3] = c.A;
                }
            }

            Marshal.Copy(pixels, 0, ptrFirstPixel, byteCount);
            Bitmap.UnlockBits(bd);
        }

19 Source : TextureUtilities.cs
with MIT License
from DanzaG

public static Bitmap ToBitmap(this TRTexImage8 tex, TRColour[] palette)
        {
            Bitmap bmp = new Bitmap(_tileSize, _tileSize, PixelFormat.Format32bppRgb);
            BitmapData bitmapData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.WriteOnly, PixelFormat.Format32bppRgb);

            List<byte> pixelCollection = new List<byte>();
            foreach (byte colourIndex in tex.Pixels)
            {
                TRColour c = palette[colourIndex];
                pixelCollection.Add((byte)(4 * c.Blue));
                pixelCollection.Add((byte)(4 * c.Green));
                pixelCollection.Add((byte)(4 * c.Red));
                pixelCollection.Add((byte)(colourIndex == 0 ? 0 : 0xFF)); // The first entry in the palette is used for transparency
            }

            Marshal.Copy(pixelCollection.ToArray(), 0, bitmapData.Scan0, pixelCollection.Count);
            bmp.UnlockBits(bitmapData);

            return bmp;
        }

19 Source : AmiiboTagWrapper.cs
with GNU General Public License v3.0
from DarkIrata

public Bitmap GetBitmap(int width, int height)
        {
            var resizedImg = this.AmiiboTag?.Amiibo?.AmiiboImage.CreateResized(width, height);
            var data = resizedImg.Data;

            // Convert rgba to bgra
            for (int i = 0; i < width * height; ++i)
            {
                byte r = data[i * 4];
                byte g = data[i * 4 + 1];
                byte b = data[i * 4 + 2];
                byte a = data[i * 4 + 3];


                data[i * 4] = b;
                data[i * 4 + 1] = g;
                data[i * 4 + 2] = r;
                data[i * 4 + 3] = a;
            }

            // Create Bitmap
            var bmp = new Bitmap(width, height, PixelFormat.Format32bppArgb);
            var bmpData = bmp.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.WriteOnly, bmp.PixelFormat);

            Marshal.Copy(data, 0, bmpData.Scan0, bmpData.Stride * bmp.Height);
            bmp.UnlockBits(bmpData);

            return bmp;
        }

19 Source : TextureFormats.cs
with MIT License
from DavidSM64

public static Bitmap decodeRGBA16(byte[] data, int width, int height)
        {
            Bitmap tex = new Bitmap(width, height);
            if (data.Length >= width * height * 2) // Sanity Check
            {
                BitmapData bitmapData = tex.LockBits(new Rectangle(0, 0, width, height),
                    ImageLockMode.ReadWrite, tex.PixelFormat);
                byte[] pixels = new byte[width * height * 4];

                int len = width * height;
                for (int i = 0; i < len; i++)
                {
                    ushort pixel = (ushort)((data[i * 2] << 8) | data[i * 2 + 1]);
                    pixels[(i * 4) + 2] = (byte)(((pixel >> 11) & 0x1F) * 8); // Red
                    pixels[(i * 4) + 1] = (byte)(((pixel >> 6) & 0x1F) * 8); // Green
                    pixels[(i * 4) + 0] = (byte)(((pixel >> 1) & 0x1F) * 8); // Blue
                    pixels[(i * 4) + 3] = (pixel & 1) > 0 ? (byte)0xFF : (byte)0x00; // (Transparency)
                }
                Marshal.Copy(pixels, 0, bitmapData.Scan0, pixels.Length);
                tex.UnlockBits(bitmapData);
            }

            tex.Tag = new string[] { "Format: RGBA16", "Width: " + width,
             "Height: " + height };
            return tex;
        }

19 Source : TextureFormats.cs
with MIT License
from DavidSM64

public static Bitmap decodeI4(byte[] data, int width, int height)
        {
            Bitmap tex = new Bitmap(width, height);

            if (data.Length >= (width * height) / 2) // Sanity Check
            {
                BitmapData bitmapData = tex.LockBits(new Rectangle(0, 0, width, height),
                ImageLockMode.ReadWrite, tex.PixelFormat);
                byte[] pixels = new byte[width * height * 4];

                int len = (width * height) / 2;
                for (int i = 0; i < len; i++)
                {
                    byte twoPixels = data[i];

                    byte intensity = (byte)((twoPixels >> 4) * 16);
                    pixels[(i * 8) + 2] = intensity; // Red
                    pixels[(i * 8) + 1] = intensity; // Green
                    pixels[(i * 8) + 0] = intensity; // Blue
                    pixels[(i * 8) + 3] = 0xFF; // Alpha

                    intensity = (byte)((twoPixels & 0xF) * 16);
                    pixels[(i * 8) + 6] = intensity; // Red
                    pixels[(i * 8) + 5] = intensity; // Green
                    pixels[(i * 8) + 4] = intensity; // Blue
                    pixels[(i * 8) + 7] = 0xFF; // Alpha
                }
                Marshal.Copy(pixels, 0, bitmapData.Scan0, pixels.Length);
                tex.UnlockBits(bitmapData);
            }
            tex.Tag = new string[] { "Format: I4", "Width: " + width,
             "Height: " + height };
            return tex;
        }

19 Source : TextureFormats.cs
with MIT License
from DavidSM64

public static Bitmap decodeCI4(byte[] data, int width, int height, ushort[] palette, bool isPaletteRGBA16)
        {
            Bitmap tex = new Bitmap(width, height);

            if (data.Length >= (width * height) / 2) // Sanity Check
            {
                BitmapData bitmapData = tex.LockBits(new Rectangle(0, 0, width, height),
                ImageLockMode.ReadWrite, tex.PixelFormat);
                byte[] pixels = new byte[width * height * 4];

                int len = (width * height) / 2;
                for (int i = 0; i < len; i++)
                {
                    ushort pixel = palette[(data[i] >> 4) & 0xF];
                    pixels[(i * 8) + 2] = (byte)(((pixel >> 11) & 0x1F) * 8); // Red
                    pixels[(i * 8) + 1] = (byte)(((pixel >> 6) & 0x1F) * 8); // Green
                    pixels[(i * 8) + 0] = (byte)(((pixel >> 1) & 0x1F) * 8); // Blue
                    pixels[(i * 8) + 3] = (pixel & 1) > 0 ? (byte)0xFF : (byte)0x00; // Alpha

                    pixel = palette[(data[i]) & 0xF];
                    pixels[(i * 8) + 6] = (byte)(((pixel >> 11) & 0x1F) * 8); // Red
                    pixels[(i * 8) + 5] = (byte)(((pixel >> 6) & 0x1F) * 8); // Green
                    pixels[(i * 8) + 4] = (byte)(((pixel >> 1) & 0x1F) * 8); // Blue
                    pixels[(i * 8) + 7] = (pixel & 1) > 0 ? (byte)0xFF : (byte)0x00; // Alpha

                }
                Marshal.Copy(pixels, 0, bitmapData.Scan0, pixels.Length);
                tex.UnlockBits(bitmapData);
            }
            tex.Tag = new string[] { "Format: CI4", "Width: " + width,
             "Height: " + height };
            return tex;
        }

19 Source : TextureFormats.cs
with MIT License
from DavidSM64

public static Bitmap decodeCI8(byte[] data, int width, int height, ushort[] palette, bool isPaletteRGBA16)
        {
            Bitmap tex = new Bitmap(width, height);

            if (data.Length >= width * height) // Sanity Check
            {
                BitmapData bitmapData = tex.LockBits(new Rectangle(0, 0, width, height),
                ImageLockMode.ReadWrite, tex.PixelFormat);
                byte[] pixels = new byte[width * height * 4];

                int len = width * height;
                for (int i = 0; i < len; i++)
                {
                    ushort pixel = palette[data[i]];
                    pixels[(i * 4) + 2] = (byte)(((pixel >> 11) & 0x1F) * 8); // Red
                    pixels[(i * 4) + 1] = (byte)(((pixel >> 6) & 0x1F) * 8); // Green
                    pixels[(i * 4) + 0] = (byte)(((pixel >> 1) & 0x1F) * 8); // Blue
                    pixels[(i * 4) + 3] = (pixel & 1) > 0 ? (byte)0xFF : (byte)0x00; // (Transparency)
                                                                                     //tex.SetPixel(i % width, i / width, Color.FromArgb(alpha, red, green, blue));
                }
                Marshal.Copy(pixels, 0, bitmapData.Scan0, pixels.Length);
                tex.UnlockBits(bitmapData);
            }
            tex.Tag = new string[] { "Format: CI8", "Width: " + width,
             "Height: " + height };
            return tex;
        }

19 Source : ContentPipe.cs
with MIT License
from DavidSM64

public static Texture2D LoadTexture(ref Bitmap bitmap)
        {
            int id = GL.GenTexture();
            BitmapData bmpData = bitmap.LockBits(
                new Rectangle(0, 0, bitmap.Width, bitmap.Height),
                ImageLockMode.ReadOnly,
                System.Drawing.Imaging.PixelFormat.Format32bppArgb);
            GL.BindTexture(TextureTarget.Texture2D, id);
            GL.TexImage2D(TextureTarget.Texture2D,
                0,
                PixelInternalFormat.Rgba,
                bitmap.Width, bitmap.Height, 0,
                OpenTK.Graphics.OpenGL.PixelFormat.Bgra,
                PixelType.UnsignedByte,
                bmpData.Scan0);
            bitmap.UnlockBits(bmpData);
            GL.TexParameter(TextureTarget.Texture2D,
                TextureParameterName.TextureMinFilter,
                (int)TextureMinFilter.Linear);
            GL.TexParameter(TextureTarget.Texture2D,
                TextureParameterName.TextureMagFilter,
                (int)TextureMagFilter.Linear);
            
            return new Texture2D(id, bitmap.Width, bitmap.Height);
        }

19 Source : TextureFormats.cs
with MIT License
from DavidSM64

public static Bitmap decodeI8(byte[] data, int width, int height)
        {
            Bitmap tex = new Bitmap(width, height);

            if (data.Length >= width * height) // Sanity Check
            {
                BitmapData bitmapData = tex.LockBits(new Rectangle(0, 0, width, height),
                ImageLockMode.ReadWrite, tex.PixelFormat);
                byte[] pixels = new byte[width * height * 4];

                int len = width * height;
                for (int i = 0; i < len; i++)
                {
                    byte intensity = data[i];
                    pixels[(i * 4) + 2] = intensity; // Red
                    pixels[(i * 4) + 1] = intensity; // Green
                    pixels[(i * 4) + 0] = intensity; // Blue
                    pixels[(i * 4) + 3] = 0xFF; // Alpha
                }
                Marshal.Copy(pixels, 0, bitmapData.Scan0, pixels.Length);
                tex.UnlockBits(bitmapData);

                tex.Tag = new string[] { "Format: I8", "Width: " + width,
             "Height: " + height };
            }
            return tex;
        }

19 Source : TextureFormats.cs
with MIT License
from DavidSM64

public static Bitmap decodeIA16(byte[] data, int width, int height)
        {
            Bitmap tex = new Bitmap(width, height);
            if (data.Length >= width * height * 2) // Sanity Check
            {
                BitmapData bitmapData = tex.LockBits(new Rectangle(0, 0, width, height),
                ImageLockMode.ReadWrite, tex.PixelFormat);
                byte[] pixels = new byte[width * height * 4];

                int len = width * height;
                for (int i = 0; i < len; i++)
                {
                    pixels[(i * 4) + 2] = data[i * 2]; // Red
                    pixels[(i * 4) + 1] = data[i * 2]; // Green
                    pixels[(i * 4) + 0] = data[i * 2]; // Blue
                    pixels[(i * 4) + 3] = data[(i * 2) + 1]; // Alpha
                }
                Marshal.Copy(pixels, 0, bitmapData.Scan0, pixels.Length);
                tex.UnlockBits(bitmapData);
            }
            tex.Tag = new string[] { "Format: IA16", "Width: " + width,
             "Height: " + height};
            return tex;
        }

19 Source : TextureFormats.cs
with MIT License
from DavidSM64

public static Bitmap decodeRGBA32(byte[] data, int width, int height)
        {
            Console.WriteLine("Texture size = (" + width + "x" + height + ")");
            Console.WriteLine("data.Length = (" + data.Length + ")");
            Bitmap tex = new Bitmap(width, height);

            if (data.Length >= width * height * 4) // Sanity Check
            {
                BitmapData bitmapData = tex.LockBits(new Rectangle(0, 0, width, height),
                ImageLockMode.ReadWrite, tex.PixelFormat);

                int len = width * height;
                for (int i = 0; i < len; i++)
                {
                    // Swap red and blue values
                    byte temp_red = data[(i * 4) + 0];
                    data[(i * 4) + 0] = data[(i * 4) + 2];
                    data[(i * 4) + 2] = temp_red;
                }
                Marshal.Copy(data, 0, bitmapData.Scan0, data.Length);
                tex.UnlockBits(bitmapData);

            }
            tex.Tag = new string[] { "Format: RGBA32", "Width: " + width,
             "Height: " + height };
            return tex;
        }

19 Source : TextureFormats.cs
with MIT License
from DavidSM64

public static Bitmap decodeIA8(byte[] data, int width, int height)
        {
            Bitmap tex = new Bitmap(width, height);
            if (data.Length >= width * height) // Sanity Check
            {
                BitmapData bitmapData = tex.LockBits(new Rectangle(0, 0, width, height),
                ImageLockMode.ReadWrite, tex.PixelFormat);
                byte[] pixels = new byte[width * height * 4];

                int len = width * height;
                for (int i = 0; i < len; i++)
                {
                    byte intensity = (byte)(((data[i] >> 4) & 0xF) * 16);
                    pixels[(i * 4) + 2] = intensity; // Red
                    pixels[(i * 4) + 1] = intensity; // Green
                    pixels[(i * 4) + 0] = intensity; // Blue
                    pixels[(i * 4) + 3] = (byte)((data[i] & 0xF) * 16); // Alpha
                }
                Marshal.Copy(pixels, 0, bitmapData.Scan0, pixels.Length);
                tex.UnlockBits(bitmapData);
            }
            tex.Tag = new string[] { "Format: IA8", "Width: " + width,
             "Height: " + height };
            return tex;
        }

19 Source : TextureFormats.cs
with MIT License
from DavidSM64

public static Bitmap decodeIA4(byte[] data, int width, int height)
        {
            Bitmap tex = new Bitmap(width, height);

            if (data.Length >= (width * height) / 2) // Sanity Check
            {
                BitmapData bitmapData = tex.LockBits(new Rectangle(0, 0, width, height),
                ImageLockMode.ReadWrite, tex.PixelFormat);
                byte[] pixels = new byte[width * height * 4];

                int len = (width * height) / 2;
                for (int i = 0; i < len; i++)
                {
                    byte twoPixels = data[i];

                    byte intensity = (byte)((twoPixels >> 5) * 32);
                    pixels[(i * 8) + 2] = intensity; // Red
                    pixels[(i * 8) + 1] = intensity; // Green
                    pixels[(i * 8) + 0] = intensity; // Blue
                    pixels[(i * 8) + 3] = (byte)(((twoPixels >> 4) & 0x1) * 255); // Alpha

                    intensity = (byte)(((twoPixels >> 1) & 0x7) * 32);
                    pixels[(i * 8) + 6] = intensity; // Red
                    pixels[(i * 8) + 5] = intensity; // Green
                    pixels[(i * 8) + 4] = intensity; // Blue
                    pixels[(i * 8) + 7] = (byte)((twoPixels & 0x1) * 255); // Alpha
                }
                Marshal.Copy(pixels, 0, bitmapData.Scan0, pixels.Length);
                tex.UnlockBits(bitmapData);
                tex.Tag = new string[] { "Format: IA4", "Width: " + width,
             "Height: " + height };
            }
            return tex;
        }

19 Source : ImageChannelNode.cs
with MIT License
from DebugST

void m_op_img_in_DataTransfer(object sender, STNodeOptionEventArgs e) {
            //如果当前不是连接状态 或者 接受到的数据为空
            if (e.Status != ConnectionStatus.Connected || e.TargetOption.Data == null) {
                m_op_img_out.TransferData(null);    //向所有输出节点输出空数据
                m_op_img_r.TransferData(null);
                m_op_img_g.TransferData(null);
                m_op_img_b.TransferData(null);
                m_img_draw = null;                  //需要绘制显示的图片置为空
            } else {
                Bitmap bmp = (Bitmap)e.TargetOption.Data;           //否则计算图片的RGB图像
                Bitmap bmp_r = new Bitmap(bmp.Width, bmp.Height);
                Bitmap bmp_g = new Bitmap(bmp.Width, bmp.Height);
                Bitmap bmp_b = new Bitmap(bmp.Width, bmp.Height);
                BitmapData bmpData = bmp.LockBits(new Rectangle(Point.Empty, bmp.Size), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
                BitmapData bmpData_r = bmp_r.LockBits(new Rectangle(Point.Empty, bmp.Size), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb);
                BitmapData bmpData_g = bmp_g.LockBits(new Rectangle(Point.Empty, bmp.Size), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb);
                BitmapData bmpData_b = bmp_b.LockBits(new Rectangle(Point.Empty, bmp.Size), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb);
                byte[] byColor = new byte[bmpData.Height * bmpData.Stride];
                byte[] byColor_r = new byte[byColor.Length];
                byte[] byColor_g = new byte[byColor.Length];
                byte[] byColor_b = new byte[byColor.Length];
                System.Runtime.InteropServices.Marshal.Copy(bmpData.Scan0, byColor, 0, byColor.Length);
                for (int y = 0; y < bmpData.Height; y++) {
                    int ny = y * bmpData.Stride;
                    for (int x = 0; x < bmpData.Width; x++) {
                        int nx = x << 2;
                        byColor_b[ny + nx] = byColor[ny + nx];
                        byColor_g[ny + nx + 1] = byColor[ny + nx + 1];
                        byColor_r[ny + nx + 2] = byColor[ny + nx + 2];
                        byColor_r[ny + nx + 3] = byColor_g[ny + nx + 3] = byColor_b[ny + nx + 3] = byColor[ny + nx + 3];
                    }
                }
                bmp.UnlockBits(bmpData);
                System.Runtime.InteropServices.Marshal.Copy(byColor_r, 0, bmpData_r.Scan0, byColor_r.Length);
                System.Runtime.InteropServices.Marshal.Copy(byColor_g, 0, bmpData_g.Scan0, byColor_g.Length);
                System.Runtime.InteropServices.Marshal.Copy(byColor_b, 0, bmpData_b.Scan0, byColor_b.Length);
                bmp_r.UnlockBits(bmpData_r);
                bmp_g.UnlockBits(bmpData_g);
                bmp_b.UnlockBits(bmpData_b);
                m_op_img_out.TransferData(bmp); //out选项 输出原图
                m_op_img_r.TransferData(bmp_r); //R选项输出R图
                m_op_img_g.TransferData(bmp_g);
                m_op_img_b.TransferData(bmp_b);
                m_img_draw = bmp;               //需要绘制显示的图片
            }
        }

19 Source : GdalImageSource.cs
with GNU General Public License v3.0
from DeepHydro

public Bitmap GetBitmap(int startRow, int startColumn, int numRows, int numColumns, int overview)
        {
            byte[] vals = ReadWindow(startRow, startColumn, numRows, numColumns, overview);
            Bitmap bmp = new Bitmap(numRows, numColumns);

            BitmapData bData = bmp.LockBits(new Rectangle(0, 0, numColumns, numRows), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb);
            //int stride = bData.Stride;
            Marshal.Copy(vals, 0, bData.Scan0, vals.Length);
            bmp.UnlockBits(bData);
            return bmp;
        }

19 Source : GdalTiledImage.cs
with GNU General Public License v3.0
from DeepHydro

private void ReadArgb()
        {
            if (_dataset.RasterCount < 4)
            {
                throw new GdalException("ARGB Format was indicated but there are only " + _dataset.RasterCount + " bands!");
            }
            _alpha = _red;
            _red = _dataset.GetRasterBand(2);
            _green = _dataset.GetRasterBand(3);
            _blue = _dataset.GetRasterBand(4);

            int tw = TileCollection.TileWidth;
            int th = TileCollection.TileHeight;
            for (int row = 0; row < TileCollection.NumTilesTall(); row++)
            {
                for (int col = 0; col < TileCollection.NumTilesWide(); col++)
                {
                    int width = TileCollection.GetTileWidth(col);
                    int height = TileCollection.GetTileHeight(row);
                    InRamImageData id = new InRamImageData(width, height);

                    Bitmap image = new Bitmap(width, height, PixelFormat.Format32bppArgb);

                    byte[] red = new byte[width * height];
                    byte[] g = new byte[width * height];
                    byte[] b = new byte[width * height];
                    byte[] a = new byte[width * height];

                    _red.ReadRaster(col * tw, row * th, width, height, red, width, height, 0, 0);
                    _green.ReadRaster(col * tw, row * th, width, height, g, width, height, 0, 0);
                    _blue.ReadRaster(col * tw, row * th, width, height, b, width, height, 0, 0);
                    _alpha.ReadRaster(col * tw, row * th, width, height, a, width, height, 0, 0);

                    BitmapData bData = image.LockBits(new Rectangle(0, 0, Width, Height), ImageLockMode.ReadWrite,
                                                       PixelFormat.Format32bppArgb);
                    Stride = bData.Stride;
                    image.UnlockBits(bData);
                    byte[] vals = new byte[Width * Height * 4];
                    int stride = Stride;
                    const int bpp = 4;
                    for (int r = 0; r < height; r++)
                    {
                        for (int c = 0; c < width; c++)
                        {
                            vals[r * stride + c * bpp] = b[r * width + c];
                            vals[r * stride + c * bpp + 1] = g[r * width + c];
                            vals[r * stride + c * bpp + 2] = red[r * width + c];
                            vals[r * stride + c * bpp + 3] = a[r * width + c];
                        }
                    }
                    id.Values = vals;
                    id.CopyValuesToBitmap();
                    TileCollection.Tiles[row, col] = id;
                }
            }
            SetTileBounds(Bounds.AffineCoefficients);
        }

19 Source : GdalTiledImage.cs
with GNU General Public License v3.0
from DeepHydro

private void ReadPaletteBuffered()
        {
            ColorTable ct = _red.GetRasterColorTable();
            if (ct == null)
            {
                throw new GdalException("Image was stored with a palette interpretation but has no color table.");
            }
            if (ct.GetPaletteInterpretation() != PaletteInterp.GPI_RGB)
            {
                throw new GdalException("Only RGB palette interpreation is currently supported by this plugin, " + ct.GetPaletteInterpretation() + " is not supported.");
            }

            int tw = TileCollection.TileWidth;
            int th = TileCollection.TileHeight;
            for (int row = 0; row < TileCollection.NumTilesTall(); row++)
            {
                for (int col = 0; col < TileCollection.NumTilesWide(); col++)
                {
                    // takes into account that right and bottom tiles might be smaller.
                    int width = TileCollection.GetTileWidth(col);
                    int height = TileCollection.GetTileHeight(row);
                    ImageData id = new ImageData();
                    byte[] red = new byte[width * height];
                    _red.ReadRaster(col * tw, row * th, width, height, red, width, height, 0, 0);
                    Bitmap image = new Bitmap(width, height, PixelFormat.Format32bppArgb);
                    BitmapData bData = image.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);
                    Stride = bData.Stride;
                    image.UnlockBits(bData);

                    const int bpp = 4;
                    int stride = Stride;
                    byte[] vals = new byte[width * height * 4];
                    byte[][] colorTable = new byte[256][];
                    for (int i = 0; i < 255; i++)
                    {
                        ColorEntry ce = ct.GetColorEntry(i);
                        colorTable[i] = new[] { (byte)ce.c3, (byte)ce.c2, (byte)ce.c1, (byte)ce.c4 };
                    }
                    for (int r = 0; r < height; r++)
                    {
                        for (int c = 0; c < width; c++)
                        {
                            Array.Copy(colorTable[red[c + r * width]], 0, vals, row * stride + col * bpp, 4);
                        }
                    }
                    id.Values = vals;
                    id.CopyValuesToBitmap();
                    TileCollection.Tiles[row, col] = id;
                }
            }
            SetTileBounds(Bounds.AffineCoefficients);
        }

19 Source : GdalTiledImage.cs
with GNU General Public License v3.0
from DeepHydro

private void ReadGrayIndex()
        {
            int tw = TileCollection.TileWidth;
            int th = TileCollection.TileHeight;
            for (int row = 0; row < TileCollection.NumTilesTall(); row++)
            {
                for (int col = 0; col < TileCollection.NumTilesWide(); col++)
                {
                    int width = TileCollection.GetTileWidth(col);
                    int height = TileCollection.GetTileHeight(row);
                    InRamImageData id = new InRamImageData(width, height);
                    byte[] red = new byte[width * height];
                    _red.ReadRaster(col * tw, row * th, width, height, red, width, height, 0, 0);
                    Bitmap image = new Bitmap(width, height);
                    BitmapData bData = image.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite,
                                                       PixelFormat.Format32bppArgb);
                    Stride = bData.Stride;
                    image.UnlockBits(bData);
                    byte[] vals = new byte[width * height * 4];

                    int stride = Stride;
                    const int bpp = 4;

                    for (int r = 0; r < height; r++)
                    {
                        for (int c = 0; c < width; c++)
                        {
                            vals[r * stride + c * bpp] = red[r * width + c];
                            vals[r * stride + c * bpp + 1] = red[r * width + c];
                            vals[r * stride + c * bpp + 2] = red[r * width + c];
                            vals[r * stride + c * bpp + 3] = 255;
                        }
                    }
                    id.Values = vals;

                    id.CopyValuesToBitmap();
                    TileCollection.Tiles[row, col] = id;
                }
            }
            SetTileBounds(Bounds.AffineCoefficients);
        }

19 Source : GdalTiledImage.cs
with GNU General Public License v3.0
from DeepHydro

private void ReadRgb()
        {
            if (_dataset.RasterCount < 3)
            {
                throw new GdalException("RGB Format was indicated but there are only " + _dataset.RasterCount + " bands!");
            }
            _green = _dataset.GetRasterBand(2);
            _blue = _dataset.GetRasterBand(3);

            int tw = TileCollection.TileWidth;
            int th = TileCollection.TileHeight;
            int ntt = TileCollection.NumTilesTall();
            int ntw = TileCollection.NumTilesWide();
            ProgressMeter pm = new ProgressMeter(ProgressHandler, "Reading Tiles ", ntt * ntw);
            for (int row = 0; row < ntt; row++)
            {
                for (int col = 0; col < ntw; col++)
                {
                    int width = TileCollection.GetTileWidth(col);
                    int height = TileCollection.GetTileHeight(row);
                    InRamImageData id = new InRamImageData(width, height);

                    Bitmap image = new Bitmap(width, height, PixelFormat.Format32bppArgb);

                    byte[] red = new byte[width * height];
                    byte[] g = new byte[width * height];
                    byte[] b = new byte[width * height];

                    _red.ReadRaster(col * tw, row * th, width, height, red, width, height, 0, 0);
                    _green.ReadRaster(col * tw, row * th, width, height, g, width, height, 0, 0);
                    _blue.ReadRaster(col * tw, row * th, width, height, b, width, height, 0, 0);

                    BitmapData bData = image.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite,
                                                       PixelFormat.Format32bppArgb);
                    Stride = bData.Stride;
                    image.UnlockBits(bData);
                    byte[] vals = new byte[width * height * 4];
                    int stride = Stride;
                    const int bpp = 4;
                    for (int r = 0; r < height; r++)
                    {
                        for (int c = 0; c < width; c++)
                        {
                            vals[r * stride + c * bpp] = b[r * width + c];
                            vals[r * stride + c * bpp + 1] = g[r * width + c];
                            vals[r * stride + c * bpp + 2] = red[r * width + c];
                            vals[r * stride + c * bpp + 3] = 255;
                        }
                    }
                    id.Values = vals;
                    id.CopyValuesToBitmap();
                    TileCollection.Tiles[row, col] = id;
                    pm.CurrentValue = row * ntw + col;
                }
            }
            pm.Reset();
            SetTileBounds(Bounds.AffineCoefficients);
        }

19 Source : RenderAssistant.cs
with GNU General Public License v3.0
from deregtd

public void RenderFrame(int frameNum, bool filter)
        {
            int dataOffset, dataLength;
            byte[] sourceData = GetFrameData(frameNum, out dataOffset, out dataLength);

            float pixelPitch = GetPixelPitch();

            float topleftX = -pixelPitch * (size.Width / 2f) - CenterX + imWidth / 2f;
            float topleftY = -pixelPitch * (size.Height / 2f) - CenterY + imHeight / 2f;

            if (filter)
            {
                topleftX -= 0.5f;
                topleftY -= 0.5f;
            }

            BitmapData bdata = RenderedImage.LockBits(new Rectangle(Point.Empty, RenderedImage.Size), ImageLockMode.WriteOnly, PixelFormat.Format32bppPArgb);
            unsafe
            {
                fixed (byte* byteData = &sourceData[dataOffset])
                {
                    fixed (byte* p1 = palettes[0], p2 = palettes[1], p3 = palettes[2])
                    {
                        fixed (ushort* p16r = palettes16[0], p16g = palettes16[1], p16b = palettes16[2])
                        {
                            byte*[] pal8 = new byte*[3] { (byte*)p1, (byte*)p2, (byte*)p3 };
                            ushort*[] pal16 = new ushort*[3] { p16r, p16g, p16b };

                            short* shortData = (short*)byteData;

                            int frameOffset = imWidth * imHeight * bytes;

                            //BS vars to init for filtering later
                            float yf = 0, w1 = 0, w2 = 0, w3 = 0, w4 = 0;
                            ushort psrc10 = 0, psrc01 = 0, psrc11 = 0;
                            int pX1 = 0, pY1 = 0;

                            float yCoord = topleftY;
                            for (int y = 0; y < size.Height; y++, yCoord += pixelPitch)
                            {
                                byte* pBMPData = (byte*)bdata.Scan0 + y * bdata.Stride;

                                int pY = (int)yCoord;
                                if (filter)
                                {
                                    yf = yCoord - pY;
                                    pY1 = pY + 1;
                                    if (pY1 >= imHeight) pY1 = pY;
                                }

                                float xCoord = topleftX;
                                for (int x = 0; x < size.Width; x++, xCoord += pixelPitch)
                                {
                                    *((uint*)(pBMPData + 4 * x)) = 0xFF000000;

                                    int pX = (int)xCoord;

                                    if (pX < 0 || pX >= imWidth || pY < 0 || pY >= imHeight)
                                        continue;

                                    if (filter)
                                    {
                                        float xf = xCoord - pX;

                                        w1 = (1.0f - xf) * (1.0f - yf);
                                        w2 = (xf) * (1.0f - yf);
                                        w3 = (1.0f - xf) * (yf);
                                        w4 = (xf) * (yf);

                                        pX1 = pX + 1;
                                        if (pX1 >= imWidth) pX1 = pX;
                                    }

                                    //Check for buffer overruns using the worst case scenario
                                    if (filter)
                                    {
                                        //Lower right pixel for filter
                                        if (bytes * (pY1 * imWidth + pX1) >= dataLength)
                                            continue;
                                    }
                                    else
                                    {
                                        if (bytes * (pY * imWidth + pX) >= dataLength)
                                            continue;
                                    }

                                    if (bPalette)
                                    {
                                        //palette lookup. 1 byte -> 3 after lookup
                                        ushort psrc = (ushort) (((bytes == 2) ? (ushort)shortData[pY * imWidth + pX] : byteData[pY * imWidth + pX]) - paletteFirstEntry);
                                        if (psrc < 0) psrc = 0; else if (psrc >= paletteNumEntries) psrc = (ushort)(paletteNumEntries - 1);

                                        if (filter)
                                        {
                                            psrc10 = (ushort)(((bytes == 2) ? shortData[pY * imWidth + pX1] : byteData[pY * imWidth + pX1]) - paletteFirstEntry);
                                            if (psrc10 < 0) psrc10 = 0; else if (psrc10 >= paletteNumEntries) psrc10 = (ushort)(paletteNumEntries - 1);
                                            psrc01 = (ushort)(((bytes == 2) ? shortData[(pY1) * imWidth + pX] : byteData[(pY1) * imWidth + pX]) - paletteFirstEntry);
                                            if (psrc01 < 0) psrc01 = 0; else if (psrc01 >= paletteNumEntries) psrc01 = (ushort)(paletteNumEntries - 1);
                                            psrc11 = (ushort)(((bytes == 2) ? shortData[(pY1) * imWidth + pX1] : byteData[(pY1) * imWidth + pX1]) - paletteFirstEntry);
                                            if (psrc11 < 0) psrc11 = 0; else if (psrc11 >= paletteNumEntries) psrc11 = (ushort)(paletteNumEntries - 1);
                                        }

                                        for (int b = 0; b < 3; b++)
                                        {
                                            int src = palette16 ? pal16[b][psrc] : pal8[b][psrc];

                                            if (filter)
                                            {
                                                int src10 = palette16 ? pal16[b][psrc10] : pal8[b][psrc10];
                                                int src01 = palette16 ? pal16[b][psrc01] : pal8[b][psrc01];
                                                int src11 = palette16 ? pal16[b][psrc11] : pal8[b][psrc11];
                                                src = (int)((src * w1) + (src10 * w2) + (src01 * w3) + (src11 * w4));
                                            }

                                            if (bRescaling) src = (int)(src * adjM + adjB);
                                            src = (int)((src - Level) * (255f / Window) + 128);
                                            if (src < 0) src = 0; else if (src > 255) src = 255;
                                            if (bFlipMono) src = (255 - src);
                                            pBMPData[4 * x + (2 - b)] = (byte)src;
                                        }
                                    }
                                    else if (bRGB)
                                    {
                                        if (bPlanarOne)
                                        {
                                            //RRR GGG BBB
                                            for (int b = 0; b < 3; b++)
                                            {
                                                int src = byteData[frameOffset * b + pY * imWidth + pX];

                                                if (filter)
                                                {
                                                    int src10 = byteData[frameOffset * b + pY * imWidth + pX1];
                                                    int src01 = byteData[frameOffset * b + pY1 * imWidth + pX];
                                                    int src11 = byteData[frameOffset * b + pY1 * imWidth + pX1];
                                                    src = (int)((src * w1) + (src10 * w2) + (src01 * w3) + (src11 * w4));
                                                }

                                                if (bRescaling) src = (int)(src * adjM + adjB);
                                                src = (int)((src - Level) * (255f / Window) + 128);
                                                if (src < 0) src = 0; else if (src > 255) src = 255;
                                                if (bFlipMono) src = (255 - src);
                                                pBMPData[4 * x + (2 - b)] = (byte)src;
                                            }
                                        }
                                        else
                                        {
                                            //RGB RGB

                                            for (int b = 0; b < 3; b++)
                                            {
                                                int src = byteData[3 * (pY * imWidth + pX) + b];

                                                if (filter)
                                                {
                                                    int src10 = byteData[3 * (pY * imWidth + pX1) + b];
                                                    int src01 = byteData[3 * (pY1 * imWidth + pX) + b];
                                                    int src11 = byteData[3 * (pY1 * imWidth + pX1) + b];
                                                    src = (int)((src * w1) + (src10 * w2) + (src01 * w3) + (src11 * w4));
                                                }

                                                if (bRescaling) src = (int)(src * adjM + adjB);
                                                src = (int)((src - Level) * (255f / Window) + 128);
                                                if (src < 0) src = 0; else if (src > 255) src = 255;
                                                if (bFlipMono) src = (255 - src);
                                                pBMPData[4 * x + (2 - b)] = (byte)src;
                                            }
                                        }
                                    }
                                    else
                                    {
                                        //grayscale
                                        int src = (bytes == 2) ? (signedData ? shortData[pY * imWidth + pX] : (int) (ushort) shortData[pY * imWidth + pX]) : byteData[pY * imWidth + pX];

                                        if (filter)
                                        {
                                            int src10 = (bytes == 2) ? (signedData ? shortData[pY * imWidth + pX1] : (int)(ushort)shortData[pY * imWidth + pX1]) : byteData[pY * imWidth + pX1];
                                            int src01 = (bytes == 2) ? (signedData ? shortData[(pY1) * imWidth + pX] : (int)(ushort)shortData[(pY1) * imWidth + pX]) : byteData[(pY1) * imWidth + pX];
                                            int src11 = (bytes == 2) ? (signedData ? shortData[(pY1) * imWidth + pX1] : (int)(ushort)shortData[(pY1) * imWidth + pX1]) : byteData[(pY1) * imWidth + pX1];
                                            src = (int)((src * w1) + (src10 * w2) + (src01 * w3) + (src11 * w4));
                                        }

                                        if (bRescaling) src = (int)(src * adjM + adjB);
                                        src = (int)((src - Level) * (255f / Window) + 128);
                                        if (src < 0) src = 0; else if (src > 255) src = 255;
                                        if (bFlipMono) src = (255 - src);

                                        pBMPData[4 * x] = (byte)src;
                                        pBMPData[4 * x + 1] = (byte)src;
                                        pBMPData[4 * x + 2] = (byte)src;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            RenderedImage.UnlockBits(bdata);
        }

19 Source : Sprite.cs
with MIT License
from DevChrome

private void LoadFromBitmap(Bitmap bmp)
		{
			Width = bmp.Width;
			Height = bmp.Height;

			colorData = new Pixel[Width * Height];

			unsafe
			{
				Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
				BitmapData bmpData = bmp.LockBits(rect, ImageLockMode.ReadOnly, bmp.PixelFormat);

				byte* scan0 = (byte*)bmpData.Scan0;

				int depth = Image.GetPixelFormatSize(bmp.PixelFormat);

				int length = Width * Height * depth / 8;
				
				for (int x = 0; x < Width; x++)
				{
					for (int y = 0; y < Height; y++)
					{
						int i = ((y * Width) + x) * depth / 8;

						Color c = Color.Empty;

						switch (depth)
						{
							case 32:
								{
									byte b = scan0[i];
									byte g = scan0[i + 1];
									byte r = scan0[i + 2];
									byte a = scan0[i + 3];
									c = Color.FromArgb(a, r, g, b);
									break;
								}

							case 24:
								{
									byte b = scan0[i];
									byte g = scan0[i + 1];
									byte r = scan0[i + 2];
									c = Color.FromArgb(r, g, b);
									break;
								}

							case 8:
								{
									byte b = scan0[i];
									c = Color.FromArgb(b, b, b);
									break;
								}
						}

						this[x, y] = new Pixel(c.R, c.G, c.B, c.A);
					}
				}

				bmp.UnlockBits(bmpData);
			}
		}

19 Source : Sprite.cs
with MIT License
from DevChrome

public static void Save(Sprite spr, string path)
		{
			unsafe
			{
				using (Bitmap bmp = new Bitmap(spr.Width, spr.Height))
				{
					Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
					BitmapData bmpData = bmp.LockBits(rect, ImageLockMode.WriteOnly, bmp.PixelFormat);

					byte* scan0 = (byte*)bmpData.Scan0;

					int depth = Image.GetPixelFormatSize(bmp.PixelFormat);

					int length = spr.Width * spr.Height * depth / 8;

					for (int x = 0; x < spr.Width; x++)
					{
						for (int y = 0; y < spr.Height; y++)
						{
							Pixel p = spr[x, y];

							int i = ((y * spr.Width) + x) * depth / 8;

							scan0[i] = p.B;
							scan0[i + 1] = p.G;
							scan0[i + 2] = p.R;
							scan0[i + 3] = p.A;
						}
					}

					bmp.UnlockBits(bmpData);

					bmp.Save(path);
				}
			}
		}

19 Source : WzCanvas.cs
with MIT License
from diamondo25

public override void Read(ArchiveReader reader)
        {
            // dont care
            if (reader.ReadByte() != 0) throw new Exception("Expected 0 is not zero");

            if (reader.ReadByte() != 0)
            {
                // Initialize prop
                base.Read(reader);

                if (Get("origin") is WzVector2D origin)
                {
                    CenterX = origin.X;
                    CenterY = origin.Y;
                }
            }
            else
            {
                base._objects = new Dictionary<string, object>();
            }

            Width = reader.ReadCompressedInt();
            if (Width >= 0x10000)
                throw new Exception($"Invalid Width: {Width}");

            Height = reader.ReadCompressedInt();
            if (Height >= 0x10000)
                throw new Exception($"Invalid Height: {Height}");

            PixFormat = (WzPixFormat)reader.ReadCompressedInt();

            if (!(
                PixFormat == WzPixFormat.A4R4G4B4 ||
                PixFormat == WzPixFormat.A8R8G8B8 ||
                PixFormat == WzPixFormat.R5G6B5 ||
                PixFormat == WzPixFormat.DXT3 ||
                PixFormat == WzPixFormat.DXT5
            ))
            {
                throw new Exception($"Invalid PixFormat: {PixFormat:D}");
            }

            MagLevel = reader.ReadCompressedInt();
            if (MagLevel < 0) throw new Exception("MagLevel is < 0");

            // Zeroes
            for (var i = 0; i < 4; i++)
                if (reader.ReadCompressedInt() != 0) throw new Exception("Expected 0 is not zero");


            var dataSize = reader.ReadInt32();

            if (reader.ReadByte() != 0) throw new Exception("Expected 0 is not zero");

            Create(Width, Height, MagLevel, (WzPixFormat)0);

            using (var outputStream = new MemoryStream(ExpectedDataSize))
            using (var inputStream = new MemoryStream(dataSize))
            {
                var isPlainZlibStream = reader.ReadByte() == 0x78;
                reader.BaseStream.Position -= 1;

                var blob = new byte[Math.Min(0x20000, dataSize)];

                if (reader.HasCurrentCrypto && !isPlainZlibStream)
                {
                    // Need to skip 1
                    for (var i = 1; i < dataSize;)
                    {
                        var blobSize = reader.ReadInt32();
                        i += 4;
                        Array.Resize(ref blob, blobSize);
                        reader.Read(blob, 0, blobSize);

                        reader.TryDecryptImage(blob);
                        inputStream.Write(blob, 0, blobSize);
                        i += blobSize;
                    }
                }
                else
                {
                    for (var i = 0; i < dataSize;)
                    {
                        var blobSize = Math.Min(blob.Length, dataSize - i);
                        reader.Read(blob, 0, blobSize);
                        inputStream.Write(blob, 0, blobSize);
                        i += blobSize;
                    }
                }


                inputStream.Position = 2;
                using (var deflate = new DeflateStream(inputStream, CompressionMode.Decompress))
                {
                    deflate.CopyTo(outputStream);
                }


                var uncompressedSize = outputStream.Length;
                outputStream.Position = 0;

                Bitmap output = null;

                byte[] arr;
                switch (PixFormat)
                {
                    case WzPixFormat.A4R4G4B4:
                        arr = ARGB16toARGB32(outputStream, uncompressedSize);
                        break;
                    case WzPixFormat.DXT5:
                    case WzPixFormat.DXT3:
                        arr = DXTDecoder.Decode(
                            TileWidth,
                            TileHeight,
                            outputStream.ToArray(),
                            PixFormat == WzPixFormat.DXT3 ?
                            DXTDecoder.CompressionType.DXT3 :
                            DXTDecoder.CompressionType.DXT5
                        );
                        break;
                    default:
                        arr = outputStream.ToArray();
                        break;
                }


                PixelFormat format;

                switch (PixFormat)
                {
                    case WzPixFormat.R5G6B5:
                        format = PixelFormat.Format16bppRgb565;
                        break;
                    case WzPixFormat.A4R4G4B4:
                    case WzPixFormat.A8R8G8B8:
                    default:
                        format = PixelFormat.Format32bppArgb;
                        break;
                }

                output = new Bitmap(TileWidth, TileHeight, format);
                var rect = new Rectangle(0, 0, output.Width, output.Height);
                var bmpData = output.LockBits(rect, ImageLockMode.ReadWrite, output.PixelFormat);

                var arrRowLength = rect.Width * (Image.GetPixelFormatSize(output.PixelFormat) / 8);
                var ptr = bmpData.Scan0;
                for (var i = 0; i < rect.Height; i++)
                {
                    Marshal.Copy(arr, i * arrRowLength, ptr, arrRowLength);
                    ptr += bmpData.Stride;
                }

                output.UnlockBits(bmpData);

                SetCanvas(0, 0, new WzRawCanvas
                {
                    Bitmap = output,
                    MagLevel = MagLevel,
                });

            }
        }

19 Source : WzRawCanvas.cs
with MIT License
from diamondo25

public void UnlockAddress(in BitmapData address)
        {
            Bitmap.UnlockBits(address);
        }

19 Source : ImageExtensions.cs
with MIT License
from DingpingZhang

public static Bitmap ToBitmap(this BitmapSource source)
        {
            var bitmap = new Bitmap(
                source.PixelWidth,
                source.PixelHeight,
                PixelFormat.Format32bppPArgb);

            var bitmapData = bitmap.LockBits(
                new Rectangle(Point.Empty, bitmap.Size),
                ImageLockMode.WriteOnly,
                PixelFormat.Format32bppPArgb);

            source.CopyPixels(
                Int32Rect.Empty,
                bitmapData.Scan0,
                bitmapData.Height * bitmapData.Stride,
                bitmapData.Stride);

            bitmap.UnlockBits(bitmapData);

            return bitmap;
        }

19 Source : Form1.cs
with GNU General Public License v3.0
from DomDom3333

private void bgW_ImageConverter_DoWork(object sender, DoWorkEventArgs e) // compreses the image to png. Is background worker to have smoother operation while work is done
        {
            byte[] integritycheck = grabFirstBytes(10, tb_PathToCompress.Text);
            if (checkFileLegitimacy(ref integritycheck))
            {
                DialogResult result = MessageBox.Show("This file is made by this application. The resulting file will not be any smaller. Continiue?","Continiue?",MessageBoxButtons.YesNo,MessageBoxIcon.Question);
                if(result == DialogResult.No)
                {
                    return; //if user answers no, function ends.
                }
            }
            BackgroundWorker worker = sender as BackgroundWorker;
            worker.ReportProgress(0);
            byte[] outputBytes = readFile(tb_PathToCompress.Text);
            //DEBUG CODE listFirstEntries(ref outputBytes, 20);
            worker.ReportProgress(15);
            int size = calculateResolution(outputBytes.Length);
            worker.ReportProgress(20);
            Bitmap bmp = new Bitmap(size, size+1);
            BitmapData bitmapData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadWrite, bmp.PixelFormat);
            worker.ReportProgress(22);
            IntPtr ptrFirstPixel = bitmapData.Scan0;
            worker.ReportProgress(23);
            Marshal.Copy(outputBytes, 0, ptrFirstPixel, outputBytes.Length);
            bmp.UnlockBits(bitmapData);
            worker.ReportProgress(50);
            bmp.Save(tb_PathToOutput.Text + "//" + tb_FileName.Text + ".png"); //this sucker takes FOREVER. Faster way would definetly be helpfull. WriteAllBytes might be an option
            worker.ReportProgress(95);
            bmp.Dispose();
            GC.Collect();
            worker.ReportProgress(100);
        }

19 Source : RgbLedMatrix.cs
with MIT License
from dotnet

public unsafe void DrawBitmap(int x, int y, Bitmap bitmap, bool backBuffer = false)
        {
            if (y >= Height || x >= Width || x + bitmap.Width <= 0 || y + bitmap.Height <= 0)
            {
                return;
            }

            byte[] buffer = backBuffer ? _colorsBackBuffer : _colorsBuffer;

            Rectangle fullImageRectangle = new Rectangle(0, 0, bitmap.Width, bitmap.Height);
            Rectangle partialBitmap = new Rectangle(x, y, bitmap.Width, bitmap.Height);
            partialBitmap.Intersect(new Rectangle(0, 0, Width, Height));

            BitmapData bitmapData =
                bitmap.LockBits(fullImageRectangle, ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);

            try
            {
                int pos = 3 * ((y < 0 ? Math.Abs(y) * bitmap.Width : 0) + (x < 0 ? Math.Abs(x) : 0));
                int stride = (bitmapData.Stride - 3 * bitmap.Width) + 3 * (bitmap.Width - partialBitmap.Width);

                Span<byte> span = new Span<byte>((void*)bitmapData.Scan0,
                    fullImageRectangle.Width * fullImageRectangle.Height * 3);

                for (int j = 0; j < partialBitmap.Height; j++)
                {
                    for (int i = 0; i < partialBitmap.Width; i++)
                    {
                        SetPixel(partialBitmap.X + i, partialBitmap.Y + j, span[pos + 2], span[pos + 1], span[pos],
                            buffer);
                        pos += 3;
                    }

                    pos += stride;
                }
            }
            finally
            {
                bitmap.UnlockBits(bitmapData);
            }
        }

19 Source : Ili9341Imaging.cs
with MIT License
from dotnet

public Span<byte> GetBitmapPixelData(Bitmap bm, Rectangle sourceRect)
        {
            BitmapData bmd;
            byte[] bitmapData; // array that takes the raw bytes of the bitmap
            byte[] outputBuffer; // array used to form the data to be written out to the SPI interface

            if (bm is null)
            {
                throw new ArgumentNullException(nameof(bm));
            }

            if (bm.PixelFormat != PixelFormat.Format32bppArgb)
            {
                throw new ArgumentException(nameof(bm), $"Pixel format {bm.PixelFormat.ToString()} not supported.");
            }

            // allocate the working arrays.
            bitmapData = new byte[sourceRect.Width * sourceRect.Height * 4];
            outputBuffer = new byte[sourceRect.Width * sourceRect.Height * 2];

            // get the raw pixel data for the bitmap
            bmd = bm.LockBits(sourceRect, ImageLockMode.ReadOnly, bm.PixelFormat);

            Marshal.Copy(bmd.Scan0, bitmapData, 0, bitmapData.Length);

            bm.UnlockBits(bmd);

            // iterate over the source bitmap converting each pixle in the raw data
            // to a format suitablle for sending to the display
            for (int i = 0; i < bitmapData.Length; i += 4)
            {
                    (outputBuffer[i / 4 * 2 + 0], outputBuffer[i / 4 * 2 + 1]) = Color565(Color.FromArgb(bitmapData[i + 2], bitmapData[i + 1], bitmapData[i + 0]));
            }

            return (outputBuffer);
        }

19 Source : Ssd1351Imaging.cs
with MIT License
from dotnet

public Span<byte> GetBitmapPixelData(Bitmap bm, Rectangle sourceRect)
        {
            BitmapData bmd;
            byte[] bitmapData; // array that takes the raw bytes of the bitmap
            byte[] outputBuffer; // array used to form the data to be written out to the SPI interface

            if (bm is null)
            {
                throw new ArgumentNullException(nameof(bm));
            }

            if (bm.PixelFormat != PixelFormat.Format32bppArgb)
            {
                throw new ArgumentException(nameof(bm), $"Pixel format {bm.PixelFormat.ToString()} not supported.");
            }

            // allocate the working arrays.
            bitmapData = new byte[sourceRect.Width * sourceRect.Height * 4];
            outputBuffer = new byte[sourceRect.Width * sourceRect.Height * (_colorDepth == ColorDepth.ColourDepth65K ? 2 : 3)];

            // get the raw pixel data for the bitmap
            bmd = bm.LockBits(sourceRect, ImageLockMode.ReadOnly, bm.PixelFormat);

            Marshal.Copy(bmd.Scan0, bitmapData, 0, bitmapData.Length);

            bm.UnlockBits(bmd);

            // iterate over the source bitmap converting each pixle in the raw data
            // to a format suitablle for sending to the display
            for (int i = 0; i < bitmapData.Length; i += 4)
            {
                if (_colorDepth == ColorDepth.ColourDepth65K)
                {
                    (outputBuffer[i / 4 * 2 + 0], outputBuffer[i / 4 * 2 + 1]) = Color565(Color.FromArgb(bitmapData[i + 2], bitmapData[i + 1], bitmapData[i + 0]));
                }
                else
                {
                    outputBuffer[i / 4 * 3 + 0] = (byte)(bitmapData[i + (_colorSequence == ColorSequence.BGR ? 0 : 2)] >> 2);
                    outputBuffer[i / 4 * 3 + 1] = (byte)(bitmapData[i + 1] >> 2);
                    outputBuffer[i / 4 * 3 + 2] = (byte)(bitmapData[i + (_colorSequence == ColorSequence.BGR ? 2 : 0)] >> 2);
                }
            }

            return (outputBuffer);
        }

19 Source : RgbLedMatrix.cs
with MIT License
from dotnet

public unsafe void DrawBitmap(int x, int y, Bitmap bitmap, byte red, byte green, byte blue, byte repRed,
            byte repGreen, byte repBlue, bool backBuffer = false)
        {
            if (y >= Height || x >= Width || x + bitmap.Width <= 0 || y + bitmap.Height <= 0)
            {
                return;
            }

            byte[] buffer = backBuffer ? _colorsBackBuffer : _colorsBuffer;

            int bitmapX = x < 0 ? -x : 0;
            int bitmapY = y < 0 ? -y : 0;
            int bitmapWidth = Math.Min(bitmap.Width - bitmapX, x < 0 ? Width : Width - x);
            int bitmapHeight = Math.Min(bitmap.Height - bitmapY, y < 0 ? Height : Height - y);
            int coorX = Math.Max(0, x);
            int coorY = Math.Max(0, y);

            BitmapData bitmapData = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height),
                ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);

            try
            {
                int pos = 3 * (bitmapY * bitmap.Width + bitmapX);
                int stride = (bitmapData.Stride - 3 * bitmap.Width) + 3 * (bitmap.Width - bitmapWidth);

                Span<byte> span = new Span<byte>((void*)bitmapData.Scan0, bitmapData.Stride * bitmap.Height);

                for (int j = 0; j < bitmapHeight; j++)
                {
                    for (int i = 0; i < bitmapWidth; i++)
                    {
                        if (red == span[pos + 2] && green == span[pos + 1] && blue == span[pos])
                        {
                            SetPixel(coorX + i, coorY + j, repRed, repGreen, repBlue, buffer);
                        }
                        else
                        {
                            SetPixel(coorX + i, coorY + j, span[pos + 2], span[pos + 1], span[pos], buffer);
                        }

                        pos += 3;
                    }

                    pos += stride;
                }
            }
            finally
            {
                bitmap.UnlockBits(bitmapData);
            }
        }

19 Source : ImagePixelExtractor.cs
with MIT License
from dotnet

private ValueGetter<VBuffer<TValue>> GetGetterCore<TValue>(DataViewRow input, int iinfo, out Action disposer)
                where TValue : struct
            {
                var type = _types[iinfo];
                var dims = type.Dimensions;
                Contracts.replacedert(dims.Length == 3);

                var ex = _parent._columns[iinfo];

                int planes = ex.InterleavePixelColors ? dims[2] : dims[0];
                int height = ex.InterleavePixelColors ? dims[0] : dims[1];
                int width = ex.InterleavePixelColors ? dims[1] : dims[2];

                int size = type.Size;
                Contracts.replacedert(size > 0);
                Contracts.replacedert(size == planes * height * width);
                int cpix = height * width;

                var getSrc = input.GetGetter<Bitmap>(input.Schema[ColMapNewToOld[iinfo]]);
                var src = default(Bitmap);

                disposer =
                    () =>
                    {
                        if (src != null)
                        {
                            src.Dispose();
                            src = null;
                        }
                    };

                return
                    (ref VBuffer<TValue> dst) =>
                    {
                        getSrc(ref src);
                        Contracts.replacedertValueOrNull(src);

                        if (src == null)
                        {
                            VBufferUtils.Resize(ref dst, size, 0);
                            return;
                        }

                        Host.Check(src.Height == height && src.Width == width);

                        if (src.PixelFormat != PixelFormat.Format32bppArgb && src.PixelFormat != PixelFormat.Format24bppRgb)
                        {
                            var clone = src.Clone(new Rectangle(0, 0, src.Width, src.Height), PixelFormat.Format32bppArgb);
                            clone.Tag = src.Tag;
                            src.Dispose();
                            src = clone;
                            using (var ch = Host.Start(nameof(ImagePixelExtractingTransformer)))
                            {
                                ch.Warning($"Encountered image {src.Tag} of unsupported pixel format {src.PixelFormat} but converting it to {nameof(PixelFormat.Format32bppArgb)}.");
                            }
                        }

                        var editor = VBufferEditor.Create(ref dst, size);
                        var values = editor.Values;

                        float offset = ex.OffsetImage;
                        float scale = ex.ScaleImage;
                        Contracts.replacedert(scale != 0);

                        // REVIEW: split the getter into 2 specialized getters, one for float case and one for byte case.
                        Span<float> vf = typeof(TValue) == typeof(float) ? MemoryMarshal.Cast<TValue, float>(editor.Values) : default;
                        Span<byte> vb = typeof(TValue) == typeof(byte) ? MemoryMarshal.Cast<TValue, byte>(editor.Values) : default;
                        Contracts.replacedert(!vf.IsEmpty || !vb.IsEmpty);
                        bool needScale = offset != 0 || scale != 1;
                        Contracts.replacedert(!needScale || !vf.IsEmpty);

                        ImagePixelExtractingEstimator.GetOrder(ex.OrderOfExtraction, ex.ColorsToExtract, out int a, out int r, out int b, out int g);

                        BitmapData bmpData = null;
                        try
                        {
                            bmpData = src.LockBits(new Rectangle(0, 0, src.Width, src.Height), ImageLockMode.ReadOnly, src.PixelFormat);
                            int h = height;
                            int w = width;
                            byte[] row = new byte[bmpData.Stride];
                            int pixelSize = System.Drawing.Image.GetPixelFormatSize(src.PixelFormat) / 8;
                            Func<int, byte> alpha = pixelSize > 3 ? new Func<int, byte>(ix => row[ix + 3]) : new Func<int, byte>(ix => 255);

                            if (ex.InterleavePixelColors)
                            {
                                int idst = 0;
                                for (int y = 0; y < h; ++y)
                                {
                                    Marshal.Copy(bmpData.Scan0 + bmpData.Stride * y, row, 0, bmpData.Stride);
                                    for (int x = 0; x < w; x++)
                                    {
                                        var ix = x * pixelSize;
                                        if (!vb.IsEmpty)
                                        {
                                            if (a != -1) { vb[idst + a] = alpha(ix); }
                                            if (r != -1) { vb[idst + r] = row[ix + 2]; }
                                            if (g != -1) { vb[idst + g] = row[ix + 1]; }
                                            if (b != -1) { vb[idst + b] = row[ix + 0]; }
                                        }
                                        else if (!needScale)
                                        {
                                            if (a != -1) { vf[idst + a] = alpha(ix); }
                                            if (r != -1) { vf[idst + r] = row[ix + 2]; }
                                            if (g != -1) { vf[idst + g] = row[ix + 1]; }
                                            if (b != -1) { vf[idst + b] = row[ix + 0]; }
                                        }
                                        else
                                        {

                                            if (a != -1) { vf[idst + a] = (alpha(ix) - offset) * scale; }
                                            if (r != -1) { vf[idst + r] = (row[ix + 2] - offset) * scale; }
                                            if (g != -1) { vf[idst + g] = (row[ix + 1] - offset) * scale; }
                                            if (b != -1) { vf[idst + b] = (row[ix + 0] - offset) * scale; }
                                        }
                                        idst += ex.Planes;
                                    }
                                }
                                Contracts.replacedert(idst == size);
                            }
                            else
                            {
                                int idstMin = 0;
                                for (int y = 0; y < h; ++y)
                                {
                                    Marshal.Copy(bmpData.Scan0 + bmpData.Stride * y, row, 0, bmpData.Stride);
                                    int idst = idstMin + y * w;
                                    for (int x = 0; x < w; x++, idst++)
                                    {
                                        var ix = x * pixelSize;
                                        if (!vb.IsEmpty)
                                        {
                                            if (a != -1) vb[idst + cpix * a] = alpha(ix);
                                            if (r != -1) vb[idst + cpix * r] = row[ix + 2];
                                            if (g != -1) vb[idst + cpix * g] = row[ix + 1];
                                            if (b != -1) vb[idst + cpix * b] = row[ix + 0];
                                        }
                                        else if (!needScale)
                                        {
                                            if (a != -1) vf[idst + cpix * a] = alpha(ix);
                                            if (r != -1) vf[idst + cpix * r] = row[ix + 2];
                                            if (g != -1) vf[idst + cpix * g] = row[ix + 1];
                                            if (b != -1) vf[idst + cpix * b] = row[ix + 0];
                                        }
                                        else
                                        {
                                            if (a != -1) vf[idst + cpix * a] = (alpha(ix) - offset) * scale;
                                            if (r != -1) vf[idst + cpix * r] = (row[ix + 2] - offset) * scale;
                                            if (g != -1) vf[idst + cpix * g] = (row[ix + 1] - offset) * scale;
                                            if (b != -1) vf[idst + cpix * b] = (row[ix + 0] - offset) * scale;
                                        }
                                    }
                                }
                            }
                        }
                        finally
                        {
                            if (bmpData != null)
                                src.UnlockBits(bmpData);
                        }

                        dst = editor.Commit();
                    };
            }

19 Source : VectorToImageTransform.cs
with MIT License
from dotnet

private ValueGetter<Bitmap> GetterFromType<TValue>(PrimitiveDataViewType srcType, DataViewRow input, int iinfo,
                VectorToImageConvertingEstimator.ColumnOptions ex, bool needScale) where TValue : IConvertible
            {
                Contracts.replacedert(typeof(TValue) == srcType.RawType);
                var getSrc = RowCursorUtils.GetVecGetterAs<TValue>(srcType, input, ColMapNewToOld[iinfo]);
                var src = default(VBuffer<TValue>);
                int width = ex.ImageWidth;
                int height = ex.ImageHeight;
                float offset = ex.OffsetImage;
                float scale = ex.ScaleImage;

                return
                    (ref Bitmap dst) =>
                    {
                        getSrc(ref src);
                        if (src.GetValues().Length == 0)
                        {
                            dst = null;
                            return;
                        }
                        VBuffer<TValue> dense = default;
                        src.CopyToDense(ref dense);
                        var values = dense.GetValues();
                        dst = new Bitmap(width, height);
                        dst.SetResolution(width, height);
                        int cpix = height * width;
                        int position = 0;
                        ImagePixelExtractingEstimator.GetOrder(ex.Order, ex.Colors, out int a, out int r, out int b, out int g);

                        BitmapData bmpData = null;
                        try
                        {
                            bmpData = dst.LockBits(new Rectangle(0, 0, dst.Width, dst.Height), ImageLockMode.WriteOnly, dst.PixelFormat);
                            for (int y = 0; y < height; ++y)
                            {
                                byte[] row = new byte[bmpData.Stride];
                                int ix = 0;
                                for (int x = 0; x < width; x++)
                                {
                                    float red = ex.DefaultRed;
                                    float green = ex.DefaultGreen;
                                    float blue = ex.DefaultBlue;
                                    float alpha = ex.DefaultAlpha;
                                    if (ex.InterleavedColors)
                                    {
                                        if (ex.Alpha)
                                            alpha = Convert.ToSingle(values[position + a]);
                                        if (ex.Red)
                                            red = Convert.ToSingle(values[position + r]);
                                        if (ex.Green)
                                            green = Convert.ToSingle(values[position + g]);
                                        if (ex.Blue)
                                            blue = Convert.ToSingle(values[position + b]);
                                        position += ex.Planes;
                                    }
                                    else
                                    {
                                        position = y * width + x;
                                        if (ex.Alpha) alpha = Convert.ToSingle(values[position + cpix * a]);
                                        if (ex.Red) red = Convert.ToSingle(values[position + cpix * r]);
                                        if (ex.Green) green = Convert.ToSingle(values[position + cpix * g]);
                                        if (ex.Blue) blue = Convert.ToSingle(values[position + cpix * b]);
                                    }
                                    if (!needScale)
                                    {
                                        row[ix++] = (byte)blue;
                                        row[ix++] = (byte)green;
                                        row[ix++] = (byte)red;
                                        row[ix++] = (byte)alpha;
                                    }
                                    else
                                    {
                                        row[ix++] = (byte)Math.Round(blue * scale - offset);
                                        row[ix++] = (byte)Math.Round(green * scale - offset);
                                        row[ix++] = (byte)Math.Round(red * scale - offset);
                                        row[ix++] = (byte)(ex.Alpha ? Math.Round(alpha * scale - offset) : 0);
                                    }
                                }
                                Marshal.Copy(row, 0, bmpData.Scan0 + y * bmpData.Stride, bmpData.Stride);
                            }
                            dst.Tag = nameof(VectorToImageConvertingTransformer);
                        }
                        finally
                        {
                            if (bmpData != null)
                                dst.UnlockBits(bmpData);
                        }
                    };
            }

19 Source : ImageList.cs
with MIT License
from dotnet

private Bitmap GetBitmap(int index)
        {
            if (index < 0 || index >= Images.Count)
            {
                throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index));
            }

            Bitmap result = null;

            // if the imagelist is 32bpp, if the image slot at index
            // has valid alpha information (not all zero... which is cause by windows just painting RGB values
            // and not touching the alpha byte for images < 32bpp painted to a 32bpp imagelist)
            // we're not using the mask. That means that
            // we can just get the whole image strip, cut out the piece that we want
            // and return that, that way we don't flatten the alpha by painting the value with the alpha... (ie using the alpha)

            if (ColorDepth == ColorDepth.Depth32Bit)
            {
                var imageInfo = new ComCtl32.IMAGEINFO();
                if (ComCtl32.ImageList.GetImageInfo(new HandleRef(this, Handle), index, ref imageInfo).IsTrue())
                {
                    Bitmap tmpBitmap = null;
                    BitmapData bmpData = null;
                    BitmapData targetData = null;
                    try
                    {
                        tmpBitmap = Bitmap.FromHbitmap((IntPtr)imageInfo.hbmImage);

                        bmpData = tmpBitmap.LockBits(new Rectangle(imageInfo.rcImage.left, imageInfo.rcImage.top, imageInfo.rcImage.right - imageInfo.rcImage.left, imageInfo.rcImage.bottom - imageInfo.rcImage.top), ImageLockMode.ReadOnly, tmpBitmap.PixelFormat);

                        int offset = bmpData.Stride * _imageSize.Height * index;
                        // we need do the following if the image has alpha because otherwise the image is fully transparent even though it has data
                        if (BitmapHasAlpha(bmpData))
                        {
                            result = new Bitmap(_imageSize.Width, _imageSize.Height, PixelFormat.Format32bppArgb);
                            targetData = result.LockBits(new Rectangle(0, 0, _imageSize.Width, _imageSize.Height), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb);
                            CopyBitmapData(bmpData, targetData);
                        }
                    }
                    finally
                    {
                        if (tmpBitmap is not null)
                        {
                            if (bmpData is not null)
                            {
                                tmpBitmap.UnlockBits(bmpData);
                            }

                            tmpBitmap.Dispose();
                        }

                        if (result is not null && targetData is not null)
                        {
                            result.UnlockBits(targetData);
                        }
                    }
                }
            }

            if (result is null)
            {
                // Paint with the mask but no alpha.
                result = new Bitmap(_imageSize.Width, _imageSize.Height);

                Graphics graphics = Graphics.FromImage(result);
                try
                {
                    IntPtr dc = graphics.GetHdc();
                    try
                    {
                        ComCtl32.ImageList.DrawEx(
                            this,
                            index,
                            new HandleRef(graphics, dc),
                            0,
                            0,
                            _imageSize.Width,
                            _imageSize.Height,
                            ComCtl32.CLR.NONE,
                            ComCtl32.CLR.NONE,
                            ComCtl32.ILD.TRANSPARENT);
                    }
                    finally
                    {
                        graphics.ReleaseHdcInternal(dc);
                    }
                }
                finally
                {
                    graphics.Dispose();
                }
            }

            // See Icon for description of fakeTransparencyColor
            if (result.RawFormat.Guid != ImageFormat.Icon.Guid)
            {
                result.MakeTransparent(s_fakeTransparencyColor);
            }

            return result;
        }

19 Source : DesignerUtils.cs
with MIT License
from dotnet

private static unsafe void SetImageAlpha(Bitmap b, double opacity)
        {
            if (opacity == 1.0)
            {
                return;
            }

            byte[] alphaValues = new byte[256];
            // precompute all the possible alpha values into an array so we don't do multiplications in the loop
            for (int i = 0; i < alphaValues.Length; i++)
            {
                alphaValues[i] = (byte)(i * opacity);
            }

            // lock the data in ARGB format.
            //
            BitmapData data = b.LockBits(new Rectangle(0, 0, b.Width, b.Height), ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);
            try
            {
                // compute the number of pixels that we're modifying.
                int pixels = data.Height * data.Width;
                int* pPixels = (int*)data.Scan0;

                // have the compiler figure out where to stop for us
                // by doing the pointer math
                byte* maxAddr = (byte*)(pPixels + pixels);

                // now run through the pixels only modifying the A byte
                for (byte* addr = (byte*)(pPixels) + 3; addr < maxAddr; addr += 4)
                {
                    // the new value is just an index into our precomputed value array from above.
                    *addr = alphaValues[*addr];
                }
            }
            finally
            {
                // now, apply the data back to the bitmap.
                b.UnlockBits(data);
            }
        }

See More Examples