氧气中毒 - Asp.Net

If you don't believe in yourself,Nobody else will!
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

asp.net中用C#自动生成透明的GIF图片

Posted on 2006-03-06 16:50  氧气中毒  阅读(1880)  评论(0)    收藏  举报
问题:

查遍网上资料,却没有关于在Asp.net中自动生成透明的GIF图片的代码。
值得大家探讨。
哪位高人能否解决这个问题?

解答:

作者:使名扬

方案1:最easy的方法利用css的滤镜

1.在aspx上拉一个HTML的img 然后run at server。同时为了体现透明,把背景色改成不同颜色自己看看效果。
<body MS_POSITIONING="GridLayout" background="images/bt_exit.gif">
  
<form id="Form1" method="post" runat="server">
   
<IMG alt="" src="" id="IMG1" style="FILTER: chroma(color:#000000)" runat="server">
如果整个GIF也要半透明可用 style="FILTER:alpha(opacity=50)"
  
</form>
 
</body>
2.codebehind的代码
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;


namespace dztz
{
 
/// 
 
/// test 的摘要说明。
 
/// 

 public class test : System.Web.UI.Page
 
{
  
protected System.Web.UI.HtmlControls.HtmlImage IMG1;


  
private void Page_Load(object sender, System.EventArgs e)
  
{
   MyTempImage myTempImage
=new MyTempImage();
   IMG1.Src
=myTempImage.CreateImage();
  }



  
Web 窗体设计器生成的代码
 }



 
public class MyTempImage : Page
 
{
  
public string CreateImage()
  
{
   
string str=DateTime.Now.ToString();
   Bitmap image
=new Bitmap(200,30);
   Graphics g
=Graphics.FromImage(image);
   
string thefullname=Server.MapPath("/")+"\\nowtime.gif";
   g.Clear(Color.Transparent); 
//这里用不用透明色无所谓的,透明色实际上会是黑色
   g.DrawString(str,new Font("Courier New"10),new 
SolidBrush(Color.FromArgb(
12800255)),20,5); //这里采用半透明字体
   image.Save(thefullname,System.Drawing.Imaging.ImageFormat.Gif);
   
return "/nowtime.gif";
  }

 }

}



方案2:生成一个真的透明背景的GIF图片(但是要调API,不推荐。)
Imports System.Runtime.InteropServices
Imports System
Imports System.IO
Imports System.Drawing
Imports System.Drawing.Imaging
Imports System.Drawing.Drawing2D


Public Class transparentGif : Inherits System.Web.UI.Page


    
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load


        
Dim pic As New System.Drawing.Bitmap(200200, PixelFormat.Format24bppRgb)


        
'''draw image
        Dim blackpen As New Pen(Color.Black, 3)
        
Dim redpen As New Pen(Color.Red, 4)
        
Dim silverpen As New Pen(ColorTranslator.FromHtml("#CCCCCC"), 10)
        
Dim fBrush As SolidBrush = New SolidBrush(ColorTranslator.FromHtml("#0000FF"))
        
Dim g As Graphics = Graphics.FromImage(pic)


        g.Clear(Color.White) 
' blank the image
        g.DrawLine(silverpen, 78011080)
        g.SmoothingMode 
= SmoothingMode.AntiAlias ' antialias objects
        g.DrawString("TEST"New Font("verdana"24, FontStyle.Bold), fBrush, New PointF(1050))
        g.DrawEllipse(blackpen, 
55110110)
        g.DrawEllipse(redpen, 
11118118)


        
'''save new image
        pic = recolorGif(pic)


        
' set the content type
        Response.ContentType = "image/gif"


        
' send the image to the viewer
        pic.Save(Response.OutputStream, ImageFormat.Gif)


        
' tidy up
        pic.Dispose()


    
End Sub



    
Private Function GetColorPalette() As ColorPalette
        
' Make a new Bitmap object to get its Palette.
        Dim bitmap As Bitmap = New Bitmap(11, PixelFormat.Format8bppIndexed)
        
Dim palette As ColorPalette = bitmap.Palette   ' Grab the palette
        bitmap.Dispose()
        
Return palette              ' Send the palette back
    End Function



    
Private Function recolorGif(ByVal image As Image) As Bitmap
        
Dim nColors As Integer = 16


        
' Make a new 8-BPP indexed bitmap that is the same size as the source image.
        Dim Width As Integer = image.Width
        
