Display Metadata-thumbnail of Jpeg in picturebox - vb.net

I need to display a Image's thumbnail, that is saved in its Metadata in a picturebox. I'm using VB.NET
http://msdn.microsoft.com/en-us/library/windows/desktop/ee719904%28v=vs.85%29.aspx#_jpeg_metadata
So far i came up with this. Adding a breakpoint displays that GETQUERY returns empty even if i know that the file does indeed have a thumbnail
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim imagepath = "C:\xampp\htdocs\Downloads\IMG_1322.JPG" ' path to file
Dim stream = New FileStream(imagepath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
Dim decoder = New JpegBitmapDecoder(stream, BitmapCreateOptions.None, BitmapCacheOption.None)
Dim metadata = TryCast(decoder.Frames(0).Metadata, BitmapMetadata)
Dim ms As New System.IO.MemoryStream
Dim bm As Bitmap
Dim arData() As Byte
arData = metadata.GetQuery("/app0/{ushort=6}") '<--- Breakpoint here: Query returns nothing!
ms.Write(arData, 78, arData.Length - 78)
bm = New Bitmap(ms)
PictureBox1.Image = bm
stream.Close()
End Sub

You can try something like this:
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim imagepath = "C:\xampp\htdocs\Downloads\IMG_1322.JPG" ' path to file
Dim stream = New FileStream(imagepath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
Dim decoder = New JpegBitmapDecoder(stream, BitmapCreateOptions.None, BitmapCacheOption.None)
Dim metadata = TryCast(decoder.Frames(0).Metadata, BitmapMetadata)
Dim thumb As BitmapMetadataBlob
thumb = metadata.GetQuery("/app1/thumb/")
If Not (thumb Is Nothing) Then
Dim src As New BitmapImage
Dim ms As MemoryStream = New MemoryStream(thumb.GetBlobValue())
src.BeginInit()
src.StreamSource = ms
src.EndInit()
PictureBox1.Source = src
End If
stream.Close()
End Sub

Related

How to Encrypt and Decrypt multiple text and image files within folders

Encryption and decryption for a single .txt file using the following code works:
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles SelectFile.Click
'Create a File Dialog Box to select the source file
Dim dlg As New OpenFileDialog
'If OK Button is Click then add file name with path to textBox1
If dlg.ShowDialog() = DialogResult.OK Then
TextBox1.Text = dlg.FileName
End If
End Sub
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Encrypt.Click
Dim outputFile As String
outputFile = "M:\Encryptions\Encrypted.txt"
Dim fsInput As New FileStream(TextBox1.Text, FileMode.Open, FileAccess.Read)
Dim fsEncrypted As New FileStream(outputFile, FileMode.Create, FileAccess.Write)
Dim sKey As String
sKey = "Helloabc"
Dim DES As New DESCryptoServiceProvider
DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey)
DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey)
Dim desencrypt As ICryptoTransform
desencrypt = DES.CreateEncryptor()
Dim cryptostream As New CryptoStream(fsEncrypted, desencrypt, CryptoStreamMode.Write)
Dim bytearrayinput(fsInput.Length) As Byte
fsInput.Read(bytearrayinput, 0, bytearrayinput.Length)
cryptostream.Write(bytearrayinput, 0, bytearrayinput.Length)
cryptostream.Close()
fsInput.Close()
fsEncrypted.Close()
TextBox2.Text = "M:\Encryptions\Encrypted.txt"
End Sub
Private Sub Button3_Click(sender As System.Object, e As System.EventArgs) Handles Decrypt.Click
Dim DES As New DESCryptoServiceProvider
Dim sKey As String
sKey = "Helloabc"
DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey)
DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey)
Dim fsread As New FileStream(TextBox2.Text, FileMode.Open, FileAccess.Read)
Dim desdecrypt As ICryptoTransform
desdecrypt = DES.CreateDecryptor()
Dim cryptostreamDecr As New CryptoStream(fsread, desdecrypt, CryptoStreamMode.Read)
Dim fsDecrypted As New StreamWriter("M:\Decryptions\Decrypted.txt")
fsDecrypted.Write(New StreamReader(cryptostreamDecr).ReadToEnd())
fsDecrypted.Flush()
fsDecrypted.Close()
TextBox3.Text = "M:\Decryptions\Decrypted.txt"
End Sub
However when attempting to encrypt/decrypt multiple files, the original output encryption/decryption file ("Encrypted.txt") will be replaced by the new output.
How do you create a loop in order to create multiple encrypted files with different file names?
Use a counter: 0, 1, 2, 3, 4 ... Append the counter to the filename and step the counter after each file is written:
Encrypted00.dat
Encrypted01.dat
Encrypted02.dat
Encrypted03.dat
...
It is probably a mistake to call the encrypted files .txt since they will not be text. They are binary data. If you want them as text then you will need to convert to Base64 format, and convert back to binary data before decrypting.
Alternatively, zip all the files in the directory into a single file and encrypt that single file.

