Forum Libraries, Components, and Plugins

How to create a Index8 bitmap?

Expack3Expack3 USMember

I'm currently porting some color dithering code to .NET Core 2.0 and SkiaSharp. What I'm currently trying to implement is the creation of a new SKBitmap with SKColorType Index8 onto which I'll add the dithered pixels from the full-color source image. However, when using the following code:

SKBitmap b = new SKBitmap(320, 240, SKColorType.Index8, SKAlphaType.Opaque);

I get this message (pasted directly from VS 2017):

System.Exception occurred
HResult=0x80131500
  Message=Unable to allocate pixels for the bitmap.
  Source=<Cannot evaluate the exception source>
  StackTrace:
   at SkiaSharp.SKBitmap..ctor(SKImageInfo info, Int32 rowBytes)
   at SkiaSharp.SKBitmap..ctor(Int32 width, Int32 height, SKColorType colorType, SKAlphaType alphaType)
   at SkiaDitherTest.Program.Main(String[] args) in C:\Users\mcder\source\repos\SkiaDitherTest\SkiaDitherTest\Program.cs:line 16

I'll be the first to admit to being new to SkiaSharp, so I was wondering if there's a way to do what I need to do.....

Posts

  • mattleibowmattleibow ZAXamarin Team Xamurai

    The reason for this is that you have requested that the colors be index-based (Index8) but you have not given the colors to use (SKColorTable).

    Basically, you need to know the colors beforehand and then create a bitmap that references it:

    var info = new SKImageInfo(320, 240, SKColorType.Index8, SKAlphaType.Opaque);
    var ct = new SKColorTable(TheColorsArray);
    var bitmap = new SKBitmap(info, ct);
    

    Although this may not be exactly what you are looking for (creating a blank bitmap and creating the color table as you go), you can get around this by creating a blank color table, and then creating the bitmap, and then setting the color table. This preserves the "pixel data", but you switch out the colors:

    bitmap.SetColorTable(new SKColorTable(...));
    
  • Expack3Expack3 USMember

    @mattleibow said:
    The reason for this is that you have requested that the colors be index-based (Index8) but you have not given the colors to use (SKColorTable).

    Basically, you need to know the colors beforehand and then create a bitmap that references it:

    var info = new SKImageInfo(320, 240, SKColorType.Index8, SKAlphaType.Opaque);
    var ct = new SKColorTable(TheColorsArray);
    var bitmap = new SKBitmap(info, ct);
    

    Although this may not be exactly what you are looking for (creating a blank bitmap and creating the color table as you go), you can get around this by creating a blank color table, and then creating the bitmap, and then setting the color table. This preserves the "pixel data", but you switch out the colors:

    bitmap.SetColorTable(new SKColorTable(...));
    

    Actually, knowing I can "bake" the information about an image before it's created is extremely useful and will save me a lot of code and work! Thank you!

Sign In or Register to comment.