Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
 
MSDN Visual Basic Community
 
 
 
 
 
TitleLoad a picture so it doesn't lock the picture file in VB .NET
DescriptionThis example shows how to load a picture so it doesn't lock the picture file in VB .NET.
Keywordsload picture, Bitmap, lock, lock file, sharing, file sharing
CategoriesGraphics, VB.NET, Files and Directories
 
When you create a Bitmap from a file, VB .NET locks the file for some reason (possibly so it can read the file again later if it needs to refresh the image).

To work around this problem, load the image into a Bitmap, create a new Bitmap and copy the image into it, and dispose of the original Bitmap. This example loads a Bitmap either the straightforward way or using this technique.

 
Private m_Bitmap As Bitmap

Private Sub btnLoad_Click(ByVal sender As System.Object, _
    ByVal e As System.EventArgs) Handles btnLoad.Click
    ' Get the file name.
    Dim file_name As String = Application.StartupPath
    file_name = file_name.Substring(0, _
        file_name.LastIndexOf("\"))
    file_name &= "\vbgp.jpg"

    If radLocked.Checked Then
        LoadLocked(file_name)
    Else
        LoadUnlocked(file_name)
    End If
End Sub

' Load the image into a Bitmap 
' and set the PictureBox's
' Image property to the Bitmap.
Private Sub LoadLocked(ByVal file_name As String)
    If Not (m_Bitmap Is Nothing) Then m_Bitmap.Dispose()

    m_Bitmap = New Bitmap(file_name)
    PictureBox1.Image = m_Bitmap
End Sub

' Load the image into a Bitmap, clone it,
' and set the PictureBox's 
' Image property to the Bitmap.
Private Sub LoadUnlocked(ByVal file_name As String)
    If Not (m_Bitmap Is Nothing) Then m_Bitmap.Dispose()

    Dim bm As New Bitmap(file_name)
    m_Bitmap = New Bitmap(bm.Width, bm.Height)
    Dim gr As Graphics = Graphics.FromImage(m_Bitmap)
    gr.DrawImage(bm, 0, 0)
    bm.Dispose()
    PictureBox1.Image = m_Bitmap
End Sub
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated