Sunday, February 5, 2012

VB.NET PictureBox scroll through images in a folder

Public Class Form1 Private files As List(Of FileInfo) Private currentFileIndex As Integer Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load RefreshFolder("c:\path\to\your\pictures") End Sub Private Sub backButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles backButton.Click Advance(-1) ShowCurrentFile() End Sub Private Sub forwardButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles forwardButton.Click Advance(1) ShowCurrentFile() End Sub Private Sub Advance(ByVal delta As Integer) currentFileIndex = ((currentFileIndex + files.Count) + delta) Mod files.Count End Sub Private Sub RefreshFolder(ByRef path As String) Dim di As DirectoryInfo = New DirectoryInfo(path) files = (From c In di.GetFiles() Where IsFileSupported(c) Select c).ToList() If files.Count > 0 Then currentFileIndex = 0 End If ShowCurrentFile() End Sub Private Sub ShowCurrentFile() If currentFileIndex <> -1 Then Try PictureBox1.Image = Image.FromFile(files(currentFileIndex).FullName) Catch ex As Exception ' TODO: handle exceptions gracefully Debug.WriteLine(ex.ToString) End Try End If End Sub Private Function IsFileSupported(ByRef file As FileInfo) As Boolean Return file.Extension = ".jpg" Or file.Extension = ".png" ' etc End Function End Class

How to load Image in PictureBox

Dim OpenFileDialog1 As New OpenFileDialog


With OpenFileDialog1
.CheckFileExists = True
.ShowReadOnly = False
.Filter = "All Files|*.*|Bitmap Files (*)|*.bmp;*.gif;*.jpg"
.FilterIndex = 2
If .ShowDialog = DialogResult.OK Then
' Load the specified file into a PictureBox control.
PictureBox1.Image = Image.FromFile(.FileName)
End If
End With