Load just a portion of the image thought stream

I’m loading images from outside unity using Texture2D extension method, LoadImage, everything is working fine, but now I need to load just a portion of some pngs. example: we have a sprite sheet with 16x64 but I want to get just the first image in a 16x16 texture. Any help would be welcome

I tried to change the png size in stream array reader manually, but it does not work.
I also tried to manually add the IEND into the end of the stream, but it does not work too.

Commented code was my last two tries

private static Sprite GetSpriteFromEntry (ZipArchiveEntry zipArchiveEntry)
{
    using (var ms = new MemoryStream())
    {
        // var buffer = new byte[512];
        // var count = zipArchiveEntry.Open().Read(buffer, 0, 512);
        // buffer[23] = 16;
        // ms.Write(buffer, 0, count);
        zipArchiveEntry
             .Open()
             .CopyTo(ms);
        
        // ms.Seek(243, SeekOrigin.Begin);
        // ms.Write(endBuffer, 0, 12);
        var tex = new Texture2D(2, 2);
        tex.LoadImage(ms.ToArray());

        return Sprite.Create(tex, new Rect(0f, 0f, tex.width, tex.height), new Vector2(.5f, .5f), 16f);
    }
}

you have to load the whole image to make any sense of its data. So you will have to do that, then create your sprite rect to only be the part of the image you want. if you only want the first 16x16 could just create your sprite to use 16 and 16 for its width and height in its rect.

1 Like

Thanks for your response, you’re right, just changed the rect size and it worked. But this way the texture will always have the real size, which means that if I want to, for example, use this texture in a button on editor I can’t show just a portion of it, am I correct? Does I have some way to be able to actually cut the texture OR some approach to be able to when reference the texture get only the desired portion of it?

yeah if you wanted to reduce down to 16x16 as a texture, i would construct a new texture at the correct size, then just copy the texture data you care about between them, can use GetPixels and SetPixels for that or in a loop with GetPixel and SetPixel. If you do not need data in the first texture anymore would call Destroy on it as well.

1 Like

Get and Set pixels worked like a charm, thanks for your time :wink:

1 Like