VB.NET 图片和BASE64互转

2019-10-29 14:27:48 浏览数 (2)

Base64是网络上最常见的用于传输8Bit字节码的编码方式之一,Base64就是一种基于64个可打印字符来表示二进制数据的方法。可查看RFC2045~RFC2049,上面有MIME的详细规范。

Base64编码是从二进制到字符的过程,可用于在HTTP环境下传递较长的标识信息。采用Base64编码具有不可读性,需要解码后才能阅读。

Base64由于以上优点被广泛应用于计算机的各个领域,然而由于输出内容中包括两个以上“符号类”字符( , /, =),不同的应用场景又分别研制了Base64的各种“变种”。为统一和规范化Base64的输出,Base62x被视为无符号化的改进版本。

图片转BASE64
代码语言:javascript复制
    ''' <summary>
    ''' 图片转BASE64
    ''' </summary>
    ''' <param name="IMG">要转换的图片</param>
    ''' <returns></returns>
    Function IMG_TO_BASE64(ByVal IMG As Image) As String
        Try
            If Not IsNothing(IMG) Then
                Dim MS As New IO.MemoryStream()
                Using BMP As New Bitmap(IMG)
                    BMP.Save(MS, Imaging.ImageFormat.Jpeg)
                    Dim BYT As Byte() = MS.GetBuffer()
                    Dim Base64_Str As String = Convert.ToBase64String(BYT)
                    Return Base64_Str
                End Using
            Else
                Return "没有要转换的图片"
            End If
        Catch ex As Exception
            Return ex.Message
        End Try
    End Function
    

BASE64转图片
代码语言:javascript复制
    ''' <summary>
    ''' BASE64转图片
    ''' </summary>
    ''' <param name="BASE_STR">BASE64数据</param>
    ''' <returns></returns>
    Function BASE64_TO_IMG(ByVal BASE_STR As String) As Image
        Try
            Dim IMG As Image
            If BASE_STR <> Nothing And Strings.Right(BASE_STR, 1) = "=" Then
                Dim BYT As Byte() = Convert.FromBase64String(BASE_STR)
                Dim MS As New IO.MemoryStream(BYT)
                IMG = Image.FromStream(MS)
                Return IMG
            Else
                Return Nothing
            End If
        Catch ex As Exception
            Return Nothing
        End Try
    End Function
    

根据字符串计算图片转换后文件大小
代码语言:javascript复制
    ''' <summary>
    ''' 根据字符串计算txt文件大小
    ''' </summary>
    ''' <param name="picstr">字符串</param>
    ''' <returns></returns>
    Function PIC_LENG(ByVal picstr As String) As Double
        Try
            Dim bytes As Byte() = System.Text.Encoding.ASCII.GetBytes(picstr)
            Dim Length As Integer = bytes.Length
            Return Math.Round(Length / 1024 / 1024, 2)
        Catch ex As Exception
            Return 0
        End Try
    End Function

0 人点赞