Save multiple images to database. Write exception for empty picture boxes - vb.net

I have 4 picture boxes on my form that I use to store images and send to my database: I do it through a table adapter. The images are converted to a stream through this Function:
Public Function ConvertImage(ByVal myImage As Image) As Byte()
'store image in memory before converting and
'create memory stream, save image in proper format
Dim mStream As New MemoryStream
myImage.Save(mStream, System.Drawing.Imaging.ImageFormat.Jpeg)
'convert new stream into bytes and indicate size
Dim myBytes(mStream.Length - 1) As Byte
mStream.Position = 0
mStream.Read(myBytes, 0, mStream.Length)
Return myBytes
End Function
The problem I have is when one or more of my picture boxes have no images, how do I indicate on procedure if one or more picture boxes are empty, then set the image to Nothing. Here is a shorten version of my procedure as it is now
Private Sub btnSaveCategory_Click(sender As Object, e As EventArgs) Handles btnSaveCategory.Click
Dim picImage As Image = picBox1.Image
Dim picImage 2 As Image = picBox2.Image
Dim picImage 3 As Image = picBox3.Image
Dim picImage 4 As Image = picBox4.Image
PRODUCT_CATEGORYTableAdapter.InsertNewCategory(txtCategoryName.Text, ConvertImage(picImage),Image(picImage2), Image(picImage3), Image(picImage4))
End Sub
How can I check for an empty picture box and set it to empty so my procedure does not error out because an image does not exist on one or more boxes?
Thank you.

Try this
If pictureBox.Image is Nothing Then
//do stuff here
End If

Related

Error Multiple Read 2D barcode from image ( A generic error occurred in GDI+.)

I want to read 2D matrixcode from an image that I captured using camera and display it on a picturebox. The image will be saved from picturebox and then it will read the value of 2D matrixcode from the image.
I managed to read it one time. However, the second time I click the button to read it, it appeared this error. ": A generic error occurred in GDI+."
I want it able to capture it multiple time for each time I click.
Below are my attached code :
Dim filepath As String = Environment.CurrentDirectory
Dim current2 As Bitmap = CType(PictureBoxFilter.Image, Bitmap)
Dim fileName2 As String = System.IO.Path.Combine(filepath, "test.png")
current2.Save(fileName2)
Dim decoder As DmtxImageDecoder = New DmtxImageDecoder()
Dim codes As List(Of String) = decoder.DecodeImage(CType(Bitmap.FromFile(System.IO.Path.Combine(filepath, "test.png")), Bitmap), 1, New TimeSpan(0, 0, 3))
For Each code As String In codes
If code <> "" Then
Label1.Text = code
Else
Label1.Text = ""
End If
Next
codes.Clear()
current2.Dispose()

Converting Ink to Base64 and then to Image gets shapes cropped

