Beispiel #1
0
            public static GdkPixBufBitmapSource Create(IntPtr pixbuf)
            {
                var colorSpace = LibGdkPixBuf.gdk_pixbuf_get_colorspace(pixbuf);

                if (colorSpace != GdkColorspace.GDK_COLORSPACE_RGB)
                {
                    throw new IOException($"Unsupported color space: {colorSpace}.");
                }

                var  nChannels = LibGdkPixBuf.gdk_pixbuf_get_n_channels(pixbuf);
                bool hasAlpha  = LibGdkPixBuf.gdk_pixbuf_get_has_alpha(pixbuf);

                PixelFormat pixelFormat;

                if (nChannels == 4 && hasAlpha)
                {
                    pixelFormat = PixelFormat.RGBA_32;
                }
                else if (nChannels == 3 && !hasAlpha)
                {
                    pixelFormat = PixelFormat.RGB_24;
                }
                else
                {
                    throw new IOException($"Unsupported number of channels: {nChannels} (has alpha: {hasAlpha}).");
                }

                int bitsPerChanel = LibGdkPixBuf.gdk_pixbuf_get_bits_per_sample(pixbuf);

                if (bitsPerChanel != 8)
                {
                    throw new IOException($"Unsupported number of bits per chanel: {bitsPerChanel}.");
                }

                int width  = LibGdkPixBuf.gdk_pixbuf_get_width(pixbuf);
                int height = LibGdkPixBuf.gdk_pixbuf_get_height(pixbuf);
                int stride = LibGdkPixBuf.gdk_pixbuf_get_rowstride(pixbuf);

                if (stride < width * nChannels)
                {
                    throw new IOException(
                              $"Unexpected row stride. Channels: {nChannels}. Bits per chanel: {bitsPerChanel}. Width: {width}. Stride: {stride}."
                              );
                }

                IntPtr dataPtr = LibGdkPixBuf.gdk_pixbuf_get_pixels(pixbuf);

                return(new GdkPixBufBitmapSource(pixbuf, dataPtr, width, height, stride, pixelFormat));
            }