0

Im checking the size of image files and if the files are large then im re-sizing it so that the processing is faster. But when I use the resize code I always get a null reference exception pointing to image.I tried debugging-> the resized Bitmap that is returned is not null but the converted image > image = new Image(x); is null.The code works fine if I remove the resize function.

Image<Bgr, byte> image = null;

foreach (string s in mylist)
{
    Bitmap x = new Bitmap(Bitmap.FromFile(s));
    if (x.Width > 1000 || x.Height > 1000)
    {
        x = ResizekeepAspectRatio(x, 1000, 1000);
        image = new Image<Bgr, byte>(x);

    }
    else
    {
        image = new Image<Bgr, byte>(x);
    }

    work(image, x, s);
}

----------------------------------------------------------------------

Bitmap ResizekeepAspectRatio(Bitmap imgPhoto, int Width, int Height)
{
    int sourceWidth = imgPhoto.Width;
    int sourceHeight = imgPhoto.Height;
    int sourceX = 0;
    int sourceY = 0;
    int destX = 0;
    int destY = 0;

    float nPercent = 0;
    float nPercentW = 0;
    float nPercentH = 0;

    nPercentW = ((float)Width / (float)sourceWidth);
    nPercentH = ((float)Height / (float)sourceHeight);
    if (nPercentH < nPercentW)
    {
        nPercent = nPercentH;
        destX = System.Convert.ToInt16((Width -
                      (sourceWidth * nPercent)) / 2);
    }
    else
    {
        nPercent = nPercentW;
        destY = System.Convert.ToInt16((Height -
                      (sourceHeight * nPercent)) / 2);
    }

    int destWidth = (int)(sourceWidth * nPercent);
    int destHeight = (int)(sourceHeight * nPercent);

    Bitmap bmPhoto = new Bitmap(Width, Height,
                      PixelFormat.Format24bppRgb);
    bmPhoto.SetResolution(imgPhoto.HorizontalResolution,
                     imgPhoto.VerticalResolution);

    Graphics grPhoto = Graphics.FromImage(bmPhoto);
    grPhoto.Clear(Color.Red);
    grPhoto.InterpolationMode =
            InterpolationMode.HighQualityBicubic;

    grPhoto.DrawImage(imgPhoto,
        new Rectangle(destX, destY, destWidth, destHeight),
        new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight),
        GraphicsUnit.Pixel);

    grPhoto.Dispose();
    return bmPhoto;
}
RB.
  • 36,301
  • 12
  • 91
  • 131
techno
  • 6,100
  • 16
  • 86
  • 192

1 Answers1

0

I'm having trouble replicating the error. I passed in a bunch of images and saved them out, but they all save correctly - even those that are re-sized.

This makes me think it must either be some specific images that fail or it is perhaps a configuration issue with Emgu.

Can you post an image that fails?

Chris Smeal
  • 681
  • 1
  • 6
  • 13