Save the image from the picturebox - vb.net

Use this code to save the image from the PictureBox.
By saving the file and adding a name to it
The problem I'm facing, come on, when adjusting the image the following error occurs : - a generic error occurred in gdi+
My Code
show image
Using fs As New System.IO.FileStream("path", IO.FileMode.Open, IO.FileAccess.Read) PIC_PARTA.Image = System.Drawing.Image.FromStream(fs) End Using
save image
Dim pic As Image
pic = PIC_PARTA.Image
Dim Savefild As New SaveFileDialog
Savefild.FileName = TEXT_NAMEIMG.Text & ".PNG"
Savefild.ShowDialog()
pic.Save(Savefild.FileName, System.Drawing.Imaging.ImageFormat.Png)
LAB_path.Text = Savefild.FileName
Savefild.Dispose()
pic.Dispose()

This is not a full answer at this stage but it includes a significant amount of code, so I'll post as an answer and then either update or delete as required.
I just tried this code and all four saves worked, even though I thought that some may not:
Imports System.IO
Public Class Form1
Private ReadOnly folderPath As String = Path.Combine(My.Computer.FileSystem.SpecialDirectories.MyPictures, "Test")
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
PictureBox1.Image = Image.FromFile(Path.Combine(folderPath, "Picture1.png"))
Using fs = File.OpenRead(Path.Combine(folderPath, "Picture2.png"))
PictureBox2.Image = Image.FromStream(fs)
End Using
PictureBox3.ImageLocation = Path.Combine(folderPath, "Picture3.png")
PictureBox4.Load(Path.Combine(folderPath, "Picture4.png"))
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
PictureBox1.Image.Save(Path.Combine(folderPath, "Output1.png"))
Catch ex As Exception
MessageBox.Show(ex.ToString())
End Try
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Try
PictureBox2.Image.Save(Path.Combine(folderPath, "Output2.png"))
Catch ex As Exception
MessageBox.Show(ex.ToString())
End Try
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Try
PictureBox3.Image.Save(Path.Combine(folderPath, "Output3.png"))
Catch ex As Exception
MessageBox.Show(ex.ToString())
End Try
End Sub
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
Try
PictureBox4.Image.Save(Path.Combine(folderPath, "Output4.png"))
Catch ex As Exception
MessageBox.Show(ex.ToString())
End Try
End Sub
End Class
Can you please test that with your own images in your own folder and see if you get the same result?
Note that the Image.FromFile option locks the file until you dispose the Image. I have seen instances in the past where trying to save an Image created using Image.FromStream generates the error message you mentioned because it can't access the stream again later. Image.FromFile avoids that but has its own downsides.
My code that uses a FileStream directly is simpler and, therefore, better than yours but setting ImageLocation or calling Load is simpler again and thus better again. I suggest that you use one of those two options and see whether you still have an issue.

Related

aforge camera won't close, error "thread abort is not supported in this platform"

I am totally new to vb.net and I am trying to incorporate my webcam into the application that i am creating. I have successfully made it run until to the point that i want to close the camera and proceed to other tasks but the camera kept running and when i tried to create a variable that will stop the camera like "camera.stop", i received this error (thread abort is not supported in this platform). i am using vb.net 2019 for this
Imports AForge
Imports AForge.Video
Imports AForge.Video.DirectShow
Imports System.IO
Imports System.Data.SqlClient
Public Class CAMERA
Dim camera As VideoCaptureDevice
Dim bmp As Bitmap
Dim cmd As New SqlCommand
Private Sub Captured(sender As Object, eventArgs As NewFrameEventArgs)
bmp = DirectCast(eventArgs.Frame.Clone(), Bitmap)
PictureBox1.Image = DirectCast(eventArgs.Frame.Clone(), Bitmap)
End Sub
Private Sub CAMERA_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim cameras As VideoCaptureDeviceForm = New VideoCaptureDeviceForm
If cameras.ShowDialog() = Windows.Forms.DialogResult.OK Then
camera = cameras.VideoDevice
AddHandler camera.NewFrame, New NewFrameEventHandler(AddressOf Captured)
camera.Start()
End If
End Sub
Private Sub CAMERA_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
camera.Stop()
End Sub
Private Sub PictureBox4_Click(sender As Object, e As EventArgs) Handles PictureBox4.Click
Me.Close()
End Sub
Private Sub SButton3_Click_1(sender As Object, e As EventArgs) Handles SButton3.Click
PictureBox2.Image = PictureBox1.Image
End Sub
Private Sub SButton1_Click(sender As Object, e As EventArgs) Handles SButton1.Click
If SaveFileDialog1.ShowDialog() = DialogResult.OK Then
PictureBox2.Image.Save(SaveFileDialog1.FileName, System.Drawing.Imaging.ImageFormat.Jpeg)
End If
MessageBox.Show("PROFILE IMAGE UPDATED")
End Sub
End Class
Not sure if you still need this but as I had the same problem I thought it might be useful to post the answer for the next person.
According to Aforge:
VideoCaptureDevice stop is now obsolete and you need to use SignalToStop.
If you need to wait for it to stop there is the WaitForStop method.
More info at:
http://www.aforgenet.com/framework/docs/html/c467086b-99dc-b7b8-cc45-f43247c2674c.htm

