简体   繁体   中英

Why isn't my image loading?

    private void LoadImageList()
    {
        string filepath = Application.StartupPath + @"\Content\Textures\Tiles\PlatformTiles.png";
        Bitmap tileSheet = new Bitmap(filepath);
        int tilecount = 0;

        for (int y = 0; y < tileSheet.Height / TileGrid.TileHeight; y++)
        {
            for (int x = 0; x < tileSheet.Width / TileGrid.TileWidth; x++)
            {
                Bitmap newBitmap = tileSheet.Clone(
                    new System.Drawing.Rectangle(
                        x * TileGrid.TileWidth,
                        y * TileGrid.TileHeight,
                        TileGrid.TileWidth,
                        TileGrid.TileHeight),
                        System.Drawing.Imaging.PixelFormat.DontCare);

                imgListTiles.Images.Add(newBitmap);
                string itemName = "";
                if (tilecount == 0)
                {
                    itemName = "Empty";
                }
                if (tilecount == 1)
                {
                    itemName = "White";
                }
                listTiles.Items.Add(new ListViewItem(itemName, tilecount++));
            }
        }
    }

All I did was update PlatformTiles.png with a newer one and the next time I ran the program it doesn't load. I placed a breakpoint at int tilecount = 0; and it doesn't ever reach it. Every thing after it doesn't load either. Any ideas?

Is that Bitmap referring to System.Drawing.Bitmap ? If so your code has a memory leak. You're creating hundreds (thousands?) of Bitmap objects without disposing them. Each Bitmap object encapsulates a GDI Bitmap surface which must be explicitly disposed. Use a C# using(Bitmap bmp) { } block to ensure they're disposed when they fall out of scope, or ensure that you dispose of the bitmaps when the parent class object is disposed.

This may be related to your problem (generally it's a bad idea to create too many bitmaps in case you hit the GDI Object limit).

I got rid of the string and replaced filepatth, Bitmap tileSheet = new Bitmap(filepath);, with the path of the image on my hard-drive and it worked. Solution, but could use some explaining.

If the file is part of your content project and it's Build Action is set to Compile, the file that's in that folder at run time does not have a .png extension so the Bitmap will never be created. Content assets have a .xnb extension as they've been compiled to a binary format. Change the Build Action to None and the Copy to Output Direction to Copy if newer

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM