vb.net 教程 20-2 base64图片转换 1

前端之家收集整理的这篇文章主要介绍了vb.net 教程 20-2 base64图片转换 1前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

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,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 教程 目录

原文链接:https://www.f2er.com/vb/256410.html

猜你在找的VB相关文章