How to stack mp3 files in listbox

i'm trying to make a music player using AxWindowsMediaPlayer but i have a small problem on this import code. (the imported items go to a listbox #listbox1)
Public Class Form1
Dim song As String()
Dim directory As String()
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
If (OpenFileDialog1.ShowDialog = DialogResult.OK) Then
song = OpenFileDialog1.SafeFileNames
directory = OpenFileDialog1.FileNames
For items As Integer = 0 To song.Count - 1
ListBox1.Items.Add(song(items))
Next
End If
Catch ex As Exception
End Try
End Sub
Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.SelectedIndexChanged
Try
AxWindowsMediaPlayer1.URL = directory(ListBox1.SelectedIndex)
AxWindowsMediaPlayer1.Ctlcontrols.play()
End Sub
End Class
Catch ex As Exception
End Try
But when trying to re-import new songs (after the first import) and trying to play it, the newly reimported songs overwrites the previous ones (e.g. oldimportedsong1 gets overwritten by newimportedsong1, oldimportedsong2 gets overwritten by newimportedsong2)
Please help me out!
It will simplify your code if you use List(Of T). Otherwise you will have to ReDim Preserve your arrays.
What is happening in your code is you are overwritting your arrays every time you click the button.
Private song As New List(Of String)
Private directory As New List(Of String)
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
Try
If OpenFileDialog1.ShowDialog = DialogResult.OK Then
song.AddRange(OpenFileDialog1.SafeFileNames)
directory.AddRange(OpenFileDialog1.FileNames)
ListBox1.DataSource = Nothing
ListBox1.DataSource = song
End If
Catch ex As Exception
'empty catch boxes are the devil's workshop
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.SelectedIndexChanged
Dim i As Integer = ListBox1.SelectedIndex
Dim path As String = directory(i)
End Sub

A generic error occurred in GDI+ for 2nd time capturig picture

I would like to capture a picture from a video recording and save it into a folder. When i capture it for the second time, a problem stated that "A generic error occurred in GDI+". I have fully access right to the folder and the path of the folder is correct.
Below is my coding
PictureBox1 is picture box used to record video
picImage is another windows form used to capture picture
Private Sub ButtonFOTO_Click(sender As Object, e As EventArgs) Handles ButtonFOTO.Click
Capturer.picImage.Image = PictureBox1.Image
Capturer.Show()
Threading.Thread.Sleep(1000)
Capturer.ButtonGUARDAR.PerformClick()
End Sub
Public Class Capturer
Private Sub ButtonGUARDAR_Click(sender As Object, e As EventArgs) Handles ButtonGUARDAR.Click
Dim bm As Bitmap = New Bitmap(picImage.Image)
bm.Save("C:\Users\lim\Desktop\photo\picture\test11.jpg", Imaging.ImageFormat.Jpeg)
Me.Hide()
End Sub
End Class

VB.NET Backgroundworker only show loading form once?

