Porting system.drawing to imagesharp #2867
-
Hi, I would like to replace System.Drawing with ImageSharp. private static byte[] CreatePreviewBytesFromImageData(int width, int height, byte[] imageData)
{
int Format = 8 | (24 << 8);
int bitsPerPixel = ((int)Format & 0xff00) >> 8;
int bytesPerPixel = (bitsPerPixel + 7) / 8;
int stride = 4 * ((width * bytesPerPixel + 3) / 4);
Bitmap bitmap = new Bitmap(width, height, PixelFormat.Format24bppRgb);
BitmapData bitmapData = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb);
IntPtr scan0 = bitmapData.Scan0;
int strideWidth = Math.Abs(stride);
int numSkipBytes = strideWidth - width * 3;
byte[] bitmapPixelData = new byte[strideWidth * height];
int writtenBytes = 0;
int readBytes = 0;
for (int h = 0; h < height; h++)
{
for (int w = 0; w < width; w++)
{
// GDI+ bitmap raw pixel data is in BGR format, red & blue values need to be flipped around for each pixel.
bitmapPixelData[writtenBytes] = imageData[readBytes + 2];
bitmapPixelData[writtenBytes + 1] = imageData[readBytes + 1];
bitmapPixelData[writtenBytes + 2] = imageData[readBytes];
writtenBytes += 3;
readBytes += 3;
}
// GDI+ bitmap stride / scan width has to be a multiple of 4, so the end of each stride / scanline can contain extra bytes
// in the bitmap raw pixel data that are not present in the image data and should be skipped when copying.
writtenBytes += numSkipBytes;
}
SixLabors.ImageSharp.Image bitmap2 =
SixLabors.ImageSharp.Image.LoadPixelData<SixLabors.ImageSharp.PixelFormats.Bgr24>(bitmapPixelData,
width, height);
bitmap2.Save("abc.bmp");
Marshal.Copy(bitmapPixelData, 0, scan0, bitmapPixelData.Length);
bitmap.UnlockBits(bitmapData);
bitmap.Save("def.bmp");
return bitmapPixelData;
} What did I do wrong with the ImageSharp-Code? regards |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
The problem lies in how ImageSharp handles stride and padding compared to System.Drawing. Your code assumes GDI+ (System.Drawing) behavior, which enforces that each row of pixel data is aligned to a 4-byte boundary. However, ImageSharp does not require such padding for rows, and the pixel data should be tightly packed with no extra padding bytes between rows. |
Beta Was this translation helpful? Give feedback.
-
Thank you so much.
This code is now working perfect. regards |
Beta Was this translation helpful? Give feedback.
The problem lies in how ImageSharp handles stride and padding compared to System.Drawing. Your code assumes GDI+ (System.Drawing) behavior, which enforces that each row of pixel data is aligned to a 4-byte boundary. However, ImageSharp does not require such padding for rows, and the pixel data should be tightly packed with no extra padding bytes between rows.