Index8 Bitmap Cropping / Resizing

DavyJCDavyJC GBMember

Hi,

I have code that uses WIC that I would like to move to using SkiaSharp (as WIC is not officially supported for use in server side apps).
The code crops, then resizes 8 bit indexed TIFF files from disk. (It is necessary to crop then resize to maximise performance when zoomed to high levels).

I'm aware that the SKBitmap.Decode() method cannot be used for 8 bit indexed (at least whenever I do it returns the skbitmap as null).

So I have been trying the following based on other forum posts. I am sure that this is failing because I am trying to read raw image bytes into the SetPixels method versus an actual pixel array, but I cannot see how to create the bitmap, then read in the data after the fact from a filestream or file on disk:

        using (FileStream fs = new FileStream(inputFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
        {
        // Set palette for 8 bit image
                SKColor[] indexArr = new SKColor[256];
                for (int i = 0; i < 256; i++)
                {
                    indexArr[i] = new SKColor((byte)i, (byte)i, (byte)i);
                }
        // Set colour table
                SKColorTable ct = new SKColorTable(indexArr);

                using (SKBitmap bitmap= new SKBitmap(new SKImageInfo(serverImageSize.Width, serverImageSize.Height, SKColorType.Index8,             SKAlphaType.Opaque), ct)){
                IntPtr ptr = fs.SafeFileHandle.DangerousGetHandle();
                bitmap.SetPixels(ptr, ct);
                    // create a canvas for drawing
                    using (var canvas = new SKCanvas(bitmap))
                    {
                        // get an image subset to save
                        using (var image = SKImage.FromBitmap(bitmap)) //<-- AccessViolationException here
                        {
                            using (var croppedImage = image.Subset(SKRectI.Create(cropX, cropY, width, height)))
                            {
                                var resizedImage = SKBitmap.FromImage(croppedImage);
                                resizedImage.Resize(new SKImageInfo(100, 100), SKBitmapResizeMethod.Lanczos3);
                                var image2 = SKImage.FromBitmap(resizedImage);
                                var data = image2.Encode(SKEncodedImageFormat.Jpeg, 100);
                            }
                        }
        }
                 }
             }

Please let me know if I am missing something here. It's not an option to create the bitmap via WIC / System.Drawing first, as the code is performance critical.

Thanks
David

Tagged:
Sign In or Register to comment.