转换图形为GIF格式,获取GIF的的颜色表。发现只有颜色索引表16的alpha是0 就是透明色。
根据图形的ALPHA为0的情况下 来设置颜色索引表。
使用方式 如果要保存图形为透明把具体位置的ALPHA的值设置为0
- Bitmap _Bitmap24 = (Bitmap)Image.FromFile(@"C:/bfx/24.bmp");
- pictureBox1.Image = ToImageGif(_Bitmap24);
- Bitmap _BitmapGDI = new Bitmap(200, 200);
- Graphics g = Graphics.FromImage(_BitmapGDI);
- g.DrawString("ASDF", new Font("宋体", 20), Brushes.Yellow, new Point(0, 0));
- pictureBox2.Image = ToImageGif(_BitmapGDI);
- pictureBox2.Image.Save(@"c:/1.GIF", ImageFormat.Gif);
把具体方法
- private static Bitmap ToImageGif(Bitmap MyBitMap)
- {
- int _Width = MyBitMap.Width;
- int _Height = MyBitMap.Height;
- System.IO.MemoryStream _MemoryStream = new MemoryStream();
- MyBitMap.Save(_MemoryStream, ImageFormat.Gif);
- Bitmap _MyBitMap256 = (Bitmap)Image.FromStream(_MemoryStream); //保存成GIF 256色
- _MemoryStream.Dispose();
- //获取颜色索引
- System.Drawing.Imaging.ColorPalette _ColorPalette = _MyBitMap256.Palette;
- Hashtable _ColorHash = new Hashtable();
- for (int i = 0; i != _ColorPalette.Entries.Length; i++)
- {
- string _Key=_ColorPalette.Entries[i].R.ToString("X02")+_ColorPalette.Entries[i].G.ToString("X02")+_ColorPalette.Entries[i].B.ToString("X02");
- if(_ColorHash[_Key]==null)_ColorHash.Add(_Key, i);
- }
- 建立新的图形
- Bitmap _Newbitmap = new Bitmap(_Width, _Height, System.Drawing.Imaging.PixelFormat.Format8bppIndexed);
- _Newbitmap.Palette = _ColorPalette; //设置索引
- Rectangle _Rect = new Rectangle(0, 0, _Width, _Height);
- //获取IMAGE数据
- System.Drawing.Imaging.BitmapData _BitmapData = _Newbitmap.LockBits(_Rect, System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format8bppIndexed);
- byte[] _Bits = new byte[_Width * _Height];
- Int32 _BitsInt = 0;
- if (_BitmapData.Stride > 0)
- {
- _BitsInt = _BitmapData.Scan0.ToInt32();
- }
- else
- {
- _BitsInt = _BitmapData.Scan0.ToInt32() + _BitmapData.Stride * (_Height - 1);
- }
- int _Stride = Math.Abs(_BitmapData.Stride);
- for (int i = 0; i != _Height; i++)
- {
- for (int y = 0; y != _Width; y++)
- {
- int _8BppPixel = i * _Stride + y;
- Color _TempColor=_MyBitMap256.GetPixel(y, i);
- int _Alpha = MyBitMap.GetPixel(y, i).A;
- if (_Alpha == 0)
- {
- _Bits[_8BppPixel] = (byte)16;
- }
- else
- {
- string _Key = _TempColor.R.ToString("X02") + _TempColor.G.ToString("X02") + _TempColor.B.ToString("X02");
- object _ValueIndex = _ColorHash[_Key];
- if (_ValueIndex == null) MessageBox.Show("Error");
- _Bits[_8BppPixel] = (byte)((int)_ValueIndex);
- }
- }
- }
- CopyArrayTo(_BitsInt, _Bits, _Height * _Stride);
- _Newbitmap.UnlockBits(_BitmapData);
- return _Newbitmap;
- }
- [DllImport("KERNEL32.DLL", EntryPoint = "RtlMoveMemory", SetLastError = true, CharSet = CharSet.Auto, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
- public static extern void CopyArrayTo([In(), MarshalAs(UnmanagedType.I4)] Int32 hpvDest, [In(), Out()]byte[] hpvSource, int cbCopy);