65.9K
CodeProject 正在变化。 阅读更多。
Home

图像批量转换器

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.85/5 (15投票s)

2010 年 9 月 24 日

CPOL

10分钟阅读

viewsIcon

51182

downloadIcon

1779

快速批量调整大小、重命名、更改格式并为多张图片添加简单特效。

引言

Image Batch Converter(以下简称“IBC”)提供了一种快速简便的方法来调整一组图片的尺寸、重新格式化、重命名、添加文本和应用特效。最初它只是一个用于处理从手机导入的图片的快速调整大小工具,但当我决定将其提交到 Code Project 时,我添加了更多功能。目前它只支持几种格式(JPG、PNG、TIF、BMP 和 GIF),但我正在研究一些第三方库以添加更多格式。

Using the Code

转换过程中使用 3 个窗口。主窗口、文本编辑窗口和转换后显示的“结果”窗口。还有一个帮助文件,解释了转换图片涉及的每一步。代码很简单——纯粹的 GDI+。

这是 Load 事件。当 IBC 启动时,它执行以下操作:

  • 将 ComboBoxes 的 SelectedIndex 属性设置为上一个会话关闭时的值(存储在 My.Settings 中)。
  • 禁用“转换”按钮,直到所有参数都设置完毕。
  • 检查 My.Settings,看上一个会话是否保存了目标目录。如果存在,IBC 将会获取它。
  • 更新 UI - 主要用于启用/禁用控件。
  Private Sub main_Load(ByVal sender As System.Object,
    ByVal e As System.EventArgs) Handles MyBase.Load
 
    'get invalid path/file chars for user's machine
    Dim invP As Char() = Path.GetInvalidPathChars()
    Dim invC As Char() = Path.GetInvalidFileNameChars()
    For Each ch As Char In invP
      invChars.Add(ch)
    Next
    For Each ch As Char In invC
      invChars.Add(ch)
    Next
 
    cmb_Format.SelectedIndex = My.Settings.selFmt
    cmb_ROT.SelectedIndex = 0
    chk_TXT.Checked = My.Settings.Txt_Enabled
    tb_Convert.Enabled = False 'enable when params are set
 
    If Directory.Exists(My.Settings.txt_DestDir) Then
      txt_DestDir.Text = My.Settings.txt_DestDir
    Else
      txt_DestDir.Text = String.Empty
    End If
 
    UpdateUI()
  End Sub

