I have an Access Database linked with a VB project through a data source. In the database on one of the tables, I have an OLE Object field. I have saved pictures in .BMP format and .JPG format in this field. The problem I am encountering is loading this image into my application. This is what I would like to be able to do:
ButtonMeal1.BackgroundImage = IPOSDBDataSet.Meals.Rows(0).Item(5)
Where Item(5) is the column of the row where the image is stored.
Is there another way of doing this. Do I have to load the picture into the program by storing it as a variable, and then using that to change the background image of the button. There are no clear answers on the internet regarding my issue. Please help!
EDIT 1:
After doing some more research, I found some code and adjusted it to try fix my problem.
Dim ImageByteArray As Byte() = CType(IPOSDBDataSet.Meals.Rows(0).Item(5), Byte())
Dim ImageMemoryStream As MemoryStream = New IO.MemoryStream(ImageByteArray)
Dim MyImage As Image = Drawing.Image.FromStream(ImageMemoryStream)
PictureBox1.Image = MyImage
However, I receive the error "Parameter is Not Valid" with the 3rd line of the code. Would anyone be able to tell me how I could adjust my code to fix this issue, or tell me if I am doing something completely wrong?
EDIT 2:
I keep on changing the code around, but the error is always "Parameter is not valid.". What parameter is not valid?
EDIT 3:
No matter what I change it to, the error still persists. What is this parameter that is causing all my issues?
Dim ImageByteArray As Byte() = CType(IPOSDBDataSet.Meals.Rows(0).Item(5), Byte())
Dim ImageMemoryStream As MemoryStream = New IO.MemoryStream(ImageByteArray)
Dim ImageStream As Stream = ImageMemoryStream
Dim MyImage As Image = Drawing.Image.FromStream(ImageStream)
PictureBox1.Image = MyImage
EDIT 4:
Can anyone please help? I really need to be able to implement this into my program. Is there any other possible way of storing images in an access database, and importing them into my vb.net program?
Credit goes to TnTinMan from CodeProject for the answer. Hopefully this helps someone else:
Dim ImageByteArray As Byte() = CType(DataSet.Table.Rows(RowNo).Item(ItemNo), Byte())
Dim ImageMemoryStream As MemoryStream = New IO.MemoryStream(GetImageBytesFromOLEField(ImageByteArray))
Dim MyImage As Image = Drawing.Image.FromStream(ImageMemoryStream)
Friend Shared Function GetImageBytesFromOLEField(ByVal oleFieldBytes() As Byte) As Byte()
Dim BITMAP_ID_BLOCK As String = "BM"
Dim JPG_ID_BLOCK As String = ChrW(&HFF).ToString() & ChrW(&HD8).ToString() & ChrW(&HFF).ToString()
Dim PNG_ID_BLOCK As String = ChrW(&H89).ToString() & "PNG" & vbCrLf & ChrW(&H1A).ToString() & vbLf
Dim GIF_ID_BLOCK As String = "GIF8"
Dim TIFF_ID_BLOCK As String = "II*" & ChrW(&H0).ToString()
Dim imageBytes() As Byte
' Get a UTF7 Encoded string version
Dim u7 As System.Text.Encoding = System.Text.Encoding.UTF7
Dim strTemp As String = u7.GetString(oleFieldBytes)
Dim st2 As String = System.Text.Encoding.UTF8.GetString(oleFieldBytes)
' Get the first 300 characters from the string
Dim strVTemp As String = strTemp.Substring(0, 300)
' Search for the block
Dim iPos As Integer = -1
If strVTemp.IndexOf(BITMAP_ID_BLOCK) <> -1 Then
iPos = strVTemp.IndexOf(BITMAP_ID_BLOCK)
ElseIf strVTemp.IndexOf(JPG_ID_BLOCK) <> -1 Then
iPos = strVTemp.IndexOf(JPG_ID_BLOCK)
ElseIf strVTemp.IndexOf(PNG_ID_BLOCK) <> -1 Then
iPos = strVTemp.IndexOf(PNG_ID_BLOCK)
ElseIf strVTemp.IndexOf(GIF_ID_BLOCK) <> -1 Then
iPos = strVTemp.IndexOf(GIF_ID_BLOCK)
ElseIf strVTemp.IndexOf(TIFF_ID_BLOCK) <> -1 Then
iPos = strVTemp.IndexOf(TIFF_ID_BLOCK)
Else
Throw New Exception("Unable to determine header size for the OLE Object")
End If
' From the position above get the new image
If iPos = -1 Then
Throw New Exception("Unable to determine header size for the OLE Object")
End If
imageBytes = New Byte(CInt(oleFieldBytes.LongLength - iPos - 1)) {}
Array.ConstrainedCopy(oleFieldBytes, iPos, imageBytes, 0, oleFieldBytes.Length - iPos)
Return imageBytes
End Function
There isn't really such a thing as an 'image' stored in an Access table, only a binary stream. Therefore, the left hand side of your expression doesn't know that the right hand side is providing an image. You would have to stream the binary stream into a stream in VB.NET, then use System.Graphics methods to make it into a BMP or PNG or whatever. You could assign that object to the button.
still show error: index and length must refer to a location within the string.Parameter name: len
Related
I'm working on a windows forms application, using vb.net and microsoft sql server as backend. As for the reports, I'm using microsoft's rdlc, which has been quite satisfactory for me until I was struck with this distinct problem.
So, in the report I'm using external images, which are loaded through local filepaths, passed as parameters. I retrieve these paths from the database and pass it to the report. This method worked for me for a long time, until it stopped working. Now the case is, that the external images are not loading in the report (a red cross is displayed instead of the image). As far as I feel, this problem has something to do with permissions on my PC because the same code and configurations worked for me before, but I'm not able to resolve it. I have searched everywhere to no end and would definitely want assistance.
My code for the report is:
Try
With Me.ReportViewer1.LocalReport
.DataSources.Clear()
.ReportPath = Application.StartupPath & "\RptArticle.rdlc"
.EnableExternalImages = True
Dim imagepathstring As String = System.IO.Path.Combine(folder & "\ArticlePics", imagepath)
Dim imgparameter As New ReportParameter
imgparameter = New ReportParameter("ImagePath", "file://" & imagepathstring, True)
.SetParameters(imgparameter)
Dim barpathstring As String = System.IO.Path.Combine(folder & "\BarCode", barpath)
Dim barcode As New ReportParameter("Barcode", "file://" & barpathstring, True)
.SetParameters(barcode)
.DataSources.Add(New Microsoft.Reporting.WinForms.ReportDataSource("DSArticleAccessory", Accdt))
.DataSources.Add(New Microsoft.Reporting.WinForms.ReportDataSource("DSArticleSize", AccSdt))
.DataSources.Add(New Microsoft.Reporting.WinForms.ReportDataSource("DSArticleColour", AccCdt))
.DataSources.Add(New Microsoft.Reporting.WinForms.ReportDataSource("DSArticleColour", AccCdt))
.DataSources.Add(New Microsoft.Reporting.WinForms.ReportDataSource("DSArticle", dt))
End With
Me.ReportViewer1.ZoomMode = ZoomMode.PageWidth
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
Me.ReportViewer1.RefreshReport()
When I load the report, the output is:
Warning: Images with external URL references will not display if the report is published to a report server without an UnattendedExecutionAccount or the target image(s) are not enabled for anonymous access. (rsWarningFetchingExternalImages)
Warning: The value of the MIMEType property for the image ‘Image1’ is “application/octet-stream”, which is not a valid MIMEType. (rsInvalidMIMEType)
Warning: The value of the ImageData property for the image ‘Image1’ is “”, which is not a valid ImageData. (rsInvalidExternalImageProperty)
Warning: The value of the MIMEType property for the image ‘Image2’ is “application/octet-stream”, which is not a valid MIMEType. (rsInvalidMIMEType)
Warning: The value of the ImageData property for the image ‘Image2’ is “”, which is not a valid ImageData. (rsInvalidExternalImageProperty)
The thread 0x3948 has exited with code 0 (0x0).
Instead of using external images, you can pass your images as string to your report as parameters.
Convert your image to Base64 string first using this:
Public Function ImageToBase64(ByVal image As Image, ByVal format As System.Drawing.Imaging.ImageFormat) As String
Dim base64String As String = ""
Using ms As New System.IO.MemoryStream()
image.Save(ms, format)
Dim imageBytes As Byte() = ms.ToArray()
base64String = Convert.ToBase64String(imageBytes)
End Using
Return base64String
End Function
So this:
Dim imagepathstring As String = System.IO.Path.Combine(folder & "\ArticlePics", imagepath)
Dim imgparameter As New ReportParameter
imgparameter = New ReportParameter("ImagePath", "file://" & imagepathstring, True)
.SetParameters(imgparameter)
Dim barpathstring As String = System.IO.Path.Combine(folder & "\BarCode", barpath)
Dim barcode As New ReportParameter("Barcode", "file://" & barpathstring, True)
.SetParameters(barcode)
will be like this:
Dim imagepathstring As String = System.IO.Path.Combine(folder & "\ArticlePics", imagepath)
Dim imgparameter As New ReportParameter
imgparameter = New ReportParameter("ImagePath", ImageToBase64(Image.FromFile(imagepathstring),<THE IMAGE FORMAT OF YOUR IMAGE>))
.SetParameters(imgparameter)
Dim barpathstring As String = System.IO.Path.Combine(folder & "\BarCode", barpath)
Dim barcode As New ReportParameter("Barcode", ImageToBase64(Image.FromFile(barpathstring),<THE IMAGE FORMAT OF YOUR IMAGE>))
.SetParameters(barcode)
Then, in your report set the following for:
ImagePath
MIMEType = select the correct MIME type from the dropdown list
Source = Database
Value = <Expression>
and in the Expression window:
=System.Convert.FromBase64String(Parameters!ImagePath.Value)
Barcode
MIMEType = select the correct MIME type from the dropdown list
Source = Database
Value = <Expression>
=System.Convert.FromBase64String(Parameters!Barcode.Value)
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()
Am trying to copy my image value to text file. my code is below.
If fldtype = "System.Byte[]" Then
Dim bits As Byte() = CType(drow(dc), Byte())
Using ms As New MemoryStream(bits)
Dim sw As New StreamWriter(ms)
Dim sr As New StreamReader(ms)
Dim myStr As String = sr.ReadToEnd()
MessageBox.Show(myStr)
fldvalue = fldvalue + "," + myStr
End Using
I find this to be one of the easiest ways to write a Byte[] to a string:
If fldtype = "System.Byte[]" Then
Dim bits As Byte() = CType(drow(dc), Byte())
Dim s As String = Convert.ToBase64String(bits)
End If
Works in reverse, too:
Dim newBytes() As Byte = Convert.FromBase64String(s)
The answer linked in the original comments could prove to be better options. Answering these questions would go a long way:
Why write an image out to text in the first place?
What do you mean to do with it once it's there?
Do you need to be able to retrieve that string and re-form the original image?
Question #3 is especially important because the information you are capturing matters when it comes to image format information. That could be lost, making it difficult to reconstitute the original image 100%.
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.
I need a solution to my current code, I am trying to save text to a file from a Text Box, and add a string to it.
My following code is:
Dim fs As FileStream = File.Create(fileName.Text)
' Add text to the file.
Dim info As Byte() = New UTF8Encoding(True).GetBytes(CodeBox.Text)
Dim Code = "-- Made with LUA Creator by Sam v1.9
" + info
fs.Write(Code, 0, Code.Length)
fs.Close()
MsgBox("File saved as " + fileName.Text)
But Visual Studio says that I cannot use "+" operator with strings & bytes:
Error BC30452 Operator '+' is not defined for types 'String' and 'Byte()'.
Anyone have a solution?
Sorry if this is a duplicate, I couldn't find it anywhere here so I just asked myself. Thanks.
"Can I Convert A Byte() to a string?" Short answer is yes, but that doesn't look like what you're really wanting to do.
You're trying to concatenate a String with a Byte array, which Dim Code has no idea what the end result is supposed to be.
FileStream.Write() requires a Byte array so you can try a couple of things
Concatenate the string from the TextBox with your "header" information then turn it into a Byte array.
Dim fs As FileStream = File.Create(fileName.Text)
' Add text to the file.
Dim Code As Byte() = New UTF8Encoding(true).GetBytes("-- Made with LUA Creator by Sam v1.9 " & CodeBox.Text)
fs.Write(Code, 0, Code.Length)
fs.Close()
Write your "header" information, then write the Textbox information
Dim fs As FileStream = File.Create(fileName.Text)
' Add text to the file.
Dim header As Byte() = New UTF8Encoding(true).GetBytes("-- Made with LUA Creator by Sam v1.9 ")
Dim info As Byte() = New UTF8Encoding(True).GetBytes(CodeBox.Text)
fs.Write(header, 0, header.Length)
fs.Write(info, 0, info.Length)
fs.Close()