Bitmap ctor throws an exception - vb.net

I can't figure out the solution. This is my code:
Dim wbRect As Rectangle = WebBrowser1.ClientRectangle
Dim wbBm As New Bitmap(WebBrowser1.ClientRectangle.Width, WebBrowser1.ClientRectangle.Height)
Dim gwb As Graphics = Graphics.FromImage(wbBm)
gwb.CopyFromScreen(WebBrowser1.PointToScreen(New Point(14, 31)),
New Point(0, 0),
New Size(PictureBox1.Width, PictureBox1.Height))
wbBm.Save("c:\temp1.bmp")
PictureBox1.ImageLocation = "c:\temp1.bmp"
PictureBox1.BringToFront()
Dim bm As New Bitmap("c:\img1.bmp") //here appears an error - Parameter is not valid
Dim rect As New Rectangle(0, 0, bm.Width, bm.Height)
Dim bmpData As System.Drawing.Imaging.BitmapData = bm.LockBits(rect, _
System.Drawing.Imaging.ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb)
What could I do to remove the error?

You will get this error if the file does not exist. Check to make sure img1.bmp exists before you try and open it:
Dim fn As String = "c:\img1.bmp"
If File.Exists(fn)
Dim bm As New Bitmap(fn) ''here appears an error - Parameter is not valid
Dim rect As New Rectangle(0, 0, bm.Width, bm.Height)
Dim bmpData As System.Drawing.Imaging.BitmapData = bm.LockBits(rect, _
System.Drawing.Imaging.ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb)
End If

Related

editing PDF to add page number | VB.net

I am looking to modify the pdf to add the page number and I cannot find why the variable "cb" is empty.
you can see error on the screen below
Error on the screen : "Object reference not set to an instance of an object"
I just found how to edit pdf and add pages number, here is my code for those who need it.
I copy a file, I count the number of pages, in a while loop I display the number of pages (1/3) then I import the page on which I wanted to add the number of pages.
Public Sub ModifPDF(ByVal annee As Integer, ByVal mois As Integer, ByVal nomFichier As String, ByVal sourceFileList As String)
Dim Col1 As PdfPCell
Dim Col2 As PdfPCell
Dim Font1 As New Font(FontFactory.GetFont(FontFactory.HELVETICA, 1, iTextSharp.text.Font.NORMAL))
Dim Font8 As New Font(FontFactory.GetFont(FontFactory.HELVETICA, 8, iTextSharp.text.Font.NORMAL))
Dim Vide As PdfPCell = New PdfPCell(New Phrase("")) With {
.Border = 0
}
Dim reader As New PdfReader(sourceFileList)
Dim sourceFilePageCount As Integer = reader.NumberOfPages
Dim doc As New Document(reader.GetPageSizeWithRotation(1))
My.Computer.FileSystem.CopyFile(sourceFileList, "C:\test")
Dim writer As PdfWriter = PdfWriter.GetInstance(doc, New FileStream("C:\test", FileMode.Open, FileAccess.Write))
doc.Open()
Dim contentByte As PdfContentByte = writer.DirectContent
Dim pageIndex As Integer = 0
While pageIndex < sourceFilePageCount
pageIndex = pageIndex + 1
doc.SetPageSize(reader.GetPageSize(pageIndex))
Dim TableNota As PdfPTable = New PdfPTable(2)
Dim widthsNota As Single() = New Single() {19.7F, 1.5F}
TableNota.WidthPercentage = 97
TableNota.SetWidths(widthsNota)
Col1 = New PdfPCell(New Phrase(" ", Font8)) With {
.Border = 0
}
TableNota.AddCell(Col1)
Col2 = New PdfPCell(New Phrase("page " & pageIndex & "/" & sourceFilePageCount & "", Font8)) With {
.Border = 0
}
TableNota.AddCell(Col2)
TableNota.AddCell(Vide)
doc.Add(TableNota)
Dim page = writer.GetImportedPage(reader, pageIndex)
Dim rotation = reader.GetPageRotation(pageIndex)
If rotation.Equals(90) Then
contentByte.AddTemplate(page, 0, -0.1F, 1.0F, 0, 0, reader.GetPageSizeWithRotation(pageIndex).Height)
Else
contentByte.AddTemplate(page, 1.0F, 0, 0, 1.0F, 0, 0)
End If
doc.NewPage()
End While
doc.Close()
End Sub

