creating more than one image file when button clicked - vb.net

Private Sub btnPrint_Click(sender As Object, e As EventArgs) Handles btnPrint.Click
CaptureScreen()
'used to created file path
Dim orderNum As String = Val(txtNum.Text) 'gets value of Invoice/PO number
Dim orderType As String = GroupBox3.Text 'gets value of either its a Invoice or PO`
'saves printscreen to PictureBox
PictureBox1.Image = bmpBackground
'saves printscreen to file path
PictureBox1.Image.Save("\\PCLIQFS\Shared_Data\PCLiq Scale-Shots\" + orderType + " " + orderNum + ".jpg", Imaging.ImageFormat.Jpeg)
'creates variable of filePath
Dim filePath As String = "\\PCLIQFS\Shared_Data\PCLiq Scale-Shots\" + orderType + " " + orderNum + ".jpg"
'checks to see if file is already in filePath
If File.Exists(filePath) Then
Dim folderPath = Path.GetDirectoryName(filePath)
Dim fileName = Path.GetFileNameWithoutExtension(filePath)
Dim extension = Path.GetExtension(filePath)
Dim fileNumber = 0
Do
'increments file name
fileNumber += 1
filePath = Path.Combine(folderPath,
String.Format("{0} ({1}){2}",
fileName,
fileNumber,
extension))
Loop While File.Exists(filePath)
End If
'saves new image
PictureBox1.Image.Save(filePath)
End Sub
I want to save an image when the user clicks the print button, but it creates two images at once since the images is already there. I only want to create another image if the print button is clicked again. How to I make it so that the code the increments the file name only runs if the print button is clicked again?

Comment the following line;
PictureBox1.Image.Save("\\PCLIQFS\Shared_Data\PCLiq Scale-Shots\" + orderType + " " + orderNum + ".jpg", Imaging.ImageFormat.Jpeg)
because you are saving the image at the end of the code.

Related

How do I prevent overwriting the name of a saved image, if the previously saved image was deleted?

Dim data As IDataObject
Dim bmap As Image
SendMessage(hHwnd, WM_CAP_EDIT_COPY, 0, 0)
data = Clipboard.GetDataObject
If data.GetDataPresent(GetType(System.Drawing.Bitmap)) Then
bmap = CType(data.GetData(GetType(System.Drawing.Bitmap)), Image)
PictureBox1.Image = bmap
SendMessage(hHwnd, WM_CAP_DRIVER_CONNECT, iDevice, 0)
DestroyWindow(hHwnd)
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Dim counter = My.Computer.FileSystem.GetFiles("C:\Data\Image")
Dim intCount As Integer
Dim strfilename As String
intCount = CStr(counter.Count)
strfilename = "Image" & intCount + 1
PictureBox1.Image.Save("C:\Data\Image\" & strfilename & ".jpeg", System.Drawing.Imaging.ImageFormat.Jpeg)
Dim strpath As String = "C:\Data\Image\" & strfilename & ".jpeg"
Label1.Text = strpath
End If
the name of the image that the image is stored in. image1, image2, image3, image4, image5, image6, image7, image8 and so on. if any image with the name image4 is deleted then the image file to be saved will look for the name with the largest number and then add 1
A better way to do this is to go to "My Project" => "Settings" and create "intCounter" as an integer. (Do not change the value)
https://i.stack.imgur.com/1iGyI.png
Every time an image is saved the intCounter should increase by 1. This can be done by: Remote.My.Settings.intCounter = Remote.My.Settings.intCounter + 1
strfilename = "Image" & Remote.My.Settings.intCounter
If the program is closed, the value of intCounter will be kept.

How not to overwrite files in VB.net

I want to check if the current file exists at the same time save video to different file but it only overwrites to an existing file.
Here is my code:
Private Sub ButtonVIDEO_Click(ByVal sender As System.Object, e As System.EventArgs) Handles ButtonVIDEO.Click
f = New Filters
cap = New Capture(f.VideoInputDevices(0), f.AudioInputDevices(0))
cap.PreviewWindow = PictureBox1
Dim Filename As String = "c:\\folder\MyFile"
Dim i As Integer = 0
Dim extension As String = ".mp4"
If ButtonVIDEO.BackColor = Color.Black Then
cap.Filename = Filename + extension
If File.Exists(Filename) Then
Do
i = i + 1
Loop While File.Exists(Filename + i.ToString() + extension)
Filename = Filename + i.ToString()
End If
cap.Cue()
cap.Start()
ButtonVIDEO.BackColor = Color.Red
ButtonVIDEO.Text = "PLAYING"
ButtonPHOTO.Hide()
End If
End Sub
You are assigning the file name to cap before searching for an unsused file name.
Also, there is an error in your logic, as you are creating the full file name with Filename + i.ToString() + extension but you also append i to Filename itself with Filename = Filename + i.ToString().
So, in then end, you are appending the number twice.
Private Sub ButtonVIDEO_Click(ByVal sender As System.Object, e As System.EventArgs) _
Handles ButtonVIDEO.Click
Dim Filename As String = "c:\folder\MyFile"
Dim i As Integer = 0
Dim extension As String = ".mp4"
Dim path As String = Filename & extension
f = New Filters
cap = New Capture(f.VideoInputDevices(0), f.AudioInputDevices(0))
cap.PreviewWindow = PictureBox1
If ButtonVIDEO.BackColor = Color.Black Then
If File.Exists(path) Then
Do
i = i + 1
path = Filename & i & extension
Loop While File.Exists(path)
End If
cap.Filename = path
cap.Cue()
cap.Start()
ButtonVIDEO.BackColor = Color.Red
ButtonVIDEO.Text = "PLAYING"
ButtonPHOTO.Hide()
End If
End Sub
The path should have only one backslash in c:\folder. In VB strings are concatenated with &, not +.
See answer to The difference between + and & for joining strings in VB.NET

VB.net Check items in a text doc and see if it's in a folder

I have a text document with a list of file names and their extensions. I need to go through this list and check a directory for the existence of each file. I then need to output the result to either foundFilesList.txt or OrphanedFiles.txt. I have two approaches to this function, and neither is working. The first example uses a loop to cycle through the text doc. The second one doesn't work it never sees a match for the file from the fileNamesList.
Thank you for taking the time to look at this.
First Code:
Dim FILE_NAME As String
FILE_NAME = txtFileName.Text
Dim fileNames = System.IO.File.ReadAllLines(FILE_NAME)
fCount = 0
For i = 0 To fileNames.Count() - 1
Dim fileName = fileNames(i)
'sFileToFind = location & "\" & fileName & "*.*"
Dim paths = IO.Directory.GetFiles(location, fileName, IO.SearchOption.AllDirectories)
If Not paths.Any() Then
System.IO.File.AppendAllText(orphanedFiles, fileName & vbNewLine)
Else
For Each pathAndFileName As String In paths
If System.IO.File.Exists(pathAndFileName) = True Then
Dim sRegLast = pathAndFileName.Substring(pathAndFileName.LastIndexOf("\") + 1)
Dim toFileLoc = System.IO.Path.Combine(createXMLFldr, sRegLast)
Dim moveToFolder = System.IO.Path.Combine(MoveLocation, "XML files", sRegLast)
'if toFileLoc = XML file exists move it into the XML files folder
If System.IO.File.Exists(toFileLoc) = False Then
System.IO.File.Copy(pathAndFileName, moveToFolder, True)
System.IO.File.AppendAllText(ListofFiles, sRegLast & vbNewLine)
fileFilename = (fileName) + vbCrLf
fCount = fCount + 1
BackgroundWorker1.ReportProgress(fCount)
'fileCount.Text = fCount
End If
End If
Next
End If
BackgroundWorker1.ReportProgress(100 * i / fileNames.Count())
'statusText = i & " of " & fileName.Count() & " copied"
fCount = i
Next
Second Code:
FILE_NAME = txtFileName.Text 'textfield with lines of filenames are located ]
Dim fileNamesList = System.IO.File.ReadAllLines(FILE_NAME)
location = txtFolderPath.Text
fCount = 0
' Two list to collect missing and found files
Dim foundFiles As List(Of String) = New List(Of String)()
Dim notfoundFiles As List(Of String) = New List(Of String)()
Dim fileNames As String() = System.IO.Directory.GetFiles(createXMLFldr)
For Each file As String In fileNamesList
Debug.Write("single file : " & file & vbCr)
' Check if the files is contained or not in the request list
Dim paths = IO.Directory.GetFiles(location, file, IO.SearchOption.AllDirectories)
If fileNamesList.Contains(Path.GetFileNameWithoutExtension(file)) Then
Dim FileNameOnly = Path.GetFileName(file)
Debug.Write("FileNameOnly " & FileNameOnly & vbCr)
If System.IO.File.Exists(FileNameOnly) = True Then
'if toFileLoc = XML file exists move it into the XML files folder
Dim moveToFolder = System.IO.Path.Combine(MoveLocation, "XML files", file)
foundFiles.Add(file) 'add to foundFiles list
fileFilename = (file) + vbCrLf 'add file name to listbox
fCount = fCount + 1
Else
notfoundFiles.Add(file)
End If
End If
Next
File.WriteAllLines(ListofFiles, foundFiles)
File.WriteAllLines(orphanedFiles, notfoundFiles)
This is just a starting point for you, but give it a try:
Friend Module Main
Public Sub Main()
Dim oFiles As List(Of String)
Dim _
sOrphanedFiles,
sSearchFolder,
sFoundFiles,
sTargetFile As String
sOrphanedFiles = "D:\Results\OrphanedFiles.txt"
sSearchFolder = "D:\Files"
sFoundFiles = "D:\Results\FoundFiles.txt"
oFiles = IO.File.ReadAllLines("D:\List.txt").ToList
oFiles.ForEach(Sub(File)
If IO.Directory.GetFiles(sSearchFolder, File, IO.SearchOption.AllDirectories).Any Then
sTargetFile = sFoundFiles
Else
sTargetFile = sOrphanedFiles
End If
IO.File.AppendAllText(sTargetFile, $"{File}{Environment.NewLine}")
End Sub)
End Sub
End Module
If I've misjudged the requirements, let me know and I'll update accordingly.
Explanations and comments in-line.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'I presume txtFileName.Text contains the full path including the file name
'I also presume that this text file contains only file names with extensions
Dim FilesInTextFile = System.IO.File.ReadAllLines(txtFileName.Text)
'Instead of accessing the Directory over and over, just get an array of all the files into memory
'This should be faster than searching the Directory structure one by one
'Replace <DirectoryPathToSearch> with the actual path of the Directory you want to search
Dim FilesInDirectory = IO.Directory.GetFiles("<DirectoryPathToSearch>", "*.*", IO.SearchOption.AllDirectories)
'We now have an array of full path and file names but we just need the file name for comparison
Dim FileNamesInDirectory = From p In FilesInDirectory
Select Path.GetFileName(p)
'A string builder is more efficient than reassigning a string with &= because a
'string build is mutable
Dim sbFound As New StringBuilder
Dim sbOrphan As New StringBuilder
'Instead of opening a file, writing to the file and closing the file
'in the loop, just append to the string builder
For Each f In FilesInTextFile
If FileNamesInDirectory.Contains(f) Then
sbFound.AppendLine(f)
Else
sbOrphan.AppendLine(f)
End If
Next
'After the loop write to the files just once.
'Replace the file path with the actual path you want to use
IO.File.AppendAllText("C:\FoundFiles.txt", sbFound.ToString)
IO.File.AppendAllText("C:\OrphanFiles.txt", sbOrphan.ToString)
End Sub

Displaying image from folder/file in vb.net

Dim ImagePath As String = "images/spaceship2.png"
Dim img1 As Bitmap
Dim newImage As Image = Image.FromFile("images/spaceship2.png")
img1 = New Bitmap(ImagePath)
pb2.ImageLocation = ImagePath
pb1.Image = newImage
I want to display image from folder, for example, student with an id number of 22137471, the picture with the name of 22137471 will be display on my picture box, between, i saw this code somewhere in google.
i want to display image from folder, for example, student with an id
number of 22137471, the picture with the name of 22137471 will be
display on my picture box
Try something like...
Dim id As String = "22137471"
Dim folder As String = "c:\some path\folder"
Dim filename As String = System.IO.Path.Combine(folder, id & ".png")
PictureBox1.Image = Image.FromFile(filename)
Here's an updated version that doesn't lock the original image file:
Dim id As String = "22137471"
Dim folder As String = "c:\some path\folder"
Dim filename As String = System.IO.Path.Combine(folder, id & ".png")
Try
Using fs As New System.IO.FileStream(filename, IO.FileMode.Open)
PictureBox1.Image = New Bitmap(Image.FromStream(fs))
End Using
Catch ex As Exception
Dim msg As String = "Filename: " & filename &
Environment.NewLine & Environment.NewLine &
"Exception: " & ex.ToString
MessageBox.Show(msg, "Error Opening Image File")
End Try
You can try this:
PictureBox1.Image = Image.FromFile("c:\some path\folder\myImage.jpg")

Load Image files from folder

I have a checked list box and a thumbnail area to display them where I am trying to load only images from a specific folder and need to display in thumbnails area but the problem is there is a thumbs.db file which is also being added to the checked list box which I don't need it.
So how do I actually load only the image files without the thumbs.db file.
Here is my code:
Private Sub LoadProjectToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles LoadProjectToolStripMenuItem.Click
Using ofdlg As New Windows.Forms.OpenFileDialog
ofdlg.DefaultExt = "trk"
ofdlg.Filter = "Project|*.trk"
ofdlg.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
If ofdlg.ShowDialog = Windows.Forms.DialogResult.OK Then
Dim SaveData As New gCanvasData
Using objStreamReader As New StreamReader(ofdlg.FileName)
Dim x As New XmlSerializer(GetType(gCanvasData))
SaveData = CType(x.Deserialize(objStreamReader), gCanvasData)
objStreamReader.Close()
End Using
With SaveData
'gTSSizer_gAZoom.Value = 100
GCanvas1.ImageXYReset()
GCanvas1.Image = .Image
GCanvas1.gAnnotates = .gAnnotates
GCanvas1.RebuildAll()
GCanvas1.AssembleBitmap()
End With
Dim fullpath As String
fullpath = Application.StartupPath + "\" & System.IO.Path.GetFileNameWithoutExtension(ofdlg.FileName) + "\"
For Each fi As FileInfo In New DirectoryInfo(fullpath).GetFiles
CheckedListBox1.Items.Add(Application.StartupPath + "\" & System.IO.Path.GetFullPath(ofdlg.FileName))
For i As Integer = 0 To CheckedListBox1.Items.Count - 1
CheckedListBox1.SetItemChecked(i, True)
ThumbControl1.AddFolder(fullpath, True)
Next i
Next
End If
End Using
End Sub
Either filter it inside of the For Each Loop:
For Each fi As FileInfo In New DirectoryInfo(fullpath).GetFiles
If Not {".jpg", ".png", ".bmp"}.Contains(fi.Extension) Then Continue For
' ...
Next
or do it in the GetFiles:
DirectoryInfo(fullpath).GetFiles(".jpg")
Found the solution at last:
Dim fullpath As String
fullpath = Application.StartupPath & "\" & System.IO.Path.GetFileNameWithoutExtension(ofdlg.FileName) + "\"
Dim FileDirectory As New IO.DirectoryInfo(fullpath)
Dim FileJpg As IO.FileInfo() = FileDirectory.GetFiles("*.jpg")
Dim FileGif As IO.FileInfo() = FileDirectory.GetFiles("*.gif")
Dim FileBmp As IO.FileInfo() = FileDirectory.GetFiles("*.bmp")
For Each File As IO.FileInfo In FileJpg
CheckedListBox1.Items.Add(File.FullName)
Dim str As String
str = Directory.GetCurrentDirectory() & "\" & "Backup\"
Next
For Each File As IO.FileInfo In FileGif
CheckedListBox1.Items.Add(File.FullName)
Dim str As String
str = Directory.GetCurrentDirectory() & "\" & "Backup\"
Next
For Each File As IO.FileInfo In FileBmp
CheckedListBox1.Items.Add(File.FullName)
Dim str As String
str = Directory.GetCurrentDirectory() & "\" & "Backup\"
Next
For i As Integer = 0 To CheckedListBox1.Items.Count - 1
CheckedListBox1.SetItemChecked(i, True)
Next i
Change DirectoryInfo(fullpath).GetFiles to DirectoryInfo(fullpath).EnumerateFiles() And add a search pattern for the image file extensions you want. http://msdn.microsoft.com/en-us/library/dd383574.aspx