Displaying an icon in a picturebox
Asked Answered
T

3

12

I am trying to display icon file in a picture box. I'm using this code to set the image.

pictureBox1.Image = new Icon(openFileDialog.FileName, new Size(48, 48)).ToBitmap();

But I'm getting this exception.

System.ArgumentOutOfRangeException: Requested range extends past the end of the array.
   at System.Runtime.InteropServices.Marshal.CopyToNative(Object source, Int32 startIndex, IntPtr destination, Int32 length)
   at System.Runtime.InteropServices.Marshal.Copy(Byte[] source, Int32 startIndex, IntPtr destination, Int32 length)
   at System.Drawing.Icon.ToBitmap()

How to overcome this problem?

Thanks.

Tarpon answered 3/4, 2013 at 8:55 Comment(0)
T
13

Solved the problem.

pictureBox1.Image = Bitmap.FromHicon(new Icon(openFileDialog.FileName, new Size(48, 48)).Handle);
Tarpon answered 3/4, 2013 at 9:6 Comment(0)
D
4

Some icons are sized incorrectly 48x48 to 32x32.

My final code is:

    Bitmap _image;
    try
    {
     _image = new Icon(icon, width, height).ToBitmap();
    }
    catch(ArgumentOutOfRangeException)
    {
     _image = Bitmap.FromHicon(new Icon(icon, new Size(width, height)).Handle);
    }
Dorella answered 27/10, 2015 at 15:56 Comment(0)
V
1

Sometimes Bitmap.FromHicon doesn't convert perfectly. I find another solution:

// event Paint of pictureBox1
void pictureBox1_Paint(object sender, PaintEventArgs e)
{
    e.Graphics.DrawIcon(theIcon, 0, 0);
}
Valero answered 23/3, 2018 at 15:34 Comment(1)
+1 for native event methods, and works out of the box. Use with Icon myIcon = System.Drawing.Icon.ExtractAssociatedIcon(@filePath);Slippy

© 2022 - 2024 — McMap. All rights reserved.