dmc1989
@dmc1989

Как конвертировать двуичный код в изображение в C#?

Я перевожу изображение в byte код при помощи следующего метода:
static readonly string[] lookup = InitLookup();

private static string[] InitLookup()
        {
            string[] instance = new string[1 + byte.MaxValue];
            StringBuilder buffer = new StringBuilder("00000000");
            for (int i = 0; i < instance.Length; ++i)
            {

                buffer[0] = (char)('0' + ((i >> 7) & 1));
                buffer[1] = (char)('0' + ((i >> 6) & 1));
                buffer[2] = (char)('0' + ((i >> 5) & 1));
                buffer[3] = (char)('0' + ((i >> 4) & 1));
                buffer[4] = (char)('0' + ((i >> 3) & 1));
                buffer[5] = (char)('0' + ((i >> 2) & 1));
                buffer[6] = (char)('0' + ((i >> 1) & 1));
                buffer[7] = (char)('0' + ((i >> 0) & 1));

                instance[i] = buffer.ToString();
            }
            return instance;
        }

        static string bytes2bin(byte[] bytes)
        {
            StringBuilder buffer = new StringBuilder(bytes.Length * 8);
            foreach (byte b in bytes)
            {
                buffer.Append(lookup[b]);
            }
            string binary = buffer.ToString();
            return binary;
        }


Оно сдвигает в каждой ячейке 8 раз по байту и получает восьмеричное значение, как я понимаю.

Но вот как перевести обратно не могу понять ( Код не мой, не могу разобраться как провести обратную операцию ).
  • Вопрос задан
  • 1129 просмотров
Пригласить эксперта
Ответы на вопрос 1
@mefutu
И так, для конвертирования изображения в byte[] есть такие функции:
public static byte[] ImageToByte(Image img)
{
    ImageConverter converter = new ImageConverter();
    return (byte[])converter.ConvertTo(img, typeof(byte[]));
}
public static byte[] ImageToByte2(Image img)
{
    using (var stream = new MemoryStream())
    {
        img.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
        return stream.ToArray();
    }
}

Из byte[] получить bitmap/image необходимо сначала перевести byte[] в Stream
Stream stream = new MemoryStream(byteArray);

var bitmap = new Bitmap(stream);

В asp.net классах есть прекрасная библиотека работы с изображениями : WebImage. В ней вы можете:
  • Уменьшать размер (Пропорционально)
  • Добавлять watermark
  • и многое др....


P.S Для быстрого получения пикселей лучше не пользоваться стандартными возможностями bitmap (слишком медленно), воспользуйтесь этим классом
spoiler
public class LockBitmap
{
    Bitmap source = null;
    IntPtr Iptr = IntPtr.Zero;
    BitmapData bitmapData = null;
 
    public byte[] Pixels { get; set; }
    public int Depth { get; private set; }
    public int Width { get; private set; }
    public int Height { get; private set; }
 
    public LockBitmap(Bitmap source)
    {
        this.source = source;
    }
 
    /// <summary>
    /// Lock bitmap data
    /// </summary>
    public void LockBits()
    {
        try
        {
            // Get width and height of bitmap
            Width = source.Width;
            Height = source.Height;
 
            // get total locked pixels count
            int PixelCount = Width * Height;
 
            // Create rectangle to lock
            Rectangle rect = new Rectangle(0, 0, Width, Height);
 
            // get source bitmap pixel format size
            Depth = System.Drawing.Bitmap.GetPixelFormatSize(source.PixelFormat);
 
            // Check if bpp (Bits Per Pixel) is 8, 24, or 32
            if (Depth != 8 && Depth != 24 && Depth != 32)
            {
                throw new ArgumentException("Only 8, 24 and 32 bpp images are supported.");
            }
 
            // Lock bitmap and return bitmap data
            bitmapData = source.LockBits(rect, ImageLockMode.ReadWrite, 
                                         source.PixelFormat);
 
            // create byte array to copy pixel values
            int step = Depth / 8;
            Pixels = new byte[PixelCount * step];
            Iptr = bitmapData.Scan0;
 
            // Copy data from pointer to array
            Marshal.Copy(Iptr, Pixels, 0, Pixels.Length);
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
 
    /// <summary>
    /// Unlock bitmap data
    /// </summary>
    public void UnlockBits()
    {
        try
        {
            // Copy data from byte array to pointer
            Marshal.Copy(Pixels, 0, Iptr, Pixels.Length);
 
            // Unlock bitmap data
            source.UnlockBits(bitmapData);
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
 
    /// <summary>
    /// Get the color of the specified pixel
    /// </summary>
    /// <param name="x"></param>
    /// <param name="y"></param>
    /// <returns></returns>
    public Color GetPixel(int x, int y)
    {
        Color clr = Color.Empty;
 
        // Get color components count
        int cCount = Depth / 8;
 
        // Get start index of the specified pixel
        int i = ((y * Width) + x) * cCount;
 
        if (i > Pixels.Length - cCount)
            throw new IndexOutOfRangeException();
 
        if (Depth == 32) // For 32 bpp get Red, Green, Blue and Alpha
        {
            byte b = Pixels[i];
            byte g = Pixels[i + 1];
            byte r = Pixels[i + 2];
            byte a = Pixels[i + 3]; // a
            clr = Color.FromArgb(a, r, g, b);
        }
        if (Depth == 24) // For 24 bpp get Red, Green and Blue
        {
            byte b = Pixels[i];
            byte g = Pixels[i + 1];
            byte r = Pixels[i + 2];
            clr = Color.FromArgb(r, g, b);
        }
        if (Depth == 8)
        // For 8 bpp get color value (Red, Green and Blue values are the same)
        {
            byte c = Pixels[i];
            clr = Color.FromArgb(c, c, c);
        }
        return clr;
    }
 
    /// <summary>
    /// Set the color of the specified pixel
    /// </summary>
    /// <param name="x"></param>
    /// <param name="y"></param>
    /// <param name="color"></param>
    public void SetPixel(int x, int y, Color color)
    {
        // Get color components count
        int cCount = Depth / 8;
 
        // Get start index of the specified pixel
        int i = ((y * Width) + x) * cCount;
 
        if (Depth == 32) // For 32 bpp set Red, Green, Blue and Alpha
        {
            Pixels[i] = color.B;
            Pixels[i + 1] = color.G;
            Pixels[i + 2] = color.R;
            Pixels[i + 3] = color.A;
        }
        if (Depth == 24) // For 24 bpp set Red, Green and Blue
        {
            Pixels[i] = color.B;
            Pixels[i + 1] = color.G;
            Pixels[i + 2] = color.R;
        }
        if (Depth == 8)
        // For 8 bpp set color value (Red, Green and Blue values are the same)
        {
            Pixels[i] = color.B;
        }
    }
}
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы