Search code examples
vb.netthumbnailspicturebox

VB.NET get any file thumbnail in picturebox as an image image programmatically


I am struggling to find a way on how to get any file thumbnail into my userforms picturebox (The image visible in windows explorer) using visual basic.

I have only found how to do that for image files

 Dim image As Image = New Bitmap(file) 'File is a full path to the file

 'Resize and preserve aspect ratio
  Dim Ratio As Double = CDbl(image.Width / image.Height)
  Dim H As Integer = 150
  Dim W As Integer = CInt(H / Ratio)

  'Set image
  .Image = image.GetThumbnailImage(H, W, callback, New IntPtr())

But it doesn't work for any other type of files.

Could someone, please,help me with this code?


Solution

  • Try the following which is adapted from C# get thumbnail from file via windows api

    Download/install NuGet package Microsoft-WindowsAPICodePack-Shell

    Imports Microsoft.WindowsAPICodePack.Shell
    Imports System.IO
                                ...
    
    Private Function GetThumbnailBytes(filename As String, desiredHeight As Integer) As Byte()
        Dim thumbnailBytes As Byte()
    
        Using sfile As ShellFile = ShellFile.FromFilePath(filename)
            Dim thumbBmp As Bitmap = sfile.Thumbnail.ExtraLargeBitmap
    
            'compute new width
            Dim Ratio As Double = CDbl(thumbBmp.Width / thumbBmp.Height)
            Dim height As Integer = desiredHeight
            Dim width As Integer = CInt(height / Ratio)
    
            'resize
            Using resizedBmp As Bitmap = New Bitmap(thumbBmp, width, height)
                Using ms As MemoryStream = New MemoryStream()
                    resizedBmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg)
                    thumbnailBytes = ms.ToArray()
                End Using
            End Using
        End Using
    
        Return thumbnailBytes
    End Function
    
    Private Sub btnRun_Click(sender As Object, e As EventArgs) Handles btnRun.Click
    
        Using ofd As OpenFileDialog = New OpenFileDialog()
            If ofd.ShowDialog() = DialogResult.OK Then
    
                Dim thumbnailBytes = GetThumbnailBytes(ofd.FileName, 60)
                Dim thumbnail = GetThumbnail(ofd.FileName, 60)
    
                Using ms As MemoryStream = New MemoryStream(thumbnailBytes)
                    PictureBox1.Image = Image.FromStream(ms)
                    PictureBox1.SizeMode = PictureBoxSizeMode.StretchImage
                End Using
            End If
        End Using
    End Sub
    

    Resources