TheCallSign / fjcore

Automatically exported from code.google.com/p/fjcore
0 stars 0 forks source link

FromBitmap, FromFile and FromStream methods for FluxJpeg.Core.Image #14

Open GoogleCodeExporter opened 8 years ago

GoogleCodeExporter commented 8 years ago
I haven't found means to contact the project owners directly, so I'm attaching 
a patched Image.cs to this issue with added methods for those who are wondering 
how to use JpegEncoder with Bitmaps generated by means of .NET code, and for 
those who wish to load raster data from GDI+ supported image formats:

        public static Image FromStream(Stream inStream)
        {
            using (Bitmap bmp = new Bitmap(Bitmap.FromStream(inStream)))
            {
                return FromBitmap(bmp);
            }
        }

        public static Image FromFile(string filePath)
        {
            using (Bitmap bmp = new Bitmap(Bitmap.FromFile(filePath)))
            {
                return FromBitmap(bmp);
            }
        }

        public static Image FromBitmap(Bitmap bitmap)
        {
            int width = bitmap.Width;
            int height = bitmap.Height;
            int bands = 3;
            byte[][,] raster = new byte[bands][,];

            for (int i = 0; i < bands; i++)
            {
                raster[i] = new byte[width, height];
            }

            BitmapData bd = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);

            int[] pixels = new int[bd.Width * bd.Height];
            Marshal.Copy(bd.Scan0, pixels, 0, pixels.Length);

            bitmap.UnlockBits(bd);

            for (int row = 0; row < height; row++)
            {
                for (int column = 0; column < width; column++)
                {
                    int pixel = 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 };

            return new Image(model, raster);
        }

Best wishes,
Ilya Melamed

Original issue reported on code.google.com by ily...@gmail.com on 1 Mar 2015 at 3:18

Attachments: