How to display a random photo from a folder in a picture box and print out the photo name without extension - vb.net

I have a folder named "MyPhotos", I want to display a random photo at each time a command button is clicked from "Myphoto" and print out the name of the displayed photo in the form without extension . I'm trying the following code, but still can't get the photo name
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As _ System.EventArgs) Handles Button1.Click
Dim DirectoryPath As String = Application.ExecutablePath
Directorypath = DirectoryPath.Substring(0, Directorypath.LastIndexOf("\bin")) & "\MyPhotos"
Dim bm As New Bitmap(GetRandomImageFilePath(Directorypath))
picImage.Image = bm
End Sub
Public Function GetRandomImageFilePath(ByVal folderPath As String) As String
Dim files() As String = Directory.GetFiles(folderPath, "*.jpg")
Dim random As Random = New Random()
Return files(random.Next(0, files.Length))
End Function
Any help please ?

I added this to your button method. All I used was FileInfo to get the details.
Dim finfo As FileInfo = New FileInfo(GetRandomImageFilePath(DirectoryPath))
Dim filename As String = finfo.Name.Replace(finfo.Extension, "")
Dim bm As New Bitmap(finfo.FullName)
picImage.Image = bm

You already have the full path being returned by GetRandomImageFilePath.
If you want just the filename, do this in your calling Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As _ System.EventArgs) Handles Button1.Click
Dim DirectoryPath As String = Application.ExecutablePath
Directorypath = DirectoryPath.Substring(0, Directorypath.LastIndexOf("\bin")) & "\MyPhotos"
Dim imagePath as String = GetRandomImageFilePath(Directorypath)
Dim fileInfo as New FileInfo(imagePath)
Dim imageName as String = fileInfo.Name
Dim bm As New Bitmap(imagePath)
picImage.Image = bm
End Sub

Related

WebClient.DownloadString to work with 2 urls

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2
Dim downloader As New WebClient
downloader.Encoding = Encoding.UTF8
Dim mystring As String = downloader.DownloadString("ONE LINK HERE" And "OTHER LINK HERE")
Dim myregex As String = "\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b:\d{2,5}"
Dim source As String = mystring
Dim findme As MatchCollection = Regex.Matches(source, myregex)
For Each mymatch As Match In findme
ListBox1.Items.Add(mymatch)
Next
New here, sorry for bad formatation, all i want to do is download string from 2 urls at same time without errors

Read text file with delimiter

i want to read text file and from the fifth line take only the first column before (;) this my code to browse and read text :
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim OpenFile As New OpenFileDialog
OpenFile.FileName = ""
OpenFile.Filter = "Fichier Texte (*.pnp)|*.pnp"
OpenFile.ShowDialog()
Try
Dim lire As New System.IO.StreamReader(OpenFile.FileName)
RichTextBox1.Text = lire.ReadToEnd
lire.Close()
Catch ex As Exception
End Try
End Sub
End Class
help me please
You could try something like this:
Dim lineYouWantToRead As Int32 = 5
Dim fieldYouWantToRead As Int32 = 1
Dim capturedValue As String = ""
Using fileReader As New FileIO.TextFieldParser(OpenFile.FileName)
fileReader.TextFieldType = FileIO.FieldType.Delimited
fileReader.SetDelimiters(";")
While fileReader.LineNumber <= lineYouWantToRead - 1
Dim currentLine As String() = fileReader.ReadFields()
capturedValue = currentLine(fieldYouWantToRead - 1)
End While
End Using
RichTextBox1.Text = capturedValue
Let us know if that is any help.

VB: How to save image to folder in the following vb code?