Warning Variable 'csCryptoStream' is used before it has been assigned a value. A null reference exception could result at runtime

Im new to VB.Net. I am trying to debug my project, but I get a warning: Variable 'csCryptoStream' is used before it has been assigned a value. A null reference exception could result at runtime
How can I fix it?
Private Sub EncryptOrDecryptFile(strInputFile As String, strOutputFile As String, bytKey As Byte(), bytIV As Byte(), Direction As crypt.CryptoAction)
' The following expression was wrapped in a checked-statement
Try
Me.fsInput = New FileStream(strInputFile, FileMode.Open, FileAccess.Read)
Me.fsOutput = New FileStream(strOutputFile, FileMode.OpenOrCreate, FileAccess.Write)
Me.fsOutput.SetLength(0L)
Dim bytBuffer As Byte() = New Byte(4096) {}
Dim lngBytesProcessed As Long = 0L
Dim lngFileLength As Long = Me.fsInput.Length
Dim cspRijndael As RijndaelManaged = New RijndaelManaged()
Me.pbStatus.Value = 0
Me.pbStatus.Maximum = 100
Dim csCryptoStream As CryptoStream
Select Case Direction
Case crypt.CryptoAction.ActionEncrypt
csCryptoStream = New CryptoStream(Me.fsOutput, cspRijndael.CreateEncryptor(bytKey, bytIV), CryptoStreamMode.Write)
Case crypt.CryptoAction.ActionDecrypt
csCryptoStream = New CryptoStream(Me.fsOutput, cspRijndael.CreateDecryptor(bytKey, bytIV), CryptoStreamMode.Write)
End Select
While lngBytesProcessed < lngFileLength
Dim intBytesInCurrentBlock As Integer = Me.fsInput.Read(bytBuffer, 0, 4096)
Warning ---> csCryptoStream.Write(bytBuffer, 0, intBytesInCurrentBlock)
' The following expression was wrapped in a unchecked-expression
lngBytesProcessed += CLng(intBytesInCurrentBlock)
' The following expression was wrapped in a unchecked-expression
Me.pbStatus.Value = CInt(Math.Round(CDec(lngBytesProcessed) / CDec(lngFileLength) * 100.0))
End While
Declare the CryptoStream as below:
Dim csCryptoStream As CryptoStream = Nothing
Add a 'Case Else' clause in your Case/Select
Before using this variable check if
If Not IsNothing(csCryptoStream)
' ....
End If

Crop image and save it in database using vb.net

