luc
luc

Reputation: 117

C# how to show image in picturebox

I'm trying to display dicom image using openDicom.net. What should i correct here?

openDicom.Image.PixelData obraz = new openDicom.Image.PixelData(file.DataSet);
// System.Drawing.Bitmap obrazek = (Bitmap)Bitmap.FromFile(element);
pictureBox1.Image = obraz;
pictureBox1.Show();

Upvotes: 1

Views: 8694

Answers (1)

Nathan Wheeler
Nathan Wheeler

Reputation: 5932

PixelData is not an image. PixelData is raw image information. In my experience, most DICOM files will be using jpeg2000 images. In order to convert them to something usable by a PictureBox, you'll need to convert it to an Image. For raw monochrome types, you can make it into a System.Drawing.Bitmap using the following conversion:

openDicom.Image.PixelData obraz = new openDicom.Image.PixelData(file.DataSet);

Bitmap img = new System.Drawing.Bitmap(obraz.Columns, obraz.Rows, System.Drawing.Imaging.PixelFormat.Format24bppRgb);

int resampleval = (int)Math.Pow(2, (obraz.BitsAllocated - obraz.BitsStored));
int pxCount = 0;
int temp = 0;

try
{
    unsafe
    {
        BitmapData bd = img.LockBits(new Rectangle(0, 0, obraz.Columns, obraz.Rows), ImageLockMode.WriteOnly, img.PixelFormat);

        for (int r = 0; r < bd.Height; r++)
        {
            byte* row = (byte*)bd.Scan0 + (r * bd.Stride);

            for (int c = 0; c < bd.Width; c++)
            {
                temp = PixelData16[pxCount] / resampleval;

                while (temp > 255)
                    temp = temp / resampleval;

                row[(c * 3)] = (byte)temp;
                row[(c * 3) + 1] = (byte)temp;
                row[(c * 3) + 2] = (byte)temp;

                pxCount++;
            }
        }

        img.UnlockBits(bd);
    }
}
catch
{
    img = new Bitmap(10, 10);
}

pictureBox1.Image = img;
pictureBox1.Show();

For other image types, you'll need to do a similar conversion with the appropriate values. This conversion is strictly for monochrome types, and only after they have been converted from jpeg2000 to jpeg. Performing this operation on a jpeg2000 image will give you exactly half of the image filled with static and the other half completely empty.

Upvotes: 1

Related Questions