订阅专栏
版权声明:本文为博主原创文章,转载请在显著位置标明本文出处以及作者网名,未经作者允许不得用于商业目的。
base64编码常用于MIME的电子邮件,IE保存的Mht格式网页,也是用的base64编码。
详细请查看查看RFC2045~RFC2049,上面有MIME的详细规范,这里谈谈在vb.net中的实现。
设计界面,包含3个按钮、1个文本框和1个webbrowser控件:
现在form窗体类添加窗体级变量,用于存储图片格式,在下一节中我们会将编码的图片显示出来:
Dim imgFormat As String
图片base64编码的代码:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim filename As String = ""
Dim ofDialog As New OpenFileDialog()
With ofDialog
.Filter = "图片文件|*.jpg;*.png;*.gif"
.FileName = ""
If .ShowDialog = DialogResult.OK Then
filename = .FileName
Else
Exit Sub
End If
End With
Dim bmp As New Bitmap(filename)
Select Case bmp.RawFormat.Guid
Case Imaging.ImageFormat.Jpeg.Guid
imgFormat = "jpeg"
Case Imaging.ImageFormat.Gif.Guid
imgFormat = "gif"
Case Imaging.ImageFormat.Png.Guid
imgFormat = "png"
Case Else
MessageBox.Show("不是指定的格式")
Exit Sub
End Select
Dim ms As New System.IO.MemoryStream()
bmp.Save(ms, bmp.RawFormat)
Dim base64String As String
Dim base64Bytes() As Byte
Dim base64Length As Integer
base64Length = ms.Length
ReDim base64Bytes(base64Length - 1)
ms.Position = 0
ms.Read(base64Bytes, 0, base64Length)
ms.Close()
base64String = Convert.ToBase64String(base64Bytes)
TextBox1.Text = base64String
End Sub
base64还原图片的代码:
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim filename As String
Dim sfDialog As New SaveFileDialog()
With sfDialog
.Filter = "图片文件|*." & IIf(imgFormat = "jpeg", "jpg", imgFormat)
.FileName = ""
If .ShowDialog = DialogResult.OK Then
filename = .FileName
Else
Exit Sub
End If
End With
Dim fromBase64Bytes() As Byte
fromBase64Bytes = Convert.FromBase64String(TextBox1.Text)
Dim ms As New System.IO.MemoryStream(fromBase64Bytes)
Dim bmp As New Bitmap(ms)
Dim saveimgformat As Imaging.ImageFormat
Select Case imgFormat
Case "jpeg"
saveimgformat = Imaging.ImageFormat.Jpeg
Case "png"
saveimgformat = Imaging.ImageFormat.Png
Case "gif"
saveimgformat = Imaging.ImageFormat.Gif
Case Else
MessageBox.Show("不是指定的格式")
Exit Sub
End Select
bmp.Save(filename, saveimgformat)
bmp.Dispose()
End Sub
注意,随着图片越大,转换会越慢。
由于.net平台下C#和vb.NET很相似,本文也可以为C#爱好者提供参考。
学习更多vb.net知识,请参看 vb.net教程 目录
版权声明:本文为CSDN博主「VB.Net」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。