Disposing dynamically created picturebox to release file lock? - vb.net

I am trying to release the file lock on some images so i can move them into an archive folder.
The program loops through the images and adds pictureboxes to a flowlayout panel. After the operation is completed i dispose of the flowlayout panel, and then archive the files.
It is my understanding that disposing the panel will dispose of the picture boxes inside of it, however when i try the move operation i get a IOException Access Denied.
Code:
Dim ImagesInFolder As New List(Of Image)()
For Each JPEGImages As String In Directory.GetFiles(ExportDir.FullName, "*.jpg")
ImagesInFolder.Add(Image.FromFile(JPEGImages))
Next
Dim x As Integer = 0
Dim y As Integer = 0
For i As Integer = 0 To ImagesInFolder.Count - 1
Dim _image As New PictureBox()
_image.Location = New Point(x, y)
x += 50
_image.Image = ImagesInFolder(i)
_image.Size = New Size(50, 50)
_image.SizeMode = PictureBoxSizeMode.StretchImage
FlowLayoutPanel1.Controls.Add(_image)
Next
Later in the application:
FlowLayoutPanel1.Dispose()
Directory.Move(CurrentFolder, ArchiveFolder)

The problem is Because of loading image using Image.FromFile(file).
When you load image using Image.FromFile(file) the file will be locked.
To avoid locking file you can load your images using Image.FromStream.
Code:
Dim filePath = "path to your image file"
Dim contentBytes = File.ReadAllBytes(filePath)
Dim memoryStream As New MemoryStream(contentBytes)
Dim image= Image.FromStream(memoryStream)
YourPictureBox.Image = image

Related

VB.NET Display Image in PictureBox from Binary DB Value