I am using the function below to convert some ink shapes I have drawn on a picturebox control to Base64
Function GetBase64(ByVal InkCollector As InkCollector) As String
Dim utf8 As UTF8Encoding = New UTF8Encoding()
InkCollector.Enabled = False
Return utf8.GetString(InkCollector.Ink.Save(PersistenceFormat.Base64InkSerializedFormat, CompressionMode.Maximum))
InkCollector.Enabled = True
End Function
I can then use the string to reproduce the sketch into a new image by feeding it to this function:
Function Base64toImage(ByVal Base64 As String) As System.Drawing.Image
Dim utf8 As UTF8Encoding = New UTF8Encoding()
Dim imgSig As System.Drawing.Image
Dim tmploadedInk As Ink = New Ink()
Dim strGIF As String
Dim imageBytes() As Byte
Dim MS As MemoryStream
'Load the Base64 String in Format(PersistenceFormat = Base64InkSerializedFormat) as ink
tmploadedInk.Load(utf8.GetBytes(Base64))
'Convert the ink to Base64 String in format (PersistenceFormat.Gif, CompressionMode.Maximum)
strGIF = Convert.ToBase64String(tmploadedInk.Save(PersistenceFormat.Gif, CompressionMode.Maximum))
'Convert Base64 String to Byte Array
imageBytes = Convert.FromBase64String(strGIF)
MS = New MemoryStream(imageBytes, 0, imageBytes.Length)
' Convert byte[] to Image
MS.Write(imageBytes, 0, imageBytes.Length)
imgSig = Image.FromStream(MS, True)
Return imgSig
End Function
This works fine except for the fact the shapes are cropped and therefore they get aligned to the top left corner of the generated image. If I use a line of code like below:
PictureBox1.Image = Signiture.Base64toImage(Signiture.GetBase64(Sketch_InkCollector))
The shapes appear at the top left and ignore the fact that they might have been drawn at the center of the original picture box. I believe that the positioning data is being properly saved into the Base64 string, but are somehow being ignored when the shapes are transferred to the image variable. The reason I believe this is because when I use the function below with the Base64 string, the shapes get placed properly in their original position.
Sub SetBase64PictureBox(ByVal InkCollector As InkCollector, ByVal PictureBox As PictureBox, ByVal Base64 As String)
Dim loadedInk As Ink = New Ink()
Dim utf8 As UTF8Encoding = New UTF8Encoding()
InkCollector.Enabled = False
InkCollector.Ink.DeleteStrokes() ' Clear all strokes
loadedInk.Load(utf8.GetBytes(Base64))
InkCollector.Ink = loadedInk
InkCollector.Enabled = True
PictureBox.Invalidate()
End Sub
Thank you
Update:
Found a temporary solution in this link:
InkPicture control - How to save both ink and image to an image file
It is not exactly what I was after but the end result is the same since I wanted to the combined picture and the ink strokes into an image to show in a PDF file.

Extract Images with text from PDF and Edit it using iTextSharp

I am trying to do following things in Windows Forms
1) Read a PDF in Windows Forms
2) Get the Images with Text in it
3) Color / fill the Image
4) save everything to a new file
I have tried Problem with PdfTextExtractor in itext!
But It didn't help.
Here is the code I've tried:
Public Shared Sub ExtractImagesFromPDF(sourcePdf As String, outputPath As String)
'NOTE: This will only get the first image it finds per page.'
Dim pdf As New PdfReader(sourcePdf)
Dim raf As RandomAccessFileOrArray = New iTextSharp.text.pdf.RandomAccessFileOrArray(sourcePdf)
Try
For pageNumber As Integer = 1 To pdf.NumberOfPages
Dim pg As PdfDictionary = pdf.GetPageN(pageNumber)
' recursively search pages, forms and groups for images.'
Dim obj As PdfObject = FindImageInPDFDictionary(pg)
If obj IsNot Nothing Then
Dim XrefIndex As Integer = Convert.ToInt32(DirectCast(obj, PRIndirectReference).Number.ToString(System.Globalization.CultureInfo.InvariantCulture))
Dim pdfObj As PdfObject = pdf.GetPdfObject(XrefIndex)
Dim pdfStrem As PdfStream = DirectCast(pdfObj, PdfStream)
Dim bytes As Byte() = PdfReader.GetStreamBytesRaw(DirectCast(pdfStrem, PRStream))
If (bytes IsNot Nothing) Then
Using memStream As New System.IO.MemoryStream(bytes)
memStream.Position = 0
Dim img As System.Drawing.Image = System.Drawing.Image.FromStream(memStream)
' must save the file while stream is open.'
If Not Directory.Exists(outputPath) Then
Directory.CreateDirectory(outputPath)
End If
Dim path__1 As String = Path.Combine(outputPath, [String].Format("{0}.jpg", pageNumber))
Dim parms As New System.Drawing.Imaging.EncoderParameters(1)
parms.Param(0) = New System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Compression, 0)
'Dim jpegEncoder As System.Drawing.Imaging.ImageCodecInfo = iTextSharp.text.Utilities.GetImageEncoder("JPEG")'
img.Save(path__1) 'jpegEncoder, parms'
End Using
End If
End If
Next
Catch
Throw
Finally
pdf.Close()
raf.Close()
End Try
End Sub
Now, the actual purpose of this is to get something like this
If this is the actual PDF, I will have to check if there any any items in that bin(by Text in that box)
If there are items then I have to color it like below
Can someone help me with this
The PDF can be retrieved here.

Sending and Receiving Bitmaps per TcpClients

