Skip to main content
GameDev.net gamedev.net
🔒 Locked

Crop Image before loading to Texture2D

Started by ver_T_ex Feb 22, 2009 at 5:18 PM 0 replies 3.3k views
Original Post
ver_T_ex
ver_T_ex
Hey guys, I've been working on this problem lately, that does not work yet. In my game, I am using large tilesets, sometimes larger than 10.000 pixels in height. Since graphic devices are only supporting textures up to 4096 pixels (at least mine) I am trying to crop the image before I actually load it to my Texture2D, assuming that the images are exceeding the size in height. This is the code I am using:

        public void LoadGraphic(GraphicsDevice myDevice)
        {
            ImageCount = (int)Math.Ceiling( (decimal) TilesetSize.Height / myDevice.GraphicsDeviceCapabilities.MaxTextureHeight);

            if(ImageCount > 1)
                TilesetImageSize.Height = myDevice.GraphicsDeviceCapabilities.MaxTextureHeight;

            //create enough textures to hold the whole image
            TilesetImages = new Texture2D[ImageCount];

            //Load image
            Image img = Image.FromFile(Path);

            for (int i = 0; i < ImageCount; i++ )
            {
                Bitmap bmPhoto = new Bitmap(TilesetImageSize.Width, TilesetImageSize.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
                Graphics grPhoto = Graphics.FromImage(bmPhoto);
                grPhoto.DrawImage(img, new System.Drawing.Rectangle(0, 0, TilesetImageSize.Width, TilesetImageSize.Height),
                                        0, i * TilesetImageSize.Height, TilesetImageSize.Width, TilesetImageSize.Height,
                                        System.Drawing.GraphicsUnit.Pixel);

                // Save to memory
                MemoryStream stream = new MemoryStream();
                bmPhoto.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
                
                bmPhoto.Dispose();
                grPhoto.Dispose();

                TilesetImages = Texture2D.FromFile(myDevice, stream);
            }

            img.Dispose();

        }

There seems to be a problem with the last part, where I try to load the texture from the stream. I get an unknown exception, not giving me a clue where to start looking - maybe you guys can help. Thanks, really appreciate it!
ver_T_ex
ver_T_ex
Argh, yet again, I solved the problem before anyone could answer.
I found a very good hint on:

Ziggys Page

Turns out that the memory stream pointer needed to be set to the beginning:

stream.Seek(0, SeekOrigin.Begin);


Good lord!

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.