Converting file to byte, sending it and converting it from byte array back to file

I am trying to send a file through tcp connection in vb.net via byte array.
How do I convert the byte array back to the file and save it using savefiledialog?
The code I use to convert the file to byte array and send it is:
Private Sub btnfSend_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnfSend.Click
browseFile.Title = "Browse Files"
browseFile.InitialDirectory = "C:\Users\LF\Desktop"
browseFile.ShowDialog()
End Sub
Private Sub browseFile_FileOk(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles browseFile.FileOk
If ((lblStatus.Text = "Status: Receiving") Or (lblStatus.Text = "Status: Connected")) Then
Dim strm As System.IO.Stream
strm = browseFile.OpenFile()
Dim fileDir As String
fileDir = browseFile.FileName.ToString()
Dim fInfo As New FileInfo(fileDir)
Dim numBytes As Long = fInfo.Length
Dim fStream As New FileStream(fileDir, FileMode.Open, FileAccess.Read)
Dim br As New BinaryReader(fStream)
Dim data As Byte() = br.ReadBytes(CInt(numBytes))
ChatSocket.SendTo(data, SocketFlags.None, New IPEndPoint(IPAddress.Parse(txtRemoteIP.Text), CInt(Val(txtRemotePort.Text))))
br.Close()
fStream.Close()
End If
End Sub

Im cant get a doc from my documents to display

Imports System.IO
Public Class Form1
Private Sub MenuItem1_Click(sender As Object, e As EventArgs) Handles MenuItem1.Click
Me.txtFileContent.Text = Nothing
End Sub
Private Sub MenuItem2_Click(sender As Object, e As EventArgs) Handles MenuItem2.Click
Me.txtFileContent.Text = Nothing
End Sub
Private Sub MenuItem3_Click(sender As Object, e As EventArgs) Handles MenuItem3.Click
Me.savSaveFile.ShowDialog()
Dim strFileName As String = Me.savSaveFile.FileName
Dim fs As New FileStream(strFileName, FileMode.Create, FileAccess.Write)
Dim TextFile As New StreamWriter(fs)
TextFile.Write(Me.txtFileContent.Text)
TextFile.Close()
fs.Close()
End Sub
Private Sub OpenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles MenuItem5.Click
Me.savSaveFile.ShowDialog()
Dim strFileName As String = Me.savSaveFile.FileName
Dim fs As New FileStream(strFileName, FileMode.Open, FileAccess.Read)
Dim TextFile As New StreamWriter(fs)
TextFile.Close()
fs.Close()
End Sub
End Class
What im trying to do is display a "open" document dialog box so the text inside the box can be displayed into the text box. I did the same with the "save" document dialog box and it worked fine just confused on the Open part. Thanks a million everyone.
There are two different kind of dialog box for selecting files.
One for save operations and one for opening files.
Your code seems to use the same one and from the name I think it is a SaveFileDialog.
To open a file you need a OpenFileDialog and use a StreamReader not a StreamWriter
Private Sub OpenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles MenuItem5.Click
' Create an OpenFileDialog here, for more precise property settings see the link above'
Dim openDlg = New OpenFileDialog()
' If user presses OK'
if openDlg.ShowDialog() = DialogResult.OK Then
' Still the filename selected could be empty, need to check'
Dim strFileName As String = openDlg.FileName
if strFileName.Trim().Length > 0 then
' Open the file using a reader, not a writer'
Using fs = New FileStream(strFileName, FileMode.Open, FileAccess.Read)
Using TextFile = New StreamReader(fs)
' Read everything (caution this should be used only for small files)'
Dim fileContent = TextFile.ReadToEnd
' Pass everything into a TextBox control for display'
Me.txtFileContent.Text = fileContent
End Using
End Using
End If
End If
End Sub

Bind a PictureBox to DataColum in VB.NET

I have a data repeater that contains a PictureBox and the picture needs to be fetched from a webserver. I already have a function that downloads the image, but the binding does not seem to be working. I am quite new to using windows forms and I am not too sure what I am doing wrong.
I have tried using a gridview, and I can confirm that that does show the images.
Public Function DlImg(ByVal _URL As String) As Byte()
Dim _tmpImage As Image = Nothing
Dim BytesOut As Byte()
Try
Dim _HttpWebRequest As System.Net.HttpWebRequest = DirectCast(System.Net.HttpWebRequest.Create(_URL), System.Net.HttpWebRequest)
_HttpWebRequest.AllowWriteStreamBuffering = True
Dim _WebResponse As System.Net.WebResponse = _HttpWebRequest.GetResponse():
Dim _WebStream As System.IO.Stream = _WebResponse.GetResponseStream()
_tmpImage = Image.FromStream(_WebStream)
_WebResponse.Close()
Using picture As Image = _tmpImage
Using stream As New IO.MemoryStream
picture.Save(stream, Imaging.ImageFormat.Jpeg)
BytesOut = stream.GetBuffer()
End Using
End Using
Catch _Exception As Exception
Return Nothing
End Try
Return BytesOut
End Function
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
ListData.Columns.Add("Image", Type.GetType("System.Byte[]"))
For Each row As DataRow In ListData.Rows
row("Image") = DlImg("http://rental.joshblease.co.uk/propertyimages/p184js94kv1qco1e1e1jt71ouv11lm6.jpg")
Next row
ImgListItem.DataBindings.Add("Image", ListData, "Image", True)
DataGridView1.DataSource = ListData
DataRepeater1.DataSource = ListData
End Sub

Save binary file from SQL Server

I'm trying to save a binary file stored in a SQL database with a SaveDialog, the function RetrieveFile retrieves the specified file from the database as a Byte array, here's what I have so far:
Private Shared Function RetrieveFile(ByVal filename As String) As Byte()
Dim connection As New SqlConnection("Data Source=SERVER\SQL2008;Initial Catalog=NorthPole;Integrated Security=True")
Dim command As New SqlCommand("SELECT pcfFile FROM Items WHERE pcfFileName=#Filename", connection)
command.Parameters.AddWithValue("#Filename", filename)
connection.Open()
Dim reader As SqlDataReader = command.ExecuteReader(System.Data.CommandBehavior.SequentialAccess)
reader.Read()
Dim memory As New MemoryStream()
Dim startIndex As Long = 0
Const ChunkSize As Integer = 256
While True
Dim buffer As Byte() = New Byte(ChunkSize - 1) {}
Dim retrievedBytes As Long = reader.GetBytes(1, startIndex, buffer, 0, ChunkSize)
memory.Write(buffer, 0, CInt(retrievedBytes))
startIndex += retrievedBytes
If retrievedBytes <> ChunkSize Then
Exit While
End If
End While
connection.Close()
Dim data As Byte() = memory.ToArray()
memory.Dispose()
Return data
End Function
Private Sub SaveAsToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveAsToolStripMenuItem.Click
Dim saveFileDialog1 As New SaveFileDialog()
saveFileDialog1.Filter = "PCF File|*.pcf|"
saveFileDialog1.Title = "Save an pcf File"
saveFileDialog1.ShowDialog()
If saveFileDialog1.FileName <> "" Then
Dim fs As System.IO.FileStream = CType(RetrieveFile("FakePCF.pcf"), System.IO.FileStream)
fs.Close()
End If
End Sub
Files are saved as "SqlDbType.VarBinary" within the database.
I get: "Index was outside the bounds of the array." on:
Dim retrievedBytes As Long = reader.GetBytes(1, startIndex, buffer, 0, ChunkSize)
The MemoryStream appears to not be retrieving the data yet the SQL sytax is correct.
What am I doing wrong?
Well, first of all, your method returns byte[] and you're trying to cast it to FileStream. You should change your handler to following:
Private Sub SaveAsToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveAsToolStripMenuItem.Click
Dim saveFileDialog1 As New SaveFileDialog()
saveFileDialog1.Filter = "PCF File|*.pcf|"
saveFileDialog1.Title = "Save an pcf File"
saveFileDialog1.ShowDialog()
If saveFileDialog1.FileName <> "" Then
Dim fs As New System.IO.FileStream (saveFileDialog1.FileName, System.IO.FileMode.Create, System.IO.FileAccess.Write)
Dim data As Byte() = RetrieveFile("FakePCF.pcf")
fs.Write(data, 0, data.Length)
fs.Flush()
fs.Close()
End If
End Sub