When copying pixel color values via Marshal.Copy, an image with spaces is obtained

77 Views Asked by At

enter image description here

When trying to copy data from one Bitmap to another, for some reason the image looks torn.

This is the code I copied from microsoft documentation. And it should work, but it doesn't.

public void DrawTextures()
        {
            Bitmap bmp = new("D:\\Photo.jpg");
            Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
            System.Drawing.Imaging.BitmapData bmpData =
                bmp.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite,
                bmp.PixelFormat)
            IntPtr ptr = bmpData.Scan0;
            int bytes = Math.Abs(bmpData.Stride) * bmp.Height;
            byte[] rgbValues = new byte[bytes];
            System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes);
            System.Runtime.InteropServices.Marshal.Copy(rgbValues, 0, ptr, bytes);
            bmp.UnlockBits(bmpData);
            PictureBox pictureBox = new()
            {
                BorderStyle = BorderStyle.FixedSingle,
                BackgroundImageLayout = ImageLayout.Stretch,
                Image = bmp,
                Width = 2048,
                Height = 2048
            };
            mainFlowPanel.Controls.Add(pictureBox);
        }

Update: I solved the problem with this code but only for .jpg 24 bit

0

There are 0 best solutions below