Convert a image to a monochrome byte array

后端 未结 2 1309
失恋的感觉
失恋的感觉 2020-12-12 04:42

I am writing a library to interface C# with the EPL2 printer language. One feature I would like to try to implement is printing images, the specification doc says

相关标签:
2条回答
  • 2020-12-12 04:56

    As SLaks said I needed to use LockBits

    Rectangle rect = new Rectangle(0, 0, Bitmap.Width, Bitmap.Height);
    System.Drawing.Imaging.BitmapData bmpData = null;
    byte[] bitVaues = null;
    int stride = 0;
    try
    {
        bmpData = Bitmap.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadOnly, Bitmap.PixelFormat);
        IntPtr ptr = bmpData.Scan0;
        stride = bmpData.Stride;
        int bytes = bmpData.Stride * Bitmap.Height;
        bitVaues = new byte[bytes];
        System.Runtime.InteropServices.Marshal.Copy(ptr, bitVaues, 0, bytes);
    }
    finally
    {
        if (bmpData != null)
            Bitmap.UnlockBits(bmpData);
    }
    
    0 讨论(0)
  • 2020-12-12 05:06

    If you just need to convert your bitmap into a byte array, try using a MemoryStream:

    Check out this link: C# Image to Byte Array and Byte Array to Image Converter Class

    public byte[] imageToByteArray(System.Drawing.Image imageIn)
    {
     MemoryStream ms = new MemoryStream();
     imageIn.Save(ms,System.Drawing.Imaging.ImageFormat.Gif);
     return  ms.ToArray();
    }
    
    0 讨论(0)
提交回复
热议问题