编码自动检测,可自由设置字体,颜色
转换当前文件夹下所有txt,转换完成的Png放到png文件夹
txt2png.ps1- cls
- [void][System.Reflection.Assembly]::LoadWithPartialName('System.Drawing')
-
- #判断文件编码的函数
- function Get-FileCoder($file_path){
- $bytes = [System.IO.File]::ReadAllBytes($file_path)
- if($bytes[0] -eq 0xff -and $bytes[1] -eq 0xfe){ return 'utf-16_le' }
- if($bytes[0] -eq 0xfe -and $bytes[1] -eq 0xff){ return 'utf-16_be' }
- if($bytes[0] -eq 0xef -and $bytes[1] -eq 0xbb -and $bytes[2] -eq 0xbf){ return 'utf-8_bom' }
- $index = 0; $bu8 = $false
- while($index -lt $bytes.Count){
- $one = 0
- for($i = 0; $i -lt 8; $i++){
- if(($bytes[$index] -band (0x80 -shr $i)) -eq 0){ break; }
- ++$one
- }
- if($one -eq 0){
- ++$index
- } else {
- if($one -eq 1){ return 'ansi' }
- $bu8 = $true
- for($i = 0; $i -lt $one-1; $i++){
- ++$index
- if(($bytes[$index] -band 0x80) -ne 0x80){ return 'ansi' }
- }
- ++$index
- }
- }
- if($bu8){return 'utf-8'} else { return 'ansi'}
- }
-
- #字体
- $font_size = 20
- $font_family = 'Courier New'
- $font = New-Object 'System.Drawing.Font'(([System.Drawing.FontFamily]::Families | Where-Object { $_.Name -eq $font_family } | Select-Object -First 1),$font_size)
- #画刷
- $black_brush = New-Object 'System.Drawing.SolidBrush'([System.Drawing.Color]::Black)
- $white_brush = New-Object 'System.Drawing.SolidBrush'([System.Drawing.Color]::White)
-
-
- #遍历txt
- [void][System.IO.Directory]::CreateDirectory('png')
- Get-ChildItem '*.txt' | foreach {
- Write-Host $_.FullName
- #读取文字
- $cp = Get-FileCoder -file_path $_.FullName
- Write-Host $cp
- $lines = $null
- if($cp -eq 'utf-8'){
- $lines = Get-Content -Encoding UTF8 -Path $_.FullName
- } elseif ( $cp -eq 'ansi'){
- $lines = Get-Content -Encoding Default -Path $_.FullName
- } elseif ( $cp -eq 'utf-16_le'){
- $lines = Get-Content -Encoding Unicode -Path $_.FullName
- } elseif ( $cp -eq 'utf-16_be'){
- $lines = Get-Content -Encoding BigEndianUnicode -Path $_.FullName
- } elseif ( $cp -eq 'utf-8_bom'){
- $lines = Get-Content -Encoding UTF8 -Path $_.FullName
- }
- #计算宽高
- $max_c = 0
- $lines | foreach {
- $len = ([System.Text.UnicodeEncoding]::Unicode.GetBytes($_)|Where-Object{ $_ -ne 0 }).Count
- if($max_c -lt $len){ $max_c = $len}
- }
- $w = $max_c*$font_size+20
- $h = $lines.Count*2*$font_size+20
- #创建图片和画布
- $bmp = New-Object 'System.Drawing.Bitmap'($w,$h)
- $g = [System.Drawing.Graphics]::FromImage($bmp)
- #画白色背景
- $g.FillRectangle($white_brush,0,0,$w,$h)
- #画文字
- $y0 = 5
- $x0 = 5
- $lines | foreach {
- $g.DrawString($_,$font,$black_brush,$x0,$y0)
- $y0 += $font_size*2
- }
- #保存图片
- [void]$g.Save()
- $bmp.Save('.\png\' + $_.BaseName + '.png',[System.Drawing.Imaging.ImageFormat]::Png)
- '.\png\' + $_.BaseName + '.png'
- '------------------------'
- }
- pause
复制代码
|