So, I'm currently making a LAN-Streaming-Program, which should record the screen of the streamer and display it at the viewer's screen.
My problem is, that when I try to convert the received ByteArray-Image to an image, it gives me a System.ArgumentException.
Here's the code for sending:
Private Sub SendFrame(ByRef IP As String, ByRef Frame As Bitmap)
FrameClient = New TcpClient(IP, 7009)
Dim FrameStream As New MemoryStream
Dim FrameBytes() As Byte
Frame.Save(FrameStream, ImageFormat.Bmp)
FrameBytes = FrameStream.GetBuffer()
SendMessage(IP, "NextFrameSize;" & LocalIP & ";" & FrameBytes.Length)
Using NS As NetworkStream = FrameClient.GetStream
NS.Write(FrameBytes, 0, FrameBytes.Length)
NS.Close()
End Using
End Sub
And here for receiving:
Private Sub CheckForFrames() 'This Sub is called everytime the viewer receives the size of the next Bitmap.
If FrameListener.Pending = True Then
FrameClient = FrameListener.AcceptTcpClient
Dim ImageBytes(NextFrameSize) As Byte
FrameClient.GetStream.Read(ImageBytes, 0, NextFrameSize)
Dim MS As New MemoryStream(ImageBytes)
StreamBox.Image = Image.FromStream(MS, False)
MS.Close()
FlushMemory()
End If
End Sub
I would be thankful for any answers!
Dim ImageBytes(FrameClient.ReceiveBufferSize) As Byte
This returns the size of te buffer, not the actual size of the bitmap:
The size of the receive buffer, in bytes. The default value is 8192
bytes.
So, ImageBytes will probably be 8192 bytes, not the size of your bitmap.
You might want to send the size before you send the bitmap data, and on the receive side read in the size first to initialize your MemoryStream.

Put content of fileStream in dataset

I want to read Stream that i get from XtrapivotGrid of DevExpress. I can save it in the computer but what i want is to save it in one of my table in my dataset called dataset1.
For now i have that code who permit to save it the directory Temp:.
Using FS As New IO.FileStream("D:\Temp\qqc.layout", IO.FileMode.Create)
PivotGridControl1.SaveLayoutToStream(FS)
End Using
Dim read As New System.IO.FileStream("D:\Temp\qqc.layout", IO.FileMode.Open, IO.FileAccess.Read)
DataSet1.LayoutMainRapport.ReadXml(read)
DataSet1.AcceptChanges()
read.Close()
The table LayoutMainRapport have 3 columns:
ID(Int)
Name(nvarchar(50))
Content(xml).
The output from the stream is xml.
thanks in advance!
I believe you should convert your saved layout into string and then save this string to database (and of course you can load this layout back from the database string value):
Private Function SaveLayoutToString(ByVal dxControl As DevExpressControl) As String
Using ms As MemoryStream = New MemoryStream()
dxControl.SaveLayoutToStream(ms)
Return Convert.ToBase64String(ms.ToArray())
End Using
End Function
Private Sub RestoreLayoutFromString(ByVal dxControl As DevExpressControl, ByVal layout As String)
If String.IsNullOrEmpty(layout) Then
Return
End If
Using ms As MemoryStream = New MemoryStream(Convert.FromBase64String(layout))
dxControl.RestoreLayoutFromStream(ms)
End Using
End Sub
Here DevExpressControl dxControl is the DevExpress control which supports saving and loading layout (XtraPivotGrid, XtraGrid, XtraLayoutControl etc.)
I simply had to save a name for the xml and after save it into my dataset.
Dim saveDialog As SaveLayout = New SaveLayout
If saveDialog.ShowDialog() = Windows.Forms.DialogResult.OK Then
Dim read As New IO.MemoryStream
PivotGridControl1.SaveLayoutToStream(read)
read.Position = 0
Dim lecteur As New IO.StreamReader(read)
Dim ligne As DataRow = DataSet1.LayoutMainRapport.NewRow()
ligne("Nom") = saveDialog.txtNom.Text
ligne("Contenu") = lecteur.ReadToEnd()
DataSet1.LayoutMainRapport.Rows.Add(ligne)
LayoutMainRapportTableAdapter.Update(DataSet1)
End If