Public Class Form1
'Webcam
Public Touchless As New TouchlessLib.TouchlessMgr
Public Camera1 As TouchlessLib.Camera = Touchless.Cameras.ElementAt(1)
Public Camera2 As TouchlessLib.Camera = Touchless.Cameras.ElementAt(0)
Private Sub Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
PictureBox3.Image = Touchless.Cameras.ElementAt(1).GetCurrentImage
PictureBox4.Image = Touchless.Cameras.ElementAt(0).GetCurrentImage
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Touchless.CurrentCamera = Camera1
Touchless.CurrentCamera.CaptureHeight = 250
Touchless.CurrentCamera.CaptureWidth = 300
Touchless.CurrentCamera = Camera2
Touchless.CurrentCamera.CaptureHeight = 250
Touchless.CurrentCamera.CaptureWidth = 300
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
PictureBox1.Image = Touchless.Cameras.ElementAt(1).GetCurrentImage
PictureBox2.Image = Touchless.Cameras.ElementAt(0).GetCurrentImage
End Sub
' Save the picture.
Private Sub Button2_Click(ByVal sender As _
System.Object, ByVal e As System.EventArgs) Handles _
Button2.Click
' Compose the picture's base file name.
Dim file_name As String = Application.ExecutablePath
file_name = file_name.Substring(0, _
file_name.LastIndexOf("\bin")) & _
"\test."
' Get a Bitmap.
Dim bm As Bitmap = PictureBox4.Image
' Save the picture as a bitmap, JPEG, and GIF.
bm.Save(file_name & "bmp", _
System.Drawing.Imaging.ImageFormat.Bmp)
bm.Save(file_name & "jpg", _
System.Drawing.Imaging.ImageFormat.Jpeg)
bm.Save(file_name & "gif", _
System.Drawing.Imaging.ImageFormat.Gif)
MsgBox("Ok")
End Sub
In the above code, i want to save image to a c:/ drive with a custom file name and with replace of default folder "\bin" and name "\test." in the above code...what is the correct code to save image with custom destination & file name option..?
Thank U
Take a look at the following part of the sample you posted.
bm.Save(file_name & "bmp", _System.Drawing.Imaging.ImageFormat.Bmp)
Your image will be saved with the name of the value that the string "file_name" holds. (plus the string "bmp")
So you should assign the path + file name you want to use to the string that's currently used to save your image.
So replace
Dim file_name As String = Application.ExecutablePath
file_name = file_name.Substring(0, _
file_name.LastIndexOf("\bin")) & _
"\test."
with
file_name = "C:\yourFileNameHere."
Then you can save your image using
bm.Save(file_name & ".bmp", _System.Drawing.Imaging.ImageFormat.Bmp)
If you want to give the name from within your form you could use a textbox and pass the text from the textbox to the string
file_name = TextBox1.Text;
Using Image.Save method: http://msdn.microsoft.com/en-us/library/ktx83wah%28v=vs.110%29.aspx
or using filestream if you have a bytestream of the object: http://msdn.microsoft.com/en-us/library/vstudio/system.io.filestream
Using FS As New IO.FileStream("C:\location\file.ext", IO.FileMode.OpenOrCreate, IO.FileAccess.Write)
FS.Write(item.imageBytes, 0, item.imageBytesLength)
End Using
to get a bytestream from an image, use:
Using FS As New IO.FileStream("C:\location\file.ext", IO.FileMode.Open, IO.FileAccess.Read)
Dim _theBytes(FS.Length) As Byte
FS.Read(_theBytes, 0, FS.Length)
_imageBytes = _theBytes
End Using

Reading from and manipulating a .csv file