I'm following a tutorial on Image Cropping with resizing using vb.net . Everything works well, But instead of saving it
on the hard disk. I want to save it on my database(SQLServer).
This is the code of saving on a disk
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cropSaveBtn.Click
Dim tempFileName As String
Dim svdlg As New SaveFileDialog()
svdlg.Filter = "JPEG files (*.jpg)|*.jpg|All files (*.*)|*.*"
svdlg.FilterIndex = 1
svdlg.RestoreDirectory = True
If svdlg.ShowDialog() = Windows.Forms.DialogResult.OK Then
tempFileName = svdlg.FileName 'check the file exist else save the cropped image
Try
Dim img As Image = PreviewPictureBox.Image
SavePhoto(img, tempFileName, 225)
Catch exc As Exception
MsgBox("Error on Saving: " & exc.Message)
End Try
End If
End Sub
Public Function SavePhoto(ByVal src As Image, ByVal dest As String, ByVal w As Integer) As Boolean
Try
Dim imgTmp As System.Drawing.Image
Dim imgFoto As System.Drawing.Bitmap
imgTmp = src
imgFoto = New System.Drawing.Bitmap(w, 225)
Dim recDest As New Rectangle(0, 0, w, imgFoto.Height)
Dim gphCrop As Graphics = Graphics.FromImage(imgFoto)
gphCrop.SmoothingMode = SmoothingMode.HighQuality
gphCrop.CompositingQuality = CompositingQuality.HighQuality
gphCrop.InterpolationMode = InterpolationMode.High
gphCrop.DrawImage(imgTmp, recDest, 0, 0, imgTmp.Width, imgTmp.Height, GraphicsUnit.Pixel)
Dim myEncoder As System.Drawing.Imaging.Encoder
Dim myEncoderParameter As System.Drawing.Imaging.EncoderParameter
Dim myEncoderParameters As System.Drawing.Imaging.EncoderParameters
Dim arrayICI() As System.Drawing.Imaging.ImageCodecInfo = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders()
Dim jpegICI As System.Drawing.Imaging.ImageCodecInfo = Nothing
Dim x As Integer = 0
For x = 0 To arrayICI.Length - 1
If (arrayICI(x).FormatDescription.Equals("JPEG")) Then
jpegICI = arrayICI(x)
Exit For
End If
Next
myEncoder = System.Drawing.Imaging.Encoder.Quality
myEncoderParameters = New System.Drawing.Imaging.EncoderParameters(1)
myEncoderParameter = New System.Drawing.Imaging.EncoderParameter(myEncoder, 60L)
myEncoderParameters.Param(0) = myEncoderParameter
imgFoto.Save(dest, jpegICI, myEncoderParameters)
imgFoto.Dispose()
imgTmp.Dispose()
Catch ex As Exception
End Try
End Function
I want it to save the picture to SQL Server 2008 (Image data type) together with my two data just like this
Using cmd As New SqlClient.SqlCommand("dbo.uspAdd", cn)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.Add("#firstname", SqlDbType.VarChar, 100).Value = txtName.Text
cmd.Parameters.Add("#lastName", SqlDbType.VarChar, 100).Value = txtSurname.Text
'add insert picture code here
cmd.ExecuteNonQuery()
MsgBox("Save Record New record Successfully")
End Using
And now i'm stuck for almost 8 hours finding ways on how to fix this.Can anyone help me to solve this. Any help would be very much appreciated.
I would suggest converting the image to Base64 and then storing it as a string.
Then when you want to get the image back you need to convert it back from Base64 to an image.
You can convert an image to Base64 using this code:
Public Function ConvertImageToBase64(ByRef img As Image, ByVal format As System.Drawing.Imaging.ImageFormat) As String
Dim ImgStream As MemoryStream = New MemoryStream()
img.Save(ImgStream, format)
ImgStream.Close()
Dim ByteArray() As Byte = ImgStream.ToArray()
ImgStream.Dispose()
Return Convert.ToBase64String(ByteArray)
End Function
(http://www.dailycoding.com/posts/convert_image_to_base64_string_and_base64_string_to_image.aspx)
And to convert it back to an image you can use this code:
Public Function ConvertBase64ToImage(ByVal base64 As String) As Image
Dim img As System.Drawing.Image
Dim MS As System.IO.MemoryStream = New System.IO.MemoryStream
Dim b64 As String = base64.Replace(" ", "+")
Dim b() As Byte
b = Convert.FromBase64String(b64)
MS = New System.IO.MemoryStream(b)
img = System.Drawing.Image.FromStream(MS)
Return img
End Function
(http://snipplr.com/view/27514/vbnet-base64-to-image/)
Now you can basically add the image as a string, like this:
Dim Base64Bitmap As String = ConvertImageToBase64(img, System.Drawing.Imaging.ImageFormat.Png)
cmd.Parameters.Add("#Image", SqlDbType.VarChar, Base64Bitmap.Length).Value = Base64Bitmap

Saving image over open file, A Generic error occurred in GDI+

I'm having trouble with my code, I'm trying to make a simple captcha for my program. The first time I run the sub it works fine, I'm guessing because the file is not "open" in my program. The second time I get the GDI+ error. I'm pretty sure this is an issue with the bitmaps being locked the 2nd time around, I'm just a little stuck.
Sub generatePasswordImage(password As String)
'This is the image where we are going to write the text on it.
Dim stringMasterImageName As String = Application.StartupPath + "\MasterImage.jpg"
Dim bitmapImage As Bitmap = New System.Drawing.Bitmap(stringMasterImageName)
Dim bitmapMasterImage As Bitmap = New System.Drawing.Bitmap(bitmapImage, New Size(400, 150))
Dim graphicsMasterImage As Graphics = Graphics.FromImage(bitmapMasterImage)
'Set the alignment based on the coordinates
Dim stringformatWriteTextFormat As StringFormat = New StringFormat()
stringformatWriteTextFormat.Alignment = StringAlignment.Center
'Do some rotation effects
Dim Generator As System.Random = New System.Random()
Dim rotation As Integer = Generator.Next(-10, 5)
graphicsMasterImage.RotateTransform(rotation)
Dim centerImgWidth As Integer = Generator.Next(CInt(graphicsMasterImage.VisibleClipBounds.Size.Width / 3), CInt(graphicsMasterImage.VisibleClipBounds.Size.Width / 2))
Dim centerImgHiehgt As Integer = Generator.Next(CInt(graphicsMasterImage.VisibleClipBounds.Size.Height / 3), CInt(graphicsMasterImage.VisibleClipBounds.Size.Height / 2))
'Set the font color
Dim colorStringColor As Color = System.Drawing.Color.Black
graphicsMasterImage.DrawString(password, New Font("Tahoma", 14, FontStyle.Bold), _
New SolidBrush(colorStringColor), New Point(centerImgWidth, centerImgHiehgt), stringformatWriteTextFormat)
Dim stringOutPutFileName As String = Application.StartupPath + "\Pass.jpg"
bitmapMasterImage.Save(stringOutPutFileName, System.Drawing.Imaging.ImageFormat.Jpeg)
bitmapMasterImage.Dispose()
bitmapImage.Dispose()
End Sub

Resize and Compress image to byte array without saving the new image

The image is first resized, compressed and then saved on disk as "Preview.jpg" and then it is opened to convert into byte array. The code works fine but I cannot figure out how to do it without saving the image on disk.
Here is the code:
Public Function GetThumb_Preview(ByVal sourceImg As String) As Byte()
Dim jgpEncoder As ImageCodecInfo = GetEncoder(ImageFormat.Jpeg)
Dim myEncoder As System.Drawing.Imaging.Encoder = System.Drawing.Imaging.Encoder.Quality
Dim myEncoderParameters As New EncoderParameters(1)
Dim myEncoderParameter As New EncoderParameter(myEncoder, 50&)
myEncoderParameters.Param(0) = myEncoderParameter
Dim myBitmap As New Bitmap(sourceImg)
Dim oWidth As Integer = myBitmap.Width
Dim oHeight As Integer = myBitmap.Height
Dim aspectRatio As Double = oHeight / oWidth
Dim thumbWidthDouble As Double = 200
Dim thumbHeightDouble As Double = Math.Round(thumbWidthDouble * aspectRatio)
Dim thumbWidth As Integer = CInt(thumbWidthDouble)
Dim thumbHeight As Integer = CInt(thumbHeightDouble)
Dim myThumb As New Bitmap(myBitmap, thumbWidth, thumbHeight)
Dim targetPreviewPath As String = "E:\Preview.jpg"
myThumb.Save(targetPreviewPath, jgpEncoder, myEncoderParameters)
Dim myImage As Image = Image.FromFile(targetPreviewPath)
Dim imgByteArray As Byte() = Nothing
'Image to byte[]
Dim imgMemoryStream As MemoryStream = New MemoryStream()
myImage.Save(imgMemoryStream, System.Drawing.Imaging.ImageFormat.Jpeg)
imgByteArray = imgMemoryStream.GetBuffer()
Return imgByteArray
End Function
That is a lot of variables to do so little. You also have a number of objects not being disposed. It will also return a valid Byte array only when the resulting byte data is less than the buffer size. It works in this case because you are resizing to 200x and reducing quality.
I didnt test if I collapsed all those variables correctly, but should be very close. More important is disposing things you create, and getting the all the Bytes for the return:
Dim jgpEncoder As ImageCodecInfo = GetEncoder(ImageFormat.Jpeg)
Dim myEncoder As System.Drawing.Imaging.Encoder =
System.Drawing.Imaging.Encoder.Quality
Dim myEncoderParameters As New EncoderParameters(1)
Dim myEncoderParameter As New EncoderParameter(myEncoder, 50&)
myEncoderParameters.Param(0) = myEncoderParameter
Dim imgByteArray As Byte()
Using myBitmap As New Bitmap(sourceImg) ' i guess this is from file
Dim aspectRatio As Double = myBitmap.Height / myBitmap.Width
' USING for disposable objects
Using myThumb As New Bitmap(myBitmap, 200,
CInt(Math.Round(200 * aspectRatio))),
ms As New MemoryStream
' encode image to memstream
myThumb.Save(ms, jgpEncoder, myEncoderParameters)
' rewind and get ALL bytes for the new image
ms.Position = 0
imgByteArray = ms.ToArray
End Using
End Using ' dispose
Return imgByteArray
You could save it to a stream and load it from there
Using Str As New MemoryStream
myThumb.Save(Str, jgpEncoder, myEncoderParameters)
myImage = Image.FromStream(Str)
End Using