I am trying to take a database binary entry where images are stored and convert it back to display in a PictureBox on a Windows Form. I have looked around and tried to piece a couple methods together however i get no errors and also no image in the PictureBox when trying to use the below code.
Dim MyByte = varReader("BinaryData")
Dim MyImg As Image
If MyByte IsNot Nothing Then
MyImg = bytesToImage(MyByte)
PictureBox1.Image = MyImg
End If
Public Function bytesToImage(ByVal byteArrayIn As Byte()) As Image
Dim ms As MemoryStream = New MemoryStream(byteArrayIn)
Dim returnImage As Image = Image.FromStream(ms)
Return returnImage
End Function
I know the Binary data is good as i have a different piece of code that has created it in the first place to store in the DB and the image displays fine on the Website which uses this data.
Any help or advice where i have gone wrong would be much appreciated!!
Many Thanks
EDITED::
The database column holding the information is varbinary(MAX)
This is the code i use to convert the image to the binary (I won't include the DB update part as this is just a basic update to the DB Column)
Dim varPictureBinary As Byte()
Dim filePath As String = "ImageFilePath"
Dim fStream As FileStream = New FileStream(filePath, FileMode.Open, FileAccess.Read)
Dim br As BinaryReader = New BinaryReader(fStream)
Dim fileInfo As FileInfo = New FileInfo(filePath)
varPictureBinary = br.ReadBytes(fileInfo.Length)
I then want to take a binary entry from this column and turn it back to an image and display it in a picture box in my program.

Resizing multiple images and saving them to a separate folder

I need to resize and compress 200 images that I have stored in a folder.
I am getting these images in a list using this code that I got from another question:
Dim dir = New IO.DirectoryInfo("C:\\Users\\Charbel\\Desktop\\Images")
Dim images = dir.GetFiles("*.jpg", IO.SearchOption.AllDirectories).ToList
Dim pictures As New List(Of PictureBox)
For Each img In images
Dim picture As New PictureBox
picture.Image = Image.FromFile(img.FullName)
pictures.Add(picture)
Next
Now, I need to compress and reduce each image to (500x374) and then save them in another folder on my PC.
Well, let me first point out a couple of points about your code:
PictureBox doesn't serve any purpose here. You shouldn't create a PictureBox to use the Image.
Always remember to dispose the Image object (e.g., by wrapping it in a Using block) so you don't run into memory issues.
Unlike C#, VB.NET doesn't require escaping the \ character, therefore, you can write your path like this "C:\Users...".
Now, for resizing the image, you can simply create an instance of the Bitmap class with the constructor that takes an image and a size argument: Bitmap(Image, Size) or Bitmap(Image, Int32, Int32).
Here:
Dim sourcePath As String = "C:\Users\Charbel\Desktop\Images"
Dim outputPath As String = "C:\Users\Charbel\Desktop\Images\Resized"
IO.Directory.CreateDirectory(outputPath)
Dim dir = New IO.DirectoryInfo(sourcePath)
Dim files As IO.FileInfo() = dir.GetFiles("*.jpg", IO.SearchOption.AllDirectories)
For Each fInfo In files
Using img As Bitmap = Image.FromFile(fInfo.FullName)
Using resizedImg As New Bitmap(img, 500, 374)
resizedImg.Save(IO.Path.Combine(outputPath, fInfo.Name),
Imaging.ImageFormat.Jpeg)
End Using
End Using
Next

Unload SplashScreen Image

I have an application that loads a spashscreen which loads a picture and centers this for a set length of time.
The issue I have is that the file used by splashscreen is locked and I can not make any modifications or replace it etc. until application is unloaded.
I am using the default VB net Spashscreen method and the code I use for the image is below
Dim Advert As System.Drawing.Image = Image.FromFile("Y:\Test\TestPic.jpg")
Dim width As Integer = Advert.Width
Dim height As Integer = Advert.Height
Me.BackgroundImage = Advert
Me.BackgroundImageLayout = ImageLayout.Stretch
Me.Size = New Size(width, height)
Me.CenterToScreen()
and then this code in the application events to overide the display time
Protected Overrides Function OnInitialize(ByVal commandLineArgs As
System.Collections.ObjectModel.ReadOnlyCollection(Of String)) As Boolean
Me.MinimumSplashScreenDisplayTime = 7000
Return MyBase.OnInitialize(commandLineArgs)
End Function
Is there a way to release the image file when the splash screen closes.

Upload and replace the same image file if it already exist

I have a picturebox named PB_Company_Logo and I have a button named btn_Save and within this button I have this function which saves the image in PB_Company_Logo to current_directory/images
Public Sub save_PB(PB_Name As PictureBox)
Dim filename As String = "company_logo.png"
Dim path As String = Directory.GetCurrentDirectory() & "\images"
Dim filename_path As String = System.IO.Path.Combine(path, filename)
If (Not System.IO.Directory.Exists(path)) Then
System.IO.Directory.CreateDirectory(path)
PB_Name.Image.Save(filename_path)
Else
PB_Name.Image.Save(filename_path)
End If
End Sub
The problem is, there are cases where the user will upload a new company_logo.png. I want the system to treat the uploading of new image as replacing the former company_logo.png.
I think the error in this line of code means that the file is currently in used (locked) and therefore cannot be replaced.
Else
PB_Name.Image.Save(filename_path)
End If
When you load a pictureBox control with an image file the ide (vs) puts a lock on the file. This happens when you set the image property of the pictureBox control to a file at design time.
You can use the FileStream object.
Example:
Dim fs As System.IO.FileStream
' Specify a valid picture file path on your computer.
fs = New System.IO.FileStream("C:\WINNT\Web\Wallpaper\Fly Away.jpg",
IO.FileMode.Open, IO.FileAccess.Read)
PictureBox1.Image = System.Drawing.Image.FromStream(fs)
fs.Close()
After you have done the workaround you can then use the System.IO.File.Exists(img) namespace to check wether or not a picture exists.
Example: This checks if the image passed through already exists and if it does then it will replace it.
Dim imageStr As String = "~/images/name.jpg"
If System.IO.File.Exists(imageStr) Then
Image1.ImageUrl = "~/images/name.jpg"
End If

AxAcroPdf Control - Issues reloading PDF

When using the axAcroPdfLib.AxAcroPDF control in my Windows Forms application, I'm not able to reload the same image. The image is initially loaded with the LoadFile() method.
Upon using the LoadFile() method again on the same path AFTER saving changes to the PDF, the control becomes blank (no PDF shown).
If I set the src property of the control to the path, I get a message saying the file does not begin with '%PDF-'. But it does. I opened it with Word and it clearly begins with %PDF-. It's not corrupt or locked either.
I've even tried closing, disposing, or setting it to Nothing, and then completely re-instantiating it as I did the first time it's loaded - no effect. The window closes and shows with the control blank.
Loading a different file via the above methods has the same effect - blank.
Using Windows 7 64-bit, VS 2010, VB.NET.
The code is below. For right now, I'm just trying to draw a simple line on it.
Private Sub _btnBarCode_Click(ByVal sender As Object, ByVal e As EventArgs) Handles _btnBarCode.Click
Dim pdfReader As iTextSharp.text.pdf.PdfReader = Nothing
Try
pdfReader = New iTextSharp.text.pdf.PdfReader(File.ReadAllBytes(_path))
Using fs As New FileStream(_path, FileMode.Create, FileAccess.Write)
Using pdfStamper = New iTextSharp.text.pdf.PdfStamper(pdfReader, fs)
Dim pdfPage As iTextSharp.text.pdf.PdfContentByte = pdfStamper.GetOverContent(1)
Using barCodeForm As New FBarCode
barCodeForm.Barcode = _barCode
If (barCodeForm.ShowDialog(Me) = DialogResult.OK) Then
Dim screenBarCode As Point = barCodeForm.Location
Dim clientBarCode As Point = Point.op_Subtraction(PointToClient(screenBarCode), New Point(0, 50)) '_pdfControl.Location '_imgView.Location
clientBarCode = New Point(10, 50)
Dim barcodeImg As New Bitmap(200, 50)
Using gc As Graphics = Graphics.FromImage(barcodeImg)
gc.DrawLine(Pens.Red, New Point(10, 10), New Point(20, 20))
'barCodeForm._barCode.DrawBarCode(gc, clientBarCode)
End Using
Dim convert As ImageConverter = New ImageConverter()
Dim bmpBytes As Byte() = DirectCast(convert.ConvertTo(barcodeImg, GetType(Byte())), Byte())
Dim thisImage As iTextSharp.text.Image = iTextSharp.text.Image.GetInstance(bmpBytes)
thisImage.SetAbsolutePosition(clientBarCode.X, clientBarCode.Y)
thisImage.SetDpi(72, 72)
pdfPage.AddImage(thisImage)
rdrAdobePdf.LoadFile(_path) 'Blank pdf
'rdrAdobePdf.src = _path '"Does not begin with '%PDF-' (even though it does)
'Me.Close()
'_myParent.ResetPdfViewer()
'ReloadPdfViewer(Me.Barcode)
End If
End Using
End Using
End Using
Catch ex As Exception
MessageBox.Show(ex.Message, "An error occurred.")
Return
Finally
If Not pdfReader Is Nothing Then pdfReader.Close()
End Try
End Sub
Any ideas what could be the problem here?
Problem was solved by getting the reloading code out of that click method. Putting it in another click method solved the problem - not sure why. The code I used just ran .LoadFile, then Form.Show() and Form.Activate().