当 IBC 关闭时,它会检查以确保当前的目标目录存在。如果存在,则将其保存到 My.Settings

  Private Sub main_FormClosing(ByVal sender As Object,
    ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
 
    If Directory.Exists(txt_DestDir.Text) Then
      My.Settings.txt_DestDir = txt_DestDir.Text
    End If
 
    My.Settings.selFmt = cmb_Format.SelectedIndex
    My.Settings.Txt_Enabled = chk_TXT.Checked
 
  End Sub

转换列表

ImageBatchConverter_01.jpg

添加图片

要将图片添加到列表中,请单击工具栏中的“+”号。IBC 不创建图片集合。它只在 listView 控件中存储路径字符串。从列表中选择一张图片会在右侧的 picturebox 中显示缩略图。这是按钮 Click 事件的代码。

 Private Sub tb_Add_Click(ByVal sender As System.Object,
    ByVal e As System.EventArgs) Handles tb_Add.Click
    res = dialog_Open.ShowDialog
 
    If res = Windows.Forms.DialogResult.OK Then
      Try
        'string array of file names from dialog
        Dim tmp() As String = dialog_Open.FileNames
 
        'check against existing selections to avoid duplicates
        For l = 0 To tmp.Length - 1
          Dim tf As Boolean = False
          For zz As Integer = 0 To lvFiles.Items.Count - 1
            If lvFiles.Items.Item(zz).Text = tmp(l) Then
              tf = True 'true if duplicate found
              Exit For 'exit the checking loop
            End If
          Next
          'add image to list if no duplicate is found
          If tf = False Then
            Dim lvi As New ListViewItem(Path.GetFullPath(tmp(l)))
            lvFiles.Items.Add(lvi)
          End If
        Next
        lvFiles.AutoResizeColumn(0, ColumnHeaderAutoResizeStyle.ColumnContent)
      Catch ex As Exception
        MsgBox(ex.Message, MsgBoxStyle.Exclamation, title)
      End Try
    End If
    Try
      lvFiles.Items.Item(lvFiles.Items.Count - 1).Selected = True
    Catch ex As Exception
    End Try
 
    UpdateUI()
  End Sub

从列表中移除图片

如果您改变了主意,不想转换某张图片或一组图片,请单击工具栏中的红色“X”。这将打开一个下拉菜单,用于删除选项。您可以选择“清除所有”(Clear All),或使用 listview 中的复选框以及“清除选定项”(Clear Selected)选项。

这是从列表中清除选定图片的相应代码...

  Private Sub tb_ClearSel_Click(ByVal sender As System.Object,
    ByVal e As System.EventArgs) Handles tb_ClearSel.Click
    Try
      If lvFiles.CheckedItems.Count > 0 Then 'if the list is populated
        For l = lvFiles.CheckedIndices.Count - 1 To 0 Step -1 'get the checked items
          lvFiles.Items.RemoveAt(lvFiles.CheckedIndices(l)) 'remove the checked items
        Next
      End If
    Catch ex As Exception
      MsgBox(ex.Message, MsgBoxStyle.Exclamation, title)
    End Try
    UpdateUI() 'update the user interface
  End Sub

以及清除所有图片的相应代码...

  Private Sub tb_ClearAll_Click(ByVal sender As System.Object,
    ByVal e As System.EventArgs) Handles tb_ClearAll.Click
    Try
      lvFiles.Items.Clear()
    Catch ex As Exception
      MsgBox(ex.Message, MsgBoxStyle.Exclamation, title)
    End Try
    UpdateUI()
  End Sub

目标目录和格式

ImageBatchConverter_02.jpg

选择好图片后,就需要决定转换后的图片将写入磁盘的位置,以及它们将被转换为什么格式(如果有)。这在“目标”选项卡中完成。

选择目标目录(必需)

顶部的第一个文本框包含将存储转换后图片的目录。单击文本框右侧的文件夹按钮可打开 Windows 文件夹对话框。该对话框的“新建文件夹”选项已启用,因此您可以在需要时创建新目录。选定的目录将显示在文本框中。这是文件夹按钮 Click 事件的代码。

  Private Sub btn_DestDir_Click(ByVal sender As System.Object,
      ByVal e As System.EventArgs) Handles btn_DestDir.Click
    'A "\" is added to the end of the path if 
    'one isn't already there. It was either append
    'it here or prepend it to the file names.
    
    Try
      res = dialog_Folder.ShowDialog
      If res = Windows.Forms.DialogResult.OK Then
        myStr = dialog_Folder.SelectedPath
        If Not myStr.EndsWith("\") Then
          myStr &= "\"
        End If
        txt_DestDir.Text = myStr
 
      End If
    Catch ex As Exception
      MsgBox(ex.Message, MsgBoxStyle.Exclamation, title)
    End Try
    UpdateUI()
  End Sub

选择基本文件名(可选)

在第二个文本框中,您可以输入一个基本文件名,它将应用于所有转换后的图片,并附带一个计数器。例如,如果您输入“MyConvertedImages”并选择 .jpg 作为格式,您的文件名将是:

  • "MyConvertedImages_1.jpg"
  • "MyConvertedImages_2.jpg"

...依此类推。要保留原始文件名,只需将此文本框留空即可。如果此文本框中包含任何合法文本,它将自动用作基本文件名。它会尝试阻止 Windows 认为是非法路径字符的字符。我在此处使用了“尝试”一词,因为在 VB.net 文档中,关于我用于构建需要注意的字符集合的方法 (Path.GetInvalidPathChars) 有一个相关的注意事项。我猜它准确率非常接近 100%。

覆盖规则(必需)

IBC 提供三种“覆盖规则”来保护现有文件。它们是:

自动覆盖
IBC 会在用户没有输入的情况下覆盖同名同格式的文件。
覆盖前询问
一个 Windows 消息框将弹出,询问您是否确定要覆盖现有文件。
不覆盖
所有现有文件都将被跳过(不覆盖),无需用户输入。

通过单击“覆盖规则”组框中的一个单选按钮来选择合适的规则。

选择目标格式(可选)

如果您希望将所有选定的图片保存为一种格式(.jpg、.png 等),请首先确保选中“使用选定格式”复选框。这将启用格式控件。在“目标格式”组框中,您可以选择转换后的图片将保存的图片格式。从下拉列表中选择一个。默认值为 .jpg。如果选择了 .jpg,则旁边的滑块允许您设置图片的质量/压缩。如果您不选中格式复选框,每张图片将以其原始格式保存。

调整大小和图片特效

ImageBatchConverter_03.jpg

调整大小(可选)

IBC 提供三种调整图片大小的方法,调整大小工具位于一个小的选项卡控件中。要进行调整大小,您必须选中选项卡控件上方的“调整图片大小”复选框。要选择一种调整大小方法,请单击相应的选项卡。调整大小的方法是:

单一尺寸(第一个选项卡)
允许用户输入一个数字值,并通过单选按钮指定它是代表宽度还是高度。另一个尺寸将自动缩放以保持宽高比。
百分比(第二个选项卡)
提供一个范围从 10% 到 300% 的滑块,用于放大和缩小图片,同时保持宽高比。
绝对尺寸(第三个选项卡)
用户同时输入宽度和高度。所有图片都将调整为这些尺寸,而不考虑宽高比。

图片变换(可选)
IBC 不支持复杂的变换,但它允许您翻转、旋转图片以及将图片转换为灰度图。只需选择垂直和/或水平翻转、灰度的相应复选框,并从下拉列表中选择旋转角度。

注意: 如果您向灰度图片添加文本,文本颜色将保留。因此,您也可以有一个带有黄绿色文本的灰度图片。此外,由于文本是在其他所有操作之后绘制的,因此文本对齐方式不受翻转/旋转的影响。

使用文本工具

ImageBatchConverter_04.jpg

此功能位于“调整大小和特效”选项卡中,允许您向所有转换后的图片添加单行文本。您可以选择计算机支持的任何字体、样式和颜色。请注意,您将无法添加文本,直到所有其他选项都已设置或禁用。这是因为 IBC 在文本工具打开时提供所有图片的*转换后*预览,以便您可以看到文本在每张图片上的效果。即使您不打算添加任何文本,这也是预览图片的好方法。

首先,请确保选中“添加文本”组框中的“使用文本”复选框。如果其下方的“编辑文本”按钮已启用,则可以打开文本工具。单击该按钮以打开工具。文本工具是一个 Windows 对话框。打开时,它会自行调整大小以填满您的屏幕,以便更容易查看较大的图片。您可以根据需要调整其大小。

工具栏按钮说明

从左到右,工具栏按钮是:
保存并返回主窗口
保存文本和格式设置,并关闭文本工具。
您*必须*单击“保存”按钮,文本才能显示在您的图片中。
如果您对现有文本进行了更改,但单击了(下方的)“取消”按钮,您将丢失更改,并且将绘制之前的文本(如果存在)。
取消并返回主窗口
丢弃对文本的更改并关闭文本工具。
设置字体
设置字体(所有文本都使用一种字体和样式)。
设置文本颜色
设置颜色。文本输入区域始终是黑底白字。颜色仅在预览中更改。
文本对齐菜单
打开两个下拉菜单(水平和垂直)以设置文本在图片上的对齐方式。
水平选项为:左对齐、右对齐和居中。
垂直选项为:顶部、中部和底部。
例如,从菜单中选择“左对齐”和“底部”会将文本放置在左下角。
图片列表导航按钮(第一张、上一张、下一张、最后一张)和“x of x”显示
工作方式类似于幻灯片。这允许您逐张浏览所有图片,以查看文本的外观。请确保您的文本不会太宽而无法显示在任何一张图片上。
用于设置文本不透明度/透明度的滑块
向右滑动以增加不透明度,向左滑动以降低它。
此功能的一种用途是为您的图片创建简单的水印。

输入文本

在工具栏下方的文本框中输入。当前选定的图片(在文本框下方预览)会在您键入时更新。无需单击“预览按钮”或打开另一个窗口即可查看文本的外观。更改字体、颜色和不透明度也一样。通过工具栏箭头来回切换以查看多张图片。

窗口底部的状态栏显示当前选定图片的路径和文件名。

这是文本工具的 Load 事件处理程序。它创建一个 Image 类型的集合并加载图片。然后它会进行转换,除了文本。工具栏中的“后退”和“前进”按钮允许您逐页浏览图片。此时不会将任何图片保存到磁盘。

  Private Sub dialog_Text_Load(ByVal sender As System.Object,
    ByVal e As System.EventArgs) Handles MyBase.Load
    'size dialog to fill screen (you can also resize it manually)
    Dim wr As Rectangle = Screen.PrimaryScreen.WorkingArea
    Me.Size = New System.Drawing.Size(wr.Width - 10, wr.Height - 10)
    Me.Location = New System.Drawing.Point(5, 5)
 
    Me.Cursor = Cursors.WaitCursor
    'load images
    'if resize or grayscale options are enabled,
    'preview images will reflect those options
    imgList.Clear()
    For Each lvi As ListViewItem In main.lvFiles.Items
      Try
        'this function checks options in main window and
        'applies whatever is enabled before adding to the 
        'collection. Note that format conversions are ignored
        'so you won't see JPEG compression results here.
 
        Dim newBMP As Bitmap = PrepPreviewImage(Image.FromFile(lvi.Text))
        imgList.Add(newBMP)
 
 
      Catch ex As Exception
        MsgBox(ex.ToString, MsgBoxStyle.Exclamation, main.title)
      End Try
    Next
 
    SourceImage = imgList(0) 'loads initial img from list
    index = 0 : imgCnt = main.lvFiles.Items.Count 'for nav buttons
    txt_Text.Font = My.Settings.TxtFont
    sldr_Opc.Value = My.Settings.Opacity
    lbl_Opc.Text = sldr_Opc.Value.ToString
    BrushColor = My.Settings.txt_Color 'triggers creation of new brush when changed
    TextBrush = New SolidBrush(My.Settings.txt_Color) 'brush to draw text
    txt_Text.Text = My.Settings.TxtString 'text to draw
 
    'get text alignment
    'cumbersome code - needs improvement
    'sets alignment menu items and text aligment properties
    For Each tsmi As ToolStripMenuItem In tb_HAlign.DropDownItems
      tsmi.Checked = False
    Next
    For Each tsmi As ToolStripMenuItem In tb_VAlign.DropDownItems
      tsmi.Checked = False
    Next
    Select Case My.Settings.alignH
      Case 1
        alignh_Left.Checked = True
        HTextAlign = TextAlignH.Left
      Case 2
        alignh_Center.Checked = True
        HTextAlign = TextAlignH.Center
      Case 3
        alignh_Right.Checked = True
        HTextAlign = TextAlignH.Right
    End Select
 
    Select Case My.Settings.alignV
      Case 1
        alignV_Top.Checked = True
        VTextAlign = TextAlignV.Top
      Case 2
        alignv_Middle.Checked = True
        VTextAlign = TextAlignV.Middle
      Case 3
        alignv_Bottom.Checked = True
        VTextAlign = TextAlignV.Bottom
    End Select
    '-----------------end textalign-------------------
 
    UpdateImage()
    UpdateUI()
    Me.Cursor = Cursors.Default
 
  End Sub

任何时候您执行了会更改预览图片的操作(键入、更改字体或颜色、或对齐方式),图片当然需要更新。因此,文本框的 TextChanged 事件,以及字体、颜色和对齐菜单项的 Click 事件都会调用 UpdateImage Sub。

  Private Sub UpdateImage()
    'any time a redraw operation is needed
 
    Try
      'default in case color/brush is not set
      If TextBrush Is Nothing Then
        BrushColor = Color.FromArgb(sldr_Opc.Value, 240, 240, 240)
        TextBrush = New SolidBrush(BrushColor)
      End If
 
      'reset display image (img)
      img = New Bitmap(SourceImage.Width, SourceImage.Height)
      Dim g As Graphics = Graphics.FromImage(img)
      g.DrawImage(SourceImage, 0, 0)
 
 
      If txt_Text.TextLength > 0 Then 'if text is present, draw it
 
        'measure the string (for alignment pruposes)
        rectSize = g.MeasureString(TextForImages, txt_Text.Font, New PointF(0, 0),
            StringFormat.GenericTypographic)
 
        'set x & y values according to alignment options
        Select Case HTextAlign
          Case TextAlignH.Center
            x = (img.Width / 2) - (rectSize.Width / 2)
          Case TextAlignH.Left
            x = 2
          Case TextAlignH.Right
            x = (img.Width - rectSize.Width) - 2
        End Select
 
        Select Case VTextAlign
          Case TextAlignV.Bottom
            y = (img.Height - rectSize.Height) - 2
          Case TextAlignV.Middle
            y = (img.Height / 2) - (rectSize.Height / 2)
          Case TextAlignV.Top
            y = 2
        End Select
 
        'draw text on display image
        Dim dPoint As New Point(x, y)
        g.TextRenderingHint = TextRenderingHint.AntiAlias
        g.DrawString(TextForImages, txt_Text.Font, TextBrush, dPoint,
            StringFormat.GenericTypographic)
      End If
 
      'display image in picbox
      picbox.Image = img
 
    Catch ex As Exception
      MsgBox(ex.ToString)
    End Try
  End Sub

ImageBatchConverter_05.jpg

转换图片

在所有必需的选项(目标目录等)设置好之前,“转换”按钮将保持禁用状态。一旦您设置了所有必需的选项,请单击工具栏中的“转换”(齿轮)按钮开始该过程。过程完成后,将打开一个对话框,详细说明结果。

可能的结果有:

  • 成功(SUCCESS),如果图片已转换。
  • 失败(FAILED),如果未转换。
  • 文件未找到(FILE NOT FOUND)(说实话,有时文件会消失)。
  • 已跳过(SKIPPED),如果由于覆盖规则而被阻止。

当您关闭结果对话框时,目标目录将打开,以便您可以看到图片。

注意: 如果图片文件已损坏但仍设法进入列表,则很可能在结果对话框中收到“文件未找到”或“失败”的消息。

这是“转换”按钮的 click 事件代码。

Private Sub tb_Convert_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
  Handles tb_Convert.Click
 
    'reset results dialog and file name counter for new conversion
    dialog_Results.lb_Results.Items.Clear()
    nameCnt = 0
 
    'loop through the selected files
    'the list doesn't store the images, just the 
    'paths to the images.
    For l = 0 To lvFiles.Items.Count - 1
      Try
        fileNameStr = CreateFileName() 'the new path for the converted image
 
        'overwrite rules...
        'checks to see which overwrite option is chosen
        'this is where messages in results dialog are created
        'if a file already exists, acts appropriately according
        'to the selected overwrite rule
        If File.Exists(fileNameStr) Then
          If rad_OvrNO.Checked Then
            dialog_Results.lb_Results.Items.Add(fileNameStr & " : SKIPPED - No Overwrite")
            dialog_Results.lb_Results.Items.Add("")
            Exit Try
 
          ElseIf rad_OvrPrompt.Checked Then
            msg = "The image," & Chr(10) _
            & fileNameStr & Chr(10) _
            & "already exists. Overwrite?"
            res = MsgBox(msg, MsgBoxStyle.YesNo, title)
            If res = Windows.Forms.DialogResult.No Then
              dialog_Results.lb_Results.Items.Add(
                  fileNameStr & " : SKIPPED - No Overwrite")
              dialog_Results.lb_Results.Items.Add("")
              Exit Try
            End If
 
          ElseIf rad_OvrAuto.Checked Then
            'no action necessary
          End If 'radio buttons
        End If 'File.Exists
        '---------------------------------------
 
        'create a new image from the current original
        tmpBMP = System.Drawing.Image.FromFile(lvFiles.Items.Item(l).Text)
 
 
        'get the selected extension from the format combobox
        Dim destExt As String = cmb_Format.SelectedItem.ToString
        'the selected extension from above decides the 
        'ImageFormat object returned from SetFormat()
 
        'set extension according to state of chk_Reformat
        If chk_Reformat.Checked Then
          imgFormat = SetFormat(destExt)
        Else
          imgFormat = SetFormat(Path.GetExtension(lvFiles.Items.Item(l).Text))
        End If
 
 
 
        Dim imgSize As Size = ResizeImage(tmpBMP.Size)
 
        Dim newBMP As New Bitmap(imgSize.Width, imgSize.Height)
        Dim g As Graphics = Graphics.FromImage(newBMP)
        g.DrawImage(tmpBMP, New Rectangle(0, 0, imgSize.Width, imgSize.Height))
        tmpBMP.Dispose()
 
        'image f/x
        'flip
        If chk_FlipH.Checked Then
          newBMP.RotateFlip(RotateFlipType.RotateNoneFlipX)
        End If
 
        If chk_FlipV.Checked Then
          newBMP.RotateFlip(RotateFlipType.RotateNoneFlipY)
        End If
 
        'rotate
        If cmb_ROT.SelectedIndex > 0 Then
          Select Case cmb_ROT.SelectedIndex
            Case 1
              newBMP.RotateFlip(RotateFlipType.Rotate90FlipNone)
            Case 2
              newBMP.RotateFlip(RotateFlipType.Rotate180FlipNone)
            Case 3
              newBMP.RotateFlip(RotateFlipType.Rotate270FlipNone)
          End Select
        End If
 
        'grayscale
        If chk_Gray.Checked Then
          newBMP = GrayScale(newBMP)
        End If
 
        'draw text (does the math here for image alignment - based on image
        'size and string size)
        'size of text is stored in My.Settings
        If chk_TXT.Checked AndAlso My.Settings.TxtString.Length > 0 Then
          Dim sb As New SolidBrush(My.Settings.txt_Color)
          Select Case My.Settings.alignH
            Case 1
              x = 2
            Case 2
              x = (newBMP.Width / 2) - (My.Settings.txt_Rsize.Width / 2)
            Case 3
              x = (newBMP.Width - My.Settings.txt_Rsize.Width) - 2
          End Select
 
          Select Case My.Settings.alignV
            Case 1
              y = 2
            Case 2
              y = (newBMP.Height / 2) - (My.Settings.txt_Rsize.Height / 2)
            Case 3
              y = (newBMP.Height - My.Settings.txt_Rsize.Height) - 2
          End Select
 
          Dim tgr As Graphics = Graphics.FromImage(newBMP)
          tgr.DrawString(My.Settings.TxtString, My.Settings.TxtFont, sb, x, y,
              StringFormat.GenericTypographic)
          'dialog_Preview.PictureBox1.Image = newBMP
          'dialog_Preview.ShowDialog()
 
        End If
 
 
        'save image
        If imgFormat.Equals(ImageFormat.Jpeg) Then
          Dim jgpEncoder As ImageCodecInfo = GetEncoder(ImageFormat.Jpeg)
          Dim myEncoder As Encoder = Encoder.Quality
          Dim myEncoderParameters As New EncoderParameters(1)
          Dim myEncoderParameter As New EncoderParameter(myEncoder, sldr_Quality.Value)
          myEncoderParameters.Param(0) = myEncoderParameter
          newBMP.Save(fileNameStr, jgpEncoder, myEncoderParameters)
 
        Else
          newBMP.Save(fileNameStr, imgFormat)
        End If
 
        dialog_Results.lb_Results.Items.Add(fileNameStr & " : SUCCESS!")
        dialog_Results.lb_Results.Items.Add("")
      Catch ex As Exception
        MsgBox(ex.ToString)
        If Not File.Exists(fileNameStr) Then
          dialog_Results.lb_Results.Items.Add(fileNameStr & " : FILE NOT FOUND")
          dialog_Results.lb_Results.Items.Add("")
        Else
          dialog_Results.lb_Results.Items.Add(fileNameStr & " : ERROR")
          dialog_Results.lb_Results.Items.Add("")
        End If
 
      End Try
 
    Next l
    dialog_Results.ShowDialog()
    
    'Open the destination folder
    Try
      System.Diagnostics.Process.Start(txt_DestDir.Text)
    Catch ex As Exception
      MsgBox("Could not open destination directory.", MsgBoxStyle.Exclamation, title)
    End Try
 
  End Sub

Convert sub 调用了几个函数来完成操作。

如果您选择了调整大小选项,此函数将获取每张原始图片的尺寸(ByVal s As Size)并应用该选项。然后它返回新的尺寸。如果您选择不调整大小,它会将原始尺寸返回给 Convert sub。

  Friend Function ResizeImage(ByVal s As Size)
 
    'If ResizeImage checkbox is unchecked, use existing size
    If Not chk_Resize.Checked Then
      Return s
    End If
 
    'resize according to selected option in tab control
    Try
      Select Case tab_Resize.SelectedIndex
        Case 0  'one dimension
          If rad_Width.Checked Then
            pctW = Val(txt_Dim.Text) / s.Width
            newW = Val(txt_Dim.Text)
            newH = s.Height * pctW
 
          ElseIf rad_Height.Checked Then
            pctH = Val(txt_Dim.Text) / s.Height
            newW = s.Width * pctH
            newH = Val(txt_Dim.Text)
          End If
 
        Case 1  'percentage
          pctSldr = sldr_Size.Value / 100
          newW = s.Width * pctSldr
          newH = s.Height * pctSldr
 
        Case 2  'absolute size
          newW = Val(txt_AbsWidth.Text)
          newH = Val(txt_AbsHeight.Text)
      End Select
 
    Catch ex As Exception
      'returning a zero size will trigger a warning in the convert sub
      Return New Size(0, 0)
    End Try
 
    Return New Size(newW, newH)
  End Function

如果您选择了所有转换后图片的通用格式...

  Private Function SetFormat(ByVal ext As String) As ImageFormat
    'if changing format, this returns the correct ImageFormat object
    'based upon the chosen extension in the format combobox
 
    Select Case ext
      Case ".jpg"
        Return ImageFormat.Jpeg
 
      Case ".gif"
        Return ImageFormat.Gif
 
      Case ".bmp"
        Return ImageFormat.Bmp
 
      Case ".png"
        Return ImageFormat.Png
 
      Case ".tif"
        Return ImageFormat.Tiff
 
      Case Else
        MsgBox(msg, MsgBoxStyle.Information, "Error")
        Return Nothing
    End Select
  End Function

这会为每张图片创建一个新的路径和文件名...

  Private Function CreateFileName()
    Dim fStr As String = String.Empty
    'get directory path
 
    'fStr is the text in the destination directory textbox
    '
    fStr = txt_DestDir.Text
    If Not fStr.EndsWith("\") Then
      fStr &= "\"
    End If
 
    'nameCnt is the variable that increments new file names (myFile_1.jpg, myFile_2.jpg...)
    If txt_FileName.TextLength > 0 Then
      'if creating new file names...
      nameCnt += 1
      fStr &= txt_FileName.Text & "_" & nameCnt.ToString
    Else
      'if using original file names...
      fStr &= Path.GetFileNameWithoutExtension(lvFiles.Items.Item(l).Text)
    End If
 
    If chk_Reformat.Checked Then
      'if changing formats...
      fStr &= cmb_Format.SelectedItem.ToString
    Else
      'if not changing formats...
      fStr &= Path.GetExtension(lvFiles.Items.Item(l).Text)
    End If
    Return fStr
  End Function

如果转换为 JPG,这会返回编码器,以便您可以设置压缩。

  Private Function GetEncoder(ByVal format As ImageFormat) As ImageCodecInfo
    'when saving to JPEG, gets the encoder so you can set compression
    Dim codecs As ImageCodecInfo() = ImageCodecInfo.GetImageDecoders()
    For Each codec As ImageCodecInfo In codecs
      If codec.MimeType.Equals("image/jpeg") Then
        Return codec
      End If
    Next codec
    Return Nothing
  End Function

如果转换为灰度图...

  Friend Function GrayScale(ByVal img As Image)
    'this function based on code from BobPowell.net
    '(because his works a lot better than mine did)
    '(http://www.bobpowell.net/grayscale.htm)
 
    Try
      Dim bm As Bitmap = New Bitmap(img.Width, img.Height)
      Dim g As Graphics = Graphics.FromImage(bm)
 
      Dim cm As ColorMatrix = New ColorMatrix(New Single()() _
                 {New Single() {0.3, 0.3, 0.3, 0, 0}, _
                New Single() {0.59, 0.59, 0.59, 0, 0}, _
                New Single() {0.11, 0.11, 0.11, 0, 0}, _
                New Single() {0, 0, 0, 1, 0}, _
                New Single() {0, 0, 0, 0, 1}})
 
      Dim ia As ImageAttributes = New ImageAttributes()
      ia.SetColorMatrix(cm)
      g.DrawImage(img, New Rectangle(0, 0, img.Width, img.Height), 0, 0, img.Width,
          img.Height, GraphicsUnit.Pixel, ia)
      g.Dispose()
      Return bm
 
    Catch ex As Exception
      MsgBox(ex.ToString, MsgBoxStyle.Exclamation, title)
      Return Nothing
    End Try
  End Function

大概就是这些了。转换过程运行得相当快,即使图片数量很多。如果您发现任何错误,请在此发布消息,我将尽快处理。我希望您觉得 IBC 有用且令人愉快。

关注点

我花了一些时间仔细思考如何最好地创建要包含在项目中的帮助文件。我最终创建了简单的 HTML 文档并将它们存储在 My.Resources 中。帮助应用程序由一个SplitContainer控件组成,右侧面板有一个 WebBrowser 控件来显示文本。左侧面板包含一个 TableLayoutPanel,其中包含 LinkLabels,代表帮助文件中的每个主题。单击链接,相应的 HTML 文件将被写入浏览器DocumentText 属性。这不能称为完美的解决方案,但它有一个好处,就是对眼睛很友好。我很想知道别人对此的看法。

历史

首次发布于 2010 年 9 月 24 日。

© . All rights reserved.