Skip to content
This repository has been archived by the owner on Nov 19, 2020. It is now read-only.

UnmanagedImage stride, multiple of four #1440

Open
halachkin opened this issue Jul 2, 2018 · 0 comments
Open

UnmanagedImage stride, multiple of four #1440

halachkin opened this issue Jul 2, 2018 · 0 comments

Comments

@halachkin
Copy link

halachkin commented Jul 2, 2018

Hello,

I noticed, that UnmanagedImage.Create method adjusts stride to make it multiple of four. It is the stride that System.Drawing.Bitmap needs.

public static UnmanagedImage Create(int width, int height, PixelFormat pixelFormat)
{
int bytesPerPixel = GetBytesPerPixel(pixelFormat);
// calculate stride
int stride = width * bytesPerPixel;
if (stride % 4 != 0)
{
stride += (4 - (stride % 4));
}
return Create(width, height, stride, pixelFormat);
}

Hovewer there is another method UnmanagedImage.Create

public static UnmanagedImage Create(int width, int height, int stride, PixelFormat pixelFormat)

that accepts stride and does not check it.

Than following code ends with exception, img.ToManagedImage is creating Bitmap image from invalid stride value.

using Accord.Imaging;
using System.Drawing.Imaging;
using System;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                var img = UnmanagedImage.FromByteArray(new byte[16], 3, 3, PixelFormat.Format8bppIndexed);
                img.ToManagedImage(false);
            }
            catch(Exception e)
            {
                Console.WriteLine(e);
            }
        }
    }
}

Here System.Drawing.Bitmap constructor will have invalid stride value (not mulitple of four)

public Bitmap ToManagedImage(bool makeCopy)
{
Bitmap dstImage = null;
try
{
if (!makeCopy)
{
dstImage = new Bitmap(width, height, stride, pixelFormat, imageData);
if (pixelFormat == PixelFormat.Format8bppIndexed)
{
Image.SetGrayscalePalette(dstImage);
}

@halachkin halachkin changed the title UnManagedImage stride, multiple of four UnmanagedImage stride, multiple of four Jul 2, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant