asp.net生成透明GIF图片的方法(2)
这是我们需要使用拷贝位图数据的办法来处理:

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

这时,我们保存了一个透明背景的gif图像!这个out3.gif,是背景透明的!
不过,如果你这时候认为大功告成的话,那可就错了,嘿嘿,这事情就是这么麻烦,请看:

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

透明色又消失了,只是这次变成了白色-_____________________-
那么为啥保存为文件就可以,而保存到流却不行呢?
事情到了这一步,只好祭出Reflector了,看看M$到底是怎么保存的,实在不行我把保存为文件的代码拷贝一份出来再往流里写
按照Reflector的说法,M$在保存文件时,使用的是RawFormat:
1public void Save(string filename)
2{
3 this.Save(filename, this.RawFormat);
4}
好吧,那我也传个 RawFormat进去
1'***我们读取上一步生成的不透明gif
2 Dim gif As New Bitmap("out1.gif")
3 PictureBox1.Image = gif
4
5 '***获取色板***
6 Dim pal = gif.Palette
7
8 For i As Integer = 0 To pal.Entries.Length - 1
9 Dim color = pal.Entries(i)
10 '***将黑色改为透明***
11 If color.R = 0 And color.G = 0 And color.B = 0 Then
12 pal.Entries(i) = color.Transparent
13 End If
14 Next
15
16 '***另外创建一个位图,格式为8位索引色**
17 Dim gif2 As New Bitmap(gif.Width, gif.Height, Imaging.PixelFormat.Format8bppIndexed)
18 '***设置修改后的调色板***
19 gif2.Palette = pal
20 '***拷贝内存
21
22 Dim src = gif.LockBits(New Rectangle(0, 0, gif.Width, gif.Height), Imaging.ImageLockMode.ReadOnly, gif.PixelFormat)
23 Dim trg = gif2.LockBits(New Rectangle(0, 0, gif2.Width, gif2.Height), Imaging.ImageLockMode.WriteOnly, gif2.PixelFormat)
24
25 Dim bits(src.Stride * src.Height - 1) As Byte
26 System.Runtime.InteropServices.Marshal.Copy(src.Scan0, bits, 0, bits.Length)
27 System.Runtime.InteropServices.Marshal.Copy(bits, 0, trg.Scan0, bits.Length)
28
29 gif.UnlockBits(src)
30 gif2.UnlockBits(trg)
31
32
33 '***按照reflector的说法,它使用的是RawFormat***
34 Dim ms As New System.IO.MemoryStream()
35 Try
36 gif2.Save(ms, gif2.RawFormat)
37 Catch ex As Exception
38 MsgBox(ex.ToString(), MsgBoxStyle.Critical)
39 Finally
40
41 gif2.Dispose()
42
43 End Try
44
45
结果如图
经过比较发现,M$的两个保存是不一样的,保存为文件时,多了一个判断!保存到文件时,M$会调用png编码器,而保存到流则不会