Sub Txt2Jpg(inFileFullName As String, outFileFullName As String) '转换过程
Dim a() As Byte, b() As Byte 'a 原始文件字节数组 b 生成的jpg字节数组
Dim i As Long, j As Long
Dim FileNo As Long '文件号
FileNo = FreeFile
Open inFileFullName For Binary As FileNo '打开文件
ReDim a(LOF(FileNo) - 1) '调整a的大小
Get FileNo, , a '获取文件内容
Close FileNo
ReDim b((UBound(a) + 1) * 3 / 4 - 1) '调整b的大小,b的字节数为原始文件的 3/4 4*6=3*8
For i = LBound(a) To UBound(a) '根据对照表将字符ASCII转为0-64
If a(i) >= 65 And a(i) <= 90 Then
a(i) = a(i) - 65
ElseIf a(i) >= 97 And a(i) <= 122 Then
a(i) = a(i) - 71
ElseIf a(i) >= 48 And a(i) <= 57 Then
a(i) = a(i) + 4
ElseIf a(i) = 43 Then
a(i) = 62
ElseIf a(i) = 47 Then
a(i) = 63
End If
Next
For i = LBound(a) To UBound(a) Step 4 '核心转换代码,每4个原始字节转换为3个jpg字节 4个字节每个字节去掉前面两位0,剩下4个6位共24位,按每8位划分为一个新的jpg字节
'原理图示如工作表
j = (i \ 4) * 3 'b下标转换
b(j) = a(i) * 4 + a(i + 1) \ 16 '位移处理生成新的jpg字节
b(j + 1) = (a(i + 1) Mod 16) * 16 + a(i + 2) \ 4
b(j + 2) = (a(i + 2) Mod 4) * 64 + a(i + 3)
Next
FileNo = FreeFile
Open outFileFullName For Binary As FileNo '将jpg字节写入文件
Put FileNo, , b
Close FileNo
End Sub
Sub Main() '适用于VBA的输入输出设定过程,可以批处理文件(一次选取多个需要处理的文件)
Dim vFileDLG As FileDialog
Dim vSeled As Variant
Dim strPath As String
Set vFileDLG = Application.FileDialog(msoFileDialogFolderPicker)
With vFileDLG
.Title = "Eersoft-选择输出文件保存的文件夹"
getpath: If .Show = -1 Then
strPath = .SelectedItems.Item(1)
strPath = strPath & IIf(Right$(strPath, 1) = "", "", "")
Else
If MsgBox("没有选择输出文件存放的文件夹,需要重新选取吗?如果不重新选取程序将退出。", vbQuestion + vbYesNo, "Eersoft-选取输出文件存放文件夹") = vbYes Then
GoTo getpath
Else
Exit Sub
End If
End If
End With
Set vFileDLG = Application.FileDialog(msoFileDialogFilePicker)
With vFileDLG
.Title = "Eersoft-选择需要转换的文件"
.Filters.Add "文本文件", "*.txt"
getfile: If .Show = -1 Then
For Each vSeled In .SelectedItems
Call Txt2Jpg(CStr(vSeled), strPath & getNameForFullName(CStr(vSeled)) & ".jpg")
Next vSeled
MsgBox "所有文件已经转换完成。", vbInformation + vbOKOnly, "Eersoft-转换完成"
Else
If MsgBox("没有选择需要转换的文件,需要重新选取吗?如果不重新选取程序将退出。", vbQuestion + vbYesNo, "Eersoft-选取需要转换的文件") = vbYes Then
GoTo getfile
Else
Exit Sub
End If
End If
End With
Set vFileDLG = Nothing
End Sub
Function getNameForFullName(strPath As String) As String '根据带路径的全名获取文件短名称(不带扩展名)
Dim srr
srr = Split(strPath, "")
getNameForFullName = Split(srr(UBound(srr)), ".")(0)
End Function