Using FJCore to encode Silverlight WriteableBitmap

前端 未结 3 923
走了就别回头了
走了就别回头了 2021-01-05 19:31

I am trying to find out how to use FJCore to encode a WriteableBitmap to a jpeg. I understand that WriteableBitmap provides the raw pixels but I am not sure how to convert i

3条回答
  •  孤城傲影
    2021-01-05 19:57

    Figured it out! I downloaded FJCore from code.google.com and went through the image class. It only expects the RGB bytes. Here is the function that I wrote. I need the base64 version of the image so that's what my function returns.

        private static string GetBase64Jpg(WriteableBitmap bitmap)
        {
            int width = bitmap.PixelWidth;
            int height = bitmap.PixelHeight;
            int bands = 3;
            byte[][,] raster = new byte[bands][,];
    
            for (int i = 0; i < bands; i++)
            {
                raster[i] = new byte[width, height];    
            }
    
            for (int row = 0; row < height; row++)
            {
                for (int column = 0; column < width; column++)
                {
                    int pixel = bitmap.Pixels[width * row + column];
                    raster[0][column, row] = (byte)(pixel >> 16);
                    raster[1][column, row] = (byte)(pixel >> 8);
                    raster[2][column, row] = (byte)pixel;
                }
            }
    
            ColorModel model = new ColorModel { colorspace = ColorSpace.RGB };
            FluxJpeg.Core.Image img = new FluxJpeg.Core.Image(model, raster);
            MemoryStream stream = new MemoryStream();
            JpegEncoder encoder = new JpegEncoder(img, 90, stream);
            encoder.Encode();
    
            stream.Seek(0, SeekOrigin.Begin);
            byte[] binaryData = new Byte[stream.Length];
            long bytesRead = stream.Read(binaryData, 0, (int)stream.Length);
    
            string base64String =
                    System.Convert.ToBase64String(binaryData,
                                                  0,
                                                  binaryData.Length);
    
            return base64String;
        }
    

提交回复
热议问题