Search code examples
c#uwpbitmapwin-universal-apprendertargetbitmap

UWP The specified buffer index is not within the buffer capacity


I got this exception when I am trying to do this:

        var pixels = await bitmap.GetPixelsAsync();
        byte[] bytes = pixels.ToArray();

It occurs at pixels.ToArray(). The information here doesn't help me too much. I only know that the length and capacity of my pixels are 0 but I don't know why and how to fix that.

The context of this piece of code:

    public static async Task<string> SaveThumbnail(UIElement image, bool isCurrent)
    {
        var bitmap = new RenderTargetBitmap();
        try
        {
            await bitmap.RenderAsync(image);
        }
        catch (ArgumentException)
        {
            return "";
        }
        var pixels = await bitmap.GetPixelsAsync();
        byte[] bytes = pixels.ToArray();
        // some other code
    }

This function is was called here:

    public static async Task<Brush> GetThumbnailMainColor(UIElement image, bool isCurrent)
    {
        var filename = await SaveThumbnail(image, isCurrent);
        var file = await ThumbnailFolder.GetFileAsync(filename);
        return await ColorHelper.GetThumbnailMainColor(file);
    }

And it is called here:

        thumbnail.Source = thumbnails.Count == 0 ? Helper.DefaultAlbumCover : thumbnails[random.Next(thumbnails.Count)];
        grid.Background = await Helper.GetThumbnailMainColor(thumbnail, false);

I set the Image source right before the call and I am pretty sure I can see the image displayed in thumbnail. So why do I get 0-Capacity pixels?


Solution

  • Maybe you render RenderTargetBitmap too quick after setting the source of the thumbnail (Is it Image control?), and the image is not yet rendered on the interface, which will result in you not getting the image inside the Image.

    Try this:

    thumbnail.Source = thumbnails.Count == 0 ? Helper.DefaultAlbumCover : thumbnails[random.Next(thumbnails.Count)];
    thumbnail.Loaded += async (_s,_e) =>
    {
        grid.Background = await Helper.GetThumbnailMainColor(thumbnail, false);
    }
    

    Best regards.