bitmap和byte数组的相互转换

由于需要在BOCHS做扩展,为了方便使用,我还得自己设计按钮。

但是看BOCHS的代码发现,bochs是从byte数组创建位图Bitmap的。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
namespace bitmap_to_uchar1
{
    class Program
    {
        static void Main(string[] args)
        {
            MemoryStream stream = new MemoryStream();
            Image img = Image.FromFile("c://flush.bmp");
            Bitmap bitmap = new Bitmap(img);
            int i = 0;
            bitmap.Save(stream, ImageFormat.Bmp);
            
            byte[] byteArray = stream.GetBuffer();
            byte[] bytelist = byteArray;
            //printf("the length of array is %d", byteArray.Length);
            System.Console.WriteLine("the length of array is  {0} ", byteArray.Length);
            Console.ReadLine();


            for (i = 0; i<900;i++ )
            {
                System.Console.Write("{0} ", byteArray[i]);   
            }
            Console.ReadLine();

            string path = @"c:\MyTest.txt";
            MemoryStream ms1 = new MemoryStream(bytelist);
            Bitmap bm = (Bitmap)Image.FromStream(ms1);
            // Delete the file if it exists.
            if (File.Exists(path)) 
            {
                File.Delete(path);
            }
            using (FileStream fs = File.Create(path)) 
            {
                
               // AddText(fs, "This is some text");
               // AddText(fs, "This is some more text,");
                //AddText(fs, "\r\nand this is on a new line");
                //AddText(fs, "\r\n\r\nThe following is a subset of characters:\r\n");
                fs.Write(byteArray, 0, byteArray.Length);
            }

            bm.Save("c:\\dd5.bmp "); 

          }

        private static void printf(string p, int p_2)
        {
            throw new NotImplementedException();
        }

        private static Bitmap Bitmap(string p)
        {
            throw new NotImplementedException();
        }


        private static void AddText(FileStream fs, string value)
        {
            byte[] info = new UTF8Encoding(true).GetBytes(value);
            fs.Write(info, 0, info.Length);
        }


        private static void printf(string p)
        {
            throw new NotImplementedException();
        }

    }
}

我的目的就是把我自己用vs画图附件画出来的图像生成一个byte数组,然后利用这个byte数组来在Bochs中生成我需要的图标。上面的程序已经可以从画出来的图像得到一个byte数组,但是就是大小不能符合,数组的长度总是为8192. 在BOCHS中,它的按钮是采用32*32像素的,它的生成是用一个byte数组生成的,那个byte数组的大小是128,刚好128*8=32*32

BOCHS中的核心代码是这样的:

  bx_bitmaps[bx_bitmap_entries].bmap = CreateBitmap(xdim,ydim,1,1,NULL);
  if (!bx_bitmaps[bx_bitmap_entries].bmap)
    terminateEmul(EXIT_HEADER_BITMAP_ERROR);

  data = new unsigned char[ydim * xdim/8];
  for (unsigned i=0; i

那么然而我在前面程序得出的buffer大小是8192,我曾以为是文件的像素问题,我调整了像素还是不行。

这个问题想先总结到这里,我暂时不用这个数据了,直接画乱改了一个数组上去。
希望知道怎么解决的可以联系我。



你可能感兴趣的:(技术总结,byte,string,path,stream,encoding,header)