Crop image and save it in database using vb.net - 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

Related

datagridview Image Display vb.net MS Access

my code is to read the image file path in every row and display it in the datagridview "Image" Column.
.....
what's the problem with my code? please help me fix this.
UPDATE
this is the updated code but it displays nothing.
Dim dbdataset As New DataTable
Try
con.Open()
query = "Select * FROM [svfmemberlist]"
cmd = New OleDbCommand(query, con)
da.SelectCommand = cmd
da.Fill(dbdataset)
dgvSearch.RowTemplate.Height = 150
source.DataSource = dbdataset
dgvSearch.DataSource = source
Dim img As New DataGridViewImageColumn()
dgvSearch.Columns.Add(img)
img.HeaderText = "Image"
img.Name = "img"
img.ImageLayout = DataGridViewImageCellLayout.Zoom
dgvSearch.Columns("img").DataGridView.AutoGenerateColumns = False
dgvSearch.Columns("Name").AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
dgvSearch.Columns("img").Width = 150
For Each row As DataGridViewRow In dgvSearch.Rows
If Not row.Cells("imgPath").FormattedValue.ToString = Nothing Then
Dim str As String = row.Cells("imgPath").FormattedValue.ToString
Dim inImg As Image = Image.FromFile(str)
row.Cells("img").Value = inImg
Else
img.Image = Nothing
End If
Next
con.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
The following example does not match how you are loading data and images but with a little effort will work within your current code.
I created two columns in the DataGridView via the IDE, one Text and one Image DataGridViewColumn.
The first line in form load sets ImageLayout, second line of code sets alignment to top-left for appearances. Next I set auto-size mode for all columns followed by setting the row height for each row.
Next (these lines are to load images from a folder one level below the app folder).
Setup the path to the images.
Add images using FileImageBytes function (which I would place into a separate class or code module but works just fine in your form).
Yes everything is hard-wired so it's easy to see how everything works.
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
CType(DataGridView1.Columns("PictureColumn"), DataGridViewImageColumn).ImageLayout = DataGridViewImageCellLayout.Normal
DataGridView1.Columns.Cast(Of DataGridViewColumn).Select(Function(col) col).ToList _
.ForEach(Sub(col) col.CellTemplate.Style.Alignment = DataGridViewContentAlignment.TopLeft)
DataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells
DataGridView1.RowTemplate.Height = 222
Dim imagePath As String = IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Images")
DataGridView1.Rows.Add(New Object() {"Car1", FileImageBytes(IO.Path.Combine(imagePath, "Car1.bmp"))})
DataGridView1.Rows.Add(New Object() {"Car2", FileImageBytes(IO.Path.Combine(imagePath, "Car2.jpg"))})
End Sub
Public Function FileImageBytes(ByVal FileName As String) As Byte()
Dim fileStream As IO.FileStream = New IO.FileStream(FileName, IO.FileMode.Open, IO.FileAccess.Read, IO.FileShare.Read)
Dim byteArray(CInt(fileStream.Length - 1)) As Byte
fileStream.Read(byteArray, 0, CInt(fileStream.Length))
Return byteArray
End Function
End Class

image in the SQL_database in vb.net