I have a button on a form which basically get data from my database as below.
Private Sub ToolStripButton1_Click(sender As Object, e As EventArgs)
Handles ToolStripButton1.Click
BackgroundWorker1.RunWorkerAsync()
Loading_Screen.ShowDialog()
End Sub
The loading screen is called after my code (obtain data from database) is run in backgroundworker.
When backgroundworker is done, I close the loading form as below
Private Sub BackgroundWorker1_RunWorkerCompleted(sender As Object, e As RunWorkerCompletedEventArgs)
Handles BackgroundWorker1.RunWorkerCompleted
DataGridView1.DataSource = bSource
SDA.Update(dataTable)
ToolStripLabel1.Text = "RESULT : " + DataGridView1.RowCount.ToString
Loading_Screen.Close()
End Sub
This only works when I started the application for the first time. Whenever I click the button again, the loading form will not show anymore but the code still runs fine. Any idea?
The loading form has no code at all, just a running progress bar every time it is loaded.
What I have done but no luck :
Me.Refresh() the main form after calling loading form.
Me.Refresh() the loading form when on load function.
Tried loadingform.hide() instead of show()
Tried both show() and showdialog()
Tried creating new instance of the loading form.
Me.dispose() loading form on closing function
Me.dispose() main form on closing function
Setting loading form as top most.
UPDATE (I will keep updating my progress here)
As many of you asked to create a new instance, here is what I already did
Private Sub ToolStripButton1_Click(sender As Object, e As EventArgs) Handles ToolStripButton1.Click
BackgroundWorker1.RunWorkerAsync()
ldScreen = New Loading_Screen()
ldScreen.ShowDialog()
Me.Refresh()
End Sub
Then, in run completed,
Private Sub BackgroundWorker1_RunWorkerCompleted(sender As Object, e As RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
DataGridView1.DataSource = bSource
SDA.Update(dataTable)
ToolStripLabel1.Text = "RESULT : " + DataGridView1.RowCount.ToString
ldScreen.Close()
BackgroundWorker1.Dispose()
End Sub
In my loading form, the code is only this
Private Sub Loading_Screen_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
Me.Dispose()
End Sub
Private Sub Loading_Screen_Load(sender As Object, e As EventArgs) Handles Me.Load
Me.Refresh()
End Sub
UPDATE 2
By stripping out most of my code and putting system thread sleep in backgroundworker do work, the loading form shows up properly. So here is my code in backgroundworkerdowork on what is actually happening.
Private Sub BackgroundWorker1_DoWork(sender As Object, e As DoWorkEventArgs) Handles BackgroundWorker1.DoWork
Connect2Database()
Try
sqlCommand.CommandText = "Select * from kup_table" 'Load full database into gridview
SDA.SelectCommand = sqlCommand
SDA.Fill(dataTable)
bSource.DataSource = dataTable
mySqlConn.Close()
Catch ex As MySqlException
MsgBox(ex.ToString)
If mySqlConn.State = ConnectionState.Open Then
mySqlConn.Close()
End If
Finally
mySqlConn.Dispose()
End Try
'System.Threading.Thread.Sleep(2000)
End Sub
And here is the Connect2Database function codes
Private Sub Connect2Database()
sqlCommand = New MySqlCommand
dataTable = New DataTable
SDA = New MySqlDataAdapter
bSource = New BindingSource
Try
dataTable.Clear()
mySqlConn.ConnectionString = connString
sqlCommand.Connection = mySqlConn
mySqlConn.Open()
Catch ex As MySqlException
MsgBox(ex.ToString)
If mySqlConn.State = ConnectionState.Open Then
mySqlConn.Close()
End If
End Try
End Sub
UPDATE 3
What I have noticed is that when my System.Threading.Thread.Sleep(2000) is not commented, the loading screen will show up normally. But if I changed it to System.Threading.Thread.Sleep(1), loading screen does not shows up. Why is this happening? Code runs super fast after the first time?
This is because calling Close() disposes the Form. So either you have to create a new instance of the form every time, or you need to use Hide(). Judging by your question, I think you want the former.
have you tried to create a new instance of the form?
Private Sub ToolStripButton1_Click(sender As Object, e As EventArgs)
Handles ToolStripButton1.Click
Dim frm As New Loading_Screen
BackgroundWorker1.RunWorkerAsync()
frm.ShowDialog()
End Sub

Locking computer drive using VB.net

I want to create a project through which I should be able to first see my drives and then select one of them to programically lock them.
Is it possible ?
If so please answer
You can get your devices with DriveInfo.GetDrives().
How do you want to lock them? If you want to encode a folder, look at https://stackoverflow.com/a/2302028/3905529
To lock a device or folder withouth encrypting is not reliable because in this case the data are not locked at another pc.
I tested the code below extracted from http://www.mindfiresolutions.com/How-to-Lock-And-Unlock-a-Folder-through-Code-in-VBNET-2310.php. First you have to provide a way to choose the directory you want to lock, in the case shown, a folderbrowserdialog was used.
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles btnBrowse.Click
Try
If FolderBrowserDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
TextBox1.Text = FolderBrowserDialog1.SelectedPath
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Then I created two buttons to lock and unlock the directory whose path was written in a textbox previously by the function above.
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles btnLock.Click
Dim fs As FileSystemSecurity = File.GetAccessControl(TextBox1.Text)
fs.AddAccessRule(New FileSystemAccessRule(Environment.UserName, FileSystemRights.FullControl, AccessControlType.Deny))
File.SetAccessControl(TextBox1.Text, fs)
End Sub
Private Sub btnUnlock_Click(sender As System.Object, e As System.EventArgs) Handles btnUnlock.Click
Dim fs As FileSystemSecurity = File.GetAccessControl(TextBox1.Text)
fs.RemoveAccessRule(New FileSystemAccessRule(Environment.UserName, FileSystemRights.FullControl, AccessControlType.Deny))
File.SetAccessControl(TextBox1.Text, fs)
End Sub
The first one locks the directory and the other unlocks it.