I have multiple .csv files for each month which go like:
01/04/2012,00:00,7.521527,80.90972,4.541667,5.774305,7,281.368
02/04/2012,00:00,8.809029,84.59028,6.451389,5.797918,7,274.0764
03/04/2012,00:00,4.882638,77.86806,1.152778,15.13611,33,127.6389
04/04/2012,00:00,5.600694,50.35417,-3.826389,15.27222,33,40.05556
The format is : Date in the form dd/mm/yy,Current time,Current temperature,Current humidity,Current dewpoint,Current wind speed,Current wind gust,Current wind bearing
The program needs to calculate the average for
temperature
humidity
wind speed
wind direction
and display them on a text box.
any ideas?
Here is what I have done so far...
Option Strict On
Option Explicit On
Imports System.IO
Imports System
Public Class Form1
Private Sub cmb1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmb1.SelectedIndexChanged
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnexit.Click
Me.Close()
End Sub
Private Sub btn1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btndata.Click
'This is for August
If cmb1.SelectedIndex = 1 Then
TextBox1.Clear()
Using reader As New StreamReader("c://temp/DailyAug12log.csv")
Dim line As String = reader.ReadLine()
Dim avgTemp As Integer
Dim fields() As String = line.Split(",".ToCharArray())
Dim fileDate = CDate(fields(0))
Dim fileTime = fields(1)
Dim fileTemp = fields(2)
Dim fileHum = fields(3)
Dim fileWindSpeed = fields(4)
Dim fileWindGust = fields(5)
Dim fileWindBearing = fields(6)
While line IsNot Nothing
counter = counter + 1
line = reader.ReadLine()
End While
avgTemp = CInt(fields(2))
avgTemp = CInt(CDbl(avgTemp / counter))
TextBox1.Text = TextBox1.Text & "Month = August" & vbCrLf & "Temperature Average: " & avgTemp & vbCrLf
End Using
End If
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim files() As String
files = Directory.GetFiles("C:\Temp", "*.csv", SearchOption.AllDirectories)
For Each FileName As String In files
cmb1.Items.Add(FileName.Substring(FileName.LastIndexOf("\") + 1, FileName.Length - FileName.LastIndexOf("\") - 1))
Next
End Sub
End Class
Private Class Weather
Public SampleTimeStamp AS Date
Public Temperature AS Double
Public Humidity As Double
Public WindSpeed AS Double
Public WindBearing AS Double
End Class
Sub Main
Dim samples = ReadFile("c://temp/DailyAug12log.csv")
Dim avgTemperature = samples.Average(Function(s) s.Temperature)
...
End Sub
Private Function ReadFile(ByVal fileName as String) AS List(Of Weather)
Dim samples As New List(Of Weather)
Using tfp As new TextFieldParser(filename)
tfp.Delimiters = new String() { "," }
tfp.TextFieldType = FieldType.Delimited
While Not tfp.EndOfData
Dim fields = tfp.ReadFields()
Dim sample As New Weather()
sample.SampleTimeStamp = Date.ParseExact(fields(0) & fields(1), "dd\/MM\/yyyyHH\:mm", CultureInfo.InvariantCulture)
sample.Temperature = Double.Parse(fields(2), CultureInfo.InvariantCulture)
sample.Humidity = Double.Parse(fields(3), CultureInfo.InvariantCulture)
sample.WindSpeed = Double.Parse(fields(4), CultureInfo.InvariantCulture)
sample.WindBearing = Double.Parse(fields(5), CultureInfo.InvariantCulture)
samples.Add(sample)
End While
Return samples
End Using
End Function
I would not use a this aprroach - if the order of the columns changes, your program will show wrong results.
I would use a good csv reader like http://kbcsv.codeplex.com/ and read the Data to a datatable. then you can calculate your resulting columns quite easily and reliablly, because you can adress each column like MyDatatable.Cooumns["Headername"].

Getting Images From file and Adding them to Array

I'm trying to create a program that checks if someone is going to Happy Hour. If not, it lists those who aren't and puts their picture next to their name.
I'm able to achieve all but get the images locally and store them in an array (which would be added to pictureArray(i)).
(You can see the commented out sections are where I've tried to get the images...)
Any ideas?
Public Class Form1
Dim ITLPList() As String = {"Name 1", "Name 2", "Name 3", "Name 4", "Name 5", "Name 6"}
' Dim imageList As New ImageList
' Dim fileSteam As New System.IO.FileStream(sFileName, System.IO.FileMode.Open)
' Dim img As Image
' Dim sFileName As String = "C:\Users\turcotd\Desktop\ITLPers\itlp1.jpg"
Dim itlpTally() As String
Dim labelArray(5) As Label
Dim pictureArray(5) As PictureBox
Dim intTally As Integer
Dim i As Integer = 0
Public itlpIndex As Integer = 0
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
itlpName.Text = ITLPList(0)
labelArray(0) = lblPerson0
labelArray(1) = lblPerson1
labelArray(2) = lblPerson2
labelArray(3) = lblPerson3
labelArray(4) = lblPerson4
pictureArray(0) = picITLP0
pictureArray(1) = picITLP1
pictureArray(2) = picITLP2
pictureArray(3) = picITLP3
pictureArray(4) = picITLP4
End Sub
Private Sub btnYes_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnYes.Click
If (i < 6) Then
itlpName.Text = ITLPList(i)
i = i + 1
End If
End Sub
Private Sub btnNo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnNo.Click
If (i < 6) Then
'Names
itlpName.Text = ITLPList(i)
intTally = intTally + 1
lblTally.Text = intTally
labelArray(i).Text = ITLPList(i)
'Images
' img = Image.FromStream(fileSteam)
' fileSteam.Close()
' imageList.Images.Add(img)
' pictureArray(i).Image = imageList.Images.Item(0)
' img.Dispose()
' img = Image.FromFile(sFileName)
i = i + 1
End If
itlpName.Text = ITLPList(i)
End Sub
End Class
You could get all jpg's in a directory as FileInfo in the following way:
Dim dir = New IO.DirectoryInfo("C:\Users\turcotd\Desktop\ITLPers")
Dim images = dir.GetFiles("*.jpg", IO.SearchOption.AllDirectories).ToList
Loading the file into the PictureBox from a file is a very straightforward operation:
picITLP0.Image = Image.FromFile("C:\Users\turcotd\Desktop\ITLPers\itlp1.jpg")