I have a problem to record the image in the SQL_database in vb.net.Enter as a file without a problem but I can not write in SQL.ABCreateNewBarcode is a PictureBox. I have a problem to take BackgroundImage from PictureBox to save in SQL. I save BackgroundImage in BarcodeImg folder but I can not save in SQl
Private Sub btnSaveBarcode_Click(sender As Object, e As EventArgs) Handles btnSaveBarcode.Click
'Create Image Object
Dim ABCreateNewBarcode As Object
ABCreateNewBarcode = CreateObject("BARCODE.BarcodeCtrl.1")
ABCreateNewBarcode.Text = txtNewBarcode.Text
ABCreateNewBarcode.typename = "Code128"
DirBarcodeImg = Application.StartupPath & "\barcodeimg"
'Save Image
If txtNewBarcode.Text = "" Then
MsgBox("Click the Create Button to create a New Barcode")
ElseIf Directory.Exists(DirBarcodeImg) = False Then
Call Directory.CreateDirectory(DirBarcodeImg)
Else
ABCreateNewBarcode.SaveAsBySize(DirBarcodeImg & "\" & txtInsertPartName.Text & ".png", 300, 130)
Dim ImageToSave As Image = ABCreateNewBarcode.BackgroundImage
Dim ms As New MemoryStream
ImageToSave.Save(ms, ImageToSave.RawFormat)
Dim buffer As Byte() = MS.GetBuffer()
'Add SQL Parameters
SQL.AddParam("#name", txtInsertPartName.Text)
SQL.AddParam("#image", buffer)
'Run Imsert Command
SQL.ExecQuery("INSERT INTRO information (PartName,BarcodeImg) " &
"VALUES (#name,#image) ")
End If
End Sub
After chaging you request "INTO" instead of "INTRO" try this line:
SQL.Parameters.AddWithValue("#image", txtInsertPartName.Text).SqlDbType = SqlDbType.Image
and replace :
Dim ms As New MemoryStream
ImageToSave.Save(ms, ImageToSave.RawFormat)
Dim buffer As Byte() = MS.GetBuffer()
by this:
Dim fs As FileStream
fs = New FileStream(imagename, FileMode.Open, FileAccess.Read)
'a byte array to read the image
Dim picbyte As Byte() = New Byte(fs.Length - 1) {}
fs.Read(picbyte, 0, System.Convert.ToInt32(fs.Length))
fs.Close()
'open the database using odp.net and insert the data
Dim buffer As Byte() =picbyte

Display an image from datagridview to a picturebox

Can anyone help me with this one? The scenario is that when I click any columns in a datagridview it will display the image to a picturebox
Private Sub DataGridView1_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
If e.RowIndex >= 0 Then
Dim row As DataGridViewRow
row = Me.DataGridView1.Rows(e.RowIndex)
lblProperty.Text = row.Cells("Column1").Value.ToString
txtType.Text = row.Cells("Column2").Value.ToString
txtPrice.Text = row.Cells("Column3").Value.ToString
txtBed.Text = row.Cells("Column4").Value.ToString
txtBath.Text = row.Cells("Column5").Value.ToString
txtFootages.Text = row.Cells("Column6").Value.ToString
txtStatus.Text = row.Cells("Column7").Value.ToString
txtYear.Text = row.Cells("Column8").Value.ToString
txtDesc.Text = row.Cells("Column9").Value.ToString
Dim bytes As [Byte]() = row.Cells("Column10").Value
Dim ms As New MemoryStream(bytes)
pbImage.Image = Image.FromStream(ms)
txtDate.Text = row.Cells("Column11").Value.ToString
txtAddress.Text = row.Cells("Column12").Value.ToString
txtStories.Text = row.Cells("Column13").Value.ToString
End If
End Sub
It has an error Unable to cast object of type 'System.String' to type 'System.Byte[]'.
Dim bytes As Byte() = Datagridview1.CurrentRow.Cells(5).Value
Using ms As New MemoryStream(bytes)
Picturebox1.Image = Image.FromStream(ms)
End Using
Maybe you are over thinking it, there is a function to easily draw bitmaps.
I would suggest using the DrawToBitmap on the DataGridView by using the ColumnBounds
example this:
Dim GridBitmap as new Bitmap(DataGridView1.GetColumnDisplayRectangle(row.Cells("Column10").ColumnIndex,false).width,DataGridView1.GetColumnDisplayRectangle(row.Cells("Column10").ColumnIndex,false).height)
DataGridView1.DrawToBitmap(GridBitmap,DataGridView1.GetColumnDisplayRectangle(row.Cells("Column10").ColumnIndex,false))
pbImage.Image = GridBitmap
It might need to be adapted to your DataGridView.
Note, Instead of this:
Dim bytes As [Byte]() = row.Cells("Column10").Value
Dim ms As New MemoryStream(bytes)
pbImage.Image = Image.FromStream(ms)
Still having problem? Try this:
New project.
Add a DataGridView (DataGridView1) to your form.
Add some random columns to your gridview.
Add a Picture Box to your form (PictureBox1)
Make sure the Picture box property "SizeMode" is set to auto size.
Add an event forDataGridView1.MouseDown.
Add this code to the event.
Dim GridBitmap As New Bitmap(DataGridView1.GetColumnDisplayRectangle(e.ColumnIndex, True).Width + DataGridView1.GetColumnDisplayRectangle(e.ColumnIndex, True).Left, DataGridView1.GetColumnDisplayRectangle(e.ColumnIndex, True).Height)
Dim GridColRectangle As New Rectangle(0, 0, DataGridView1.GetColumnDisplayRectangle(e.ColumnIndex, True).Width + DataGridView1.GetColumnDisplayRectangle(e.ColumnIndex, True).Left, DataGridView1.GetColumnDisplayRectangle(e.ColumnIndex, True).Height + DataGridView1.GetColumnDisplayRectangle(e.ColumnIndex, True).Top)
DataGridView1.DrawToBitmap(GridBitmap, GridColRectangle)
PictureBox1.Image = GridBitmap
You may need to adjust it to your own application.

Preserve Exif/Image Properties

In a web app, users can upload images, which save on the server. It creates thumbnails of the image on the back end with the following code, but all exif data of the image is lost.
I want to preserve the exif data from the original image all throughout the process, and have it included in the final stream. I can read the exif properties from the image, but can't get it to preserve when saving.
To clarify, I am not trying to read, parse, or do anything specific to the metadata itself, I just want to preserve it exactly as it was in the original image during image processing.
Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
'prepare image
Dim imgFullSize As System.Drawing.Image
'attempt to get the image
Dim sInputURL As String = HttpUtility.UrlDecode(Request.QueryString("IptFl"))
If InStr(sInputURL, "http://") > 0 Or InStr(sInputURL, "https://") Then
'from web url
Dim imgWebRequest As System.Net.WebRequest
Dim imgWebResponse As System.Net.WebResponse
imgWebRequest = System.Net.WebRequest.Create(sInputURL)
imgWebResponse = imgWebRequest.GetResponse()
imgFullSize = System.Drawing.Image.FromStream(imgWebResponse.GetResponseStream())
Else
'from file
imgFullSize = System.Drawing.Image.FromFile(Server.MapPath(sInputURL))
End If
' Dim props As PropertyItem() = imgFullSize.PropertyItems
' For Each prop As PropertyItem In props
' Response.Write(prop.Id.ToString() & "<br />")
' Next
'determine type
Dim sFileExtension As String = "png"
If Left(Right(sInputURL, 4), 1) = "." Then sFileExtension = Right(sInputURL, 3) 'for jpg, gif, etc
If Left(Right(sInputURL, 5), 1) = "." Then sFileExtension = Right(sInputURL, 4) 'for tiff, jpeg, etc
Dim jpgEncoder As ImageCodecInfo = GetEncoder(ImageFormat.Jpeg)
Dim gifEncoder As ImageCodecInfo = GetEncoder(ImageFormat.Gif)
Dim pngEncoder As ImageCodecInfo = GetEncoder(ImageFormat.Png)
'set the quality
Dim myEncoder As System.Drawing.Imaging.Encoder = System.Drawing.Imaging.Encoder.Quality
Dim myEncoderParams As New EncoderParameters(1)
Dim myEncoderQuality As New EncoderParameter(myEncoder, CType(100L, Int32))
myEncoderParams.Param(0) = myEncoderQuality
'save img to memory stream
Dim ms As New MemoryStream()
Select Case sFileExtension
Case "jpg" : imgFullSize.Save(ms, jpgEncoder, myEncoderParams)
Case "png", "gif" : imgFullSize.Save(ms, pngEncoder, myEncoderParams)
Case Else : imgFullSize.Save(ms, pngEncoder, myEncoderParams)
End Select
'output the memory stream
Response.ContentType = "image/" & sFileExtension
ms.WriteTo(Response.OutputStream)
'---> when I save the above image and look at the exif, it doesn't exist
End Sub
Private Function GetEncoder(ByVal format As ImageFormat) As ImageCodecInfo
Dim codecs As ImageCodecInfo() = ImageCodecInfo.GetImageDecoders()
Dim codec As ImageCodecInfo
For Each codec In codecs
If codec.FormatID = format.Guid Then Return codec
Next codec
Return Nothing
End Function
So this did the trick. Basically I had to loop through the source image properties, and for each, set the property in the new image.
'retrieve relative path to image
Dim sSrc As String = HttpUtility.UrlDecode(Request.QueryString("IptFl"))
'prepare image
Dim oImg As System.Drawing.Image
'attempt to get the image, either from web or local file
If InStr(sSrc, "http://") > 0 Or InStr(sSrc, "https://") Then
Dim oRequest As System.Net.WebRequest = System.Net.WebRequest.Create(sSrc)
Dim oResponse As System.Net.WebResponse = oRequest.GetResponse()
oImg = System.Drawing.Image.FromStream(oResponse.GetResponseStream())
oResponse.Close()
Else
oImg = System.Drawing.Image.FromFile(Server.MapPath(sSrc))
End If
'discard if image file not found
If oImg Is Nothing Then Response.End()
Dim sFileExt As String = Split(sSrc, ".")(UBound(Split(sSrc, ".")))
Dim oCanvas As System.Drawing.Bitmap = New System.Drawing.Bitmap(oImg.Width, oImg.Height, System.Drawing.Imaging.PixelFormat.Format16bppRgb555)
For Each pi As PropertyItem In oImg.PropertyItems
oCanvas.SetPropertyItem(pi)
Next
Dim oGraphic As System.Drawing.Graphics = System.Drawing.Graphics.FromImage(oCanvas)
oGraphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.Default
oGraphic.DrawImage(oImg, 0, 0, oImg.Width, oImg.Height)
Dim oStream As System.IO.MemoryStream = New System.IO.MemoryStream()
oCanvas.Save(oStream, System.Drawing.Imaging.ImageFormat.Jpeg)
Response.ContentType = "image/" & sFileExt
'output the memory stream
oStream.WriteTo(Response.OutputStream)
Response.End()

SQL Download Image into Picture Box 'Out of Memory' Error

*strong text*Okay, I've got a test application which is just to test the Uploading and Downloading of images to/from an SQL Server. The upload code works, but when I try to retrieve the image from the SQL Server I receive an 'Out of Memory' error. However, when I change the picturebox from .BackGroundImage to just .Image the code works flawlessly.
I require the image to be in the format of a BackGoundImage so that I can easily change the size of the image (center, stretch ect).
The error:
An unhandled exception of type 'System.OutOfMemoryException' occurred
in System.Drawing.dll
Additional information: Out of memory.
The code for retrieving the image from the SQL Server is:
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
'Retrieve Image
GroupBox2.BringToFront()
GroupBox2.Visible = True
Label1.Visible = False
TextBox1.Visible = False
con.Open()
Dim cmd As New SqlCommand("SELECT DP FROM PersonsA WHERE Members_ID = 1", con)
cmd.CommandType = CommandType.Text
Dim ImgStream As New IO.MemoryStream(CType(cmd.ExecuteScalar, Byte()))
PictureBox2.BackgroundImage = Image.FromStream(ImgStream, False, True)
ImgStream.Dispose()
con.Close()
End Sub
The error highlights the PictureBox2.BackgroundImage = Image.FromStream(ImgStream, False, True) line.
Additional information:
Only 1 row is expected as Members_ID is Primary Key.
SQL Server is MS SQL Server + Management Studio.
The DP Column is formatted as 'Image' and stores the picture like this:
0xFFD8FFE000104A46494600010201000000000000FF....
Here's the upload image code (WORKING)
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
'Upload Image
con.Open()
Dim cmd As New SqlCommand("UPDATE PersonsA SET DP=#DP WHERE Members_ID = 1", con)
Dim ms As New MemoryStream()
PictureBox1.BackgroundImage.Save(ms, PictureBox1.BackgroundImage.RawFormat)
Dim data As Byte() = ms.GetBuffer()
Dim p As New SqlParameter("#DP", SqlDbType.Image)
p.Value = data
cmd.Parameters.Add(p)
cmd.ExecuteNonQuery()
MessageBox.Show("Image has been saved", "Save", MessageBoxButtons.OK)
Label1.Visible = False
TextBox1.Visible = False
con.Close()
Imports and Dims
Imports System.Data.SqlClient
Imports System.IO
Public Class Form1
'path variable use for Get application running path
Dim path As String = (Microsoft.VisualBasic.Left(Application.StartupPath, Len(Application.StartupPath) - 9))
Dim con As New SqlConnection("CONNECTION_STRING;")
Dim cn As New SqlConnection("CONNECTION_STRING;")
Dim cmd As SqlCommand
Any ideas on why I'm receiving the 'Out of Memory Error'? The program is tiny and doesn't seam to be using excessive amounts of RAM so it has to be with my code...
[EDIT 1]
Following Jaques very helpful advice I've changed my code to the following - note there's two errors as read is not declared - what should that be declared as?
Dim cmd As New SqlCommand("SELECT DP FROM PersonsA WHERE Members_ID = 1", con)
cmd.CommandType = CommandType.Text
Dim Buffersize As Integer = 4096
Dim retval As Long = 0
Dim TempLen1 As Long = 0
Dim startindex As Long = 0
Dim reference_temp As [Byte]() = New [Byte](4095) {}
Dim RefTemp As New List(Of Byte)()
Dim Read As
retval = read.GetBytes(0, startindex, reference_temp, 0, buffersize)
'0 is the first Column
TempLen1 += retval
While retval = buffersize
RefTemp.AddRange(reference_temp)
startindex += buffersize
retval = read.GetBytes(0, startindex, reference_temp, 0, buffersize)
TempLen1 += retval
End While
RefTemp.AddRange(reference_temp)
Dim Reference_temp1 As Byte() = RefTemp.GetRange(0, CInt(TempLen1)).ToArray()
End Sub
[EDIT 2]
I'm now receiving an error on the retval - read.GetBytes(16, startindex.... line.
An unhandled exception of type 'System.InvalidOperationException'
occurred in Microsoft.VisualBasic.dll
Additional information: Invalid attempt to read when no data is
present.
My code so far:
'Retrieve Image
GroupBox2.BringToFront()
GroupBox2.Visible = True
Label1.Visible = False
TextBox1.Visible = False
con.Open()
Dim cmd As New SqlCommand("SELECT DP FROM PersonsA WHERE Members_ID = 1", con)
cmd.CommandType = CommandType.Text
Dim read = cmd.ExecuteReader
Dim Buffersize As Integer = 4096
Dim retval As Long = 0
Dim TempLen1 As Long = 0
Dim startindex As Long = 0
Dim reference_temp As [Byte]() = New [Byte](4095) {}
Dim RefTemp As New List(Of Byte)()
retval = read.GetBytes(16, startindex, reference_temp, 16, Buffersize)
'0 is the first Column
TempLen1 += retval
While retval = buffersize
RefTemp.AddRange(reference_temp)
startindex += buffersize
retval = read.GetBytes(16, startindex, reference_temp, 16, Buffersize)
TempLen1 += retval
End While
RefTemp.AddRange(reference_temp)
Dim Reference_temp1 As Byte() = RefTemp.GetRange(16, CInt(TempLen1)).ToArray()
Dim ImgStream As New IO.MemoryStream(Reference_temp1)
PictureBox2.BackgroundImage = Image.FromStream(ImgStream, False, True)
ImgStream.Dispose()
Why don't you use the GetBytes from a DataReader like (Its C#, but I'm sure you can convert it :))
'Retrieve Image
GroupBox2.BringToFront()
GroupBox2.Visible = True
Label1.Visible = False
TextBox1.Visible = False
con.Open()
Dim cmd As New SqlCommand("SELECT DP FROM PersonsA WHERE Members_ID = 1", con)
cmd.CommandType = CommandType.Text
Dim read = cmd.ExecuteReader();
if(read.HadRows) then
read.Read() 'Reads the first record from the DataReader
Convert this to VB:
int buffersize = 4096;
long retval = 0;
long TempLen1 = 0;
long startindex = 0;
Byte[] reference_temp = new Byte[4096];
List<byte> RefTemp = new List<byte>();
retval = read.GetBytes(0, startindex, reference_temp, 0, buffersize); //0 is the first Column
TempLen1 += retval;
while (retval == buffersize)
{
RefTemp.AddRange(reference_temp);
startindex += buffersize;
retval = read.GetBytes(0, startindex, reference_temp, 0, buffersize);
TempLen1 += retval;
}
RefTemp.AddRange(reference_temp);
byte[] Reference_temp1 = RefTemp.GetRange(0, (int)TempLen1).ToArray();
Then add your code
Dim ImgStream As New IO.MemoryStream(Reference_temp1)
PictureBox2.BackgroundImage = Image.FromStream(ImgStream, False, True)
ImgStream.Dispose()
EndIf
I'd like to thank Jaques for his/her efforts in helping me. The solution was a little simpler than that answer - which still resulted in a 'Out of Memory' Error. But the efforts made are extremely appreciated. In the end this code worked without any errors.
'Retrieve Image
GroupBox2.BringToFront()
GroupBox2.Visible = True
Label1.Visible = False
TextBox1.Visible = False
Dim stream As New MemoryStream()
con.Open()
Dim cmd As New SqlCommand("SELECT DP FROM PersonsA WHERE Members_ID = 1", con)
cmd.CommandType = CommandType.Text
Dim image As Byte() = DirectCast(cmd.ExecuteScalar(), Byte())
Stream.Write(image, 0, image.Length)
con.Close()
Dim bitmap As New Bitmap(stream)
PictureBox2.BackgroundImage = bitmap
PictureBox2.BackgroundImageLayout = ImageLayout.Stretch