Dim Height As Integer = image.Height


        
Dim bitmap As Bitmap = New Bitmap(Width, Height, PixelFormat.Format8bppIndexed)


        
' Create a color palette big enough to hold the colors you want.
        Dim pal As ColorPalette = GetColorPalette()


        
' Initialize a new color table with entries 
        Dim i As Integer


        
' set palette the lazy way!
        ' replace with a proper color algorithm
        For i = 0 To nColors - 1
            pal.Entries(i) 
= Color.FromArgb(255100100100)
        
Next


        pal.Entries(
0= Color.FromArgb(255000)
        pal.Entries(
1= Color.FromArgb(25525500)
        pal.Entries(
2= Color.FromArgb(25502550)
        pal.Entries(
3= Color.FromArgb(25500255)
        pal.Entries(
4= Color.FromArgb(255204204204)
        pal.Entries(nColors 
- 1= Color.FromArgb(0255255255)


        
'web safe palette use values =
        '00 51 102 153 204 255 


        
' Set the palette into the new Bitmap object.
        bitmap.Palette = pal


        
Dim BmpCopy As Bitmap = New Bitmap(Width, Height, PixelFormat.Format32bppArgb)


        
Dim g As Graphics
        g 
= Graphics.FromImage(BmpCopy)


        g.PageUnit 
= GraphicsUnit.Pixel


        
' Transfer the Image to the Bitmap.
        g.DrawImage(image, 00, Width, Height)


        
' Force g to release its resources, namely BmpCopy.
        g.Dispose()


        
' Lock a rectangular portion of the bitmap for writing.
        Dim bitmapData As BitmapData
        
Dim rect As Rectangle = New Rectangle(00, Width, Height)


        bitmapData 
= bitmap.LockBits(rect, ImageLockMode.WriteOnly, PixelFormat.Format8bppIndexed)


        
' Copy the pixels from the source image 
        Dim pixels As IntPtr = bitmapData.Scan0
        
Dim bits As Byte()      ' the buffer
        Dim pBits As Int32


        
If (bitmapData.Stride > 0Then
            pBits 
= pixels.ToInt32()
        
Else
            pBits 
= pixels.ToInt32() + bitmapData.Stride * (Height - 1)
        
End If


        
Dim stride As Integer = Math.Abs(bitmapData.Stride)
        
ReDim bits(Height * stride) ' Allocate the working buffer.


        
Dim row As Integer
        
Dim col As Integer


        
For row = 0 To Height - 1
            
For col = 0 To Width - 1


                
Dim pixel As Color
                
Dim i8BppPixel As Integer = row * stride + col


                pixel 
= BmpCopy.GetPixel(col, row)


                
Dim colorIndex As Double
                
If pixel.R = 0 And pixel.G = 0 And pixel.B = 0 Then
                    colorIndex 
= 0
                
ElseIf pixel.R > 100 And pixel.G = 0 And pixel.B = 0 Then
                    colorIndex 
= 1
                
ElseIf pixel.G > 100 And pixel.R = 0 And pixel.B = 0 Then
                    colorIndex 
= 2
                
ElseIf pixel.B > 100 And pixel.R = 0 And pixel.G = 0 Then
                    colorIndex 
= 3
                
ElseIf pixel.B = 204 And pixel.R = 204 And pixel.G = 204 Then
                    colorIndex 
= 4
                
Else
                    colorIndex 
= (nColors - 1)
                
End If


                bits(i8BppPixel) 
= CByte(colorIndex)


            
Next col
        
Next row


        
' Put the image bits definition into the bitmap.
        Dim win32 As win32api = New win32api()
        win32.CopyArrayTo(pBits, bits, Height 
* stride)
        bitmap.UnlockBits(bitmapData)


        
Return bitmap


        BmpCopy.Dispose()
        bitmap.Dispose()


    
End Function



End Class



Public Class win32api


    
<DllImport("KERNEL32.DLL", EntryPoint:="RtlMoveMemory", _
       SetLastError:
=True, CharSet:=CharSet.Auto, _
       ExactSpelling:
=True, _
       CallingConvention:
=CallingConvention.StdCall)> _
    
Public Shared Sub CopyArrayTo(<[In](), MarshalAs(UnmanagedType.I4)> ByVal hpvDest As Int32, <[In](), Out()> ByVal hpvSource() As ByteByVal cbCopy As Integer)
        
' Leave function empty
    End Sub



End Class