C#中保存Gif文件设置透明无效果

在C#中使用Graphics.Clear(Color.Transparent)生成gif格式透明文件时,设置透明不起作用。使用Bitmap.MakeTransparent 方法同样也不能使gif文件透明。这两个问题也是微软的设计使然,和gif文件格式有关系。

如果要在c#中编程实现透明色,必须另写代码,下面是一位老外的代码

///   <summary>
///  Make the image transparent. 
///  The input is the color which you want to make transparent.
///   </summary>
///   <param name="color"> The color to make transparent. </param>
///   <param name="bitmap"> The bitmap to make transparent. </param>
///   <returns> New memory stream containing transparent background gif. </returns>
public  Bitmap MakeTransparentGif(Bitmap bitmap, Color color)
{
    
byte  R  =  color.R;
    
byte  G  =  color.G;
    
byte  B  =  color.B;

    MemoryStream fin 
=   new  MemoryStream();
    bitmap.Save(fin, System.Drawing.Imaging.ImageFormat.Gif);

    MemoryStream fout 
=   new  MemoryStream(( int )fin.Length);
    
int  count  =   0 ;
    
byte [] buf  =   new   byte [ 256 ];
    
byte  transparentIdx  =   0 ;
    fin.Seek(
0 , SeekOrigin.Begin);
    
// header
    count  =  fin.Read(buf,  0 13 );
    
if  ((buf[ 0 !=   71 ||  (buf[ 1 !=   73 ||  (buf[ 2 !=   70 ))  return   null // GIF

    fout.Write(buf, 
0 13 );

    
int  i  =   0 ;
    
if  ((buf[ 10 &   0x80 >   0 )
    {
        i 
=   1   <<  ((buf[ 10 &   7 +   1 ==   256   ?   256  :  0 ;
    }

    
for  (; i  !=   0 ; i -- )
    {
        fin.Read(buf, 
0 3 );
        
if  ((buf[ 0 ==  R)  &&  (buf[ 1 ==  G)  &&  (buf[ 2 ==  B))
        {
            transparentIdx 
=  ( byte )( 256   -  i);
        }
        fout.Write(buf, 
0 3 );
    }

    
bool  gcePresent  =   false ;
    
while  ( true )
    {
        fin.Read(buf, 
0 1 );
        fout.Write(buf, 
0 1 );
        
if  (buf[ 0 !=   0x21 break ;
        fin.Read(buf, 
0 1 );
        fout.Write(buf, 
0 1 );
        gcePresent 
=  (buf[ 0 ==   0xf9 );
        
while  ( true )
        {
            fin.Read(buf, 
0 1 );
            fout.Write(buf, 
0 1 );
            
if  (buf[ 0 ==   0 break ;
            count 
=  buf[ 0 ];
            
if  (fin.Read(buf,  0 , count)  !=  count)  return   null ;
            
if  (gcePresent)
            {
                
if  (count  ==   4 )
                {
                    buf[
0 |=   0x01 ;
                    buf[
3 =  transparentIdx;
                }
            }
            fout.Write(buf, 
0 , count);
        }
    }
    
while  (count  >   0 )
    {
        count 
=  fin.Read(buf,  0 1 );
        fout.Write(buf, 
0 1 );
    }
    fin.Close();
    fout.Flush();

    
return   new  Bitmap(fout);
}

在生成图片之后调用此方法,即可使gif显示透明色。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值