I have a number of images in the resources directory and access them like this...
Public Function ReturnToolBarImage(ByVal ImageName As String) As Image
Dim UpdateImage As New Image
With UpdateImage
End With
Dim UpdateBitmap As New BitmapImage
With UpdateBitmap
.BeginInit()
.UriSource = New Uri("pack://application:,,,/HOA_Manager_Client_04;component/Resources/" & ImageName, UriKind.Absolute)
.EndInit()
.DecodePixelHeight = 32
End With
UpdateImage.Source = UpdateBitmap
Return UpdateImage
End Function
I have control that insists upon using an Image Path not an Image - I can access it like this
.ImageSource = "//application:,,,/HOA_Manager_Client_04;component/Resources/Customers.png"
But the image is, or course, far too large.. Soooooo I added a function to save the resized image to a Temp folder (that is working) and send the path back - but for some reason that just doesn't work (no errors, just no image). Any ideas?
Public Function ReturnToolBarImageAsString(ByVal ImageName As String) As String
Dim UpdateImage As New Image
With UpdateImage
End With
Dim UpdateBitmap As New BitmapImage
With UpdateBitmap
.BeginInit()
.UriSource = New Uri("pack://application:,,,/HOA_Manager_Client_04;component/Resources/" & ImageName, UriKind.Absolute)
.EndInit()
.DecodePixelHeight = 32
End With
Using FS As New IO.FileStream("../../Pages/Temp/" & ImageName, IO.FileMode.Create)
Dim vEncoder As New PngBitmapEncoder
vEncoder.Frames.Add(BitmapFrame.Create(UpdateBitmap))
vEncoder.Save(FS)
End Using
'Return "../Temp/" & ImageName
Return "//application:,,,/HOA_Manager_Client_04;component/Pages/Temp/" & ImageName
End Function
By creating a directory at run time in the Bin directory seems to have cured the issue
Public Function ReturnToolBarImageAsString(ByVal ImageName As String) As String
Dim UpdateImage As New Image
With UpdateImage
End With
Dim UpdateBitmap As New BitmapImage
With UpdateBitmap
.BeginInit()
.DecodePixelHeight = 32
.UriSource = New Uri("pack://application:,,,/HOA_Manager_Client_04;component/Resources/" & ImageName, UriKind.Absolute)
.EndInit()
End With
Dim vPath As String = My.Application.Info.DirectoryPath
If Not IO.Directory.Exists(vPath & "\Temp_Images") Then
IO.Directory.CreateDirectory(vPath & "\Temp_Images")
End If
Using FS As New IO.FileStream(vPath & "\Temp_Images\" & ImageName, IO.FileMode.Create)
Dim vEncoder As New PngBitmapEncoder
vEncoder.Frames.Add(BitmapFrame.Create(UpdateBitmap))
vEncoder.Save(FS)
End Using
Return vPath & "\Temp_Images\" & ImageName
End Function
Related
I inserted an image into a .mdb database with this code from my WPF app :
Dim con As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & GetCurrentDirectory() & "\Data\rctts.mdb;Jet OLEDB:Database Password=arn33423342;")
con.Open()
Dim cmd As New OleDbCommand("Insert into recents(Uname,Pic,Email)values(#uname,#pic,#email)", con)
image1.Source = New BitmapImage(New Uri("D:\logo.png"))
Dim buffer As Byte()
Dim bitmap = TryCast(image1.Source, BitmapSource)
Dim encoder = New PngBitmapEncoder()
encoder.Frames.Add(BitmapFrame.Create(bitmap))
Using stream = New MemoryStream()
encoder.Save(stream)
buffer = stream.ToArray()
End Using
cmd.Parameters.AddWithValue("#pic", buffer)
The Pic column or cell's data type is OLE Object...Anyway,after inserting the data,i opened my database,i saw that a new record was added but the value of the Pic column was Long binary data.Anyway,then i went on retrieving the image in my wpf app.I used this code ?
Dim cmd As New OleDbCommand("Select * from recents", con)
Dim table As New DataTable
Dim adap As New OleDbDataAdapter(cmd)
adap.Fill(table)
If table.Rows.Count <= 0 Then
Else
For Each row In table.Rows
recentbtn.Image.ImageSource = BytesToImage(CType(row(1), Byte()))
recentbtn.Names.Text = table.Rows(0)(0).ToString
AddHandler recentbtn.MouseDown, AddressOf recentbtn_mousedow
RecentsList.stp.Children.Add(recentbtn)
Next
End If
loadingrecents.Visibility = Visibility.Hidden
End Sub
Private Shared Function BytesToImage(ByVal bytes As Byte()) As BitmapImage
Dim bm = New BitmapImage()
Using stream As MemoryStream = New MemoryStream(bytes)
stream.Position = 0
stream.Seek(0, SeekOrigin.Begin)
bm.BeginInit()
bm.StreamSource = stream
bm.CreateOptions = BitmapCreateOptions.PreservePixelFormat
bm.CacheOption = BitmapCacheOption.OnLoad
bm.EndInit()
End Using
Return bm
End Function
But it's returning an error : No imaging component suitable to complete the operation was found
Fixed it...For anyone who faces this error in future :
Make sure you're inserting the data in the proper way(sometimes corrupted data in the db causes such errors)
2 . You don't need to do some heavy coding to convert the image to byte!
Finally,let's code :
Public Sub read()
con.Open()
Dim cmd As New OleDbCommand("Select * from recents", con)
Dim _dr As OleDbDataReader
_dr = cmd.ExecuteReader
Dim _photo As Byte()
While _dr.Read()
Try
_photo = CType(_dr(1), Byte())
Dim strm As MemoryStream = New MemoryStream(_photo)
Dim img As System.Drawing.Image = System.Drawing.Image.FromStream(strm)
Dim bi As BitmapImage = New BitmapImage()
bi.BeginInit()
Dim ms As MemoryStream = New MemoryStream()
img.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp)
ms.Seek(0, SeekOrigin.Begin)
bi.StreamSource = ms
bi.EndInit()
image1.Source = bi
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End While
In a table image column is storing as 0xFF...how to display this format file in picture box in vb.net winforms? I tried below code but not working and showing readtimeout/writetimeout error ..help me..advanced thanks..
Private Sub DisplayNameAttribute_UserImage()
Try
strimage = "SELECT userimage from MKBLOGIN where empcode='" & str_empcode & "'"
imagedatabytes = objcommonvalidation.func_loadUserImage(strimage)
mem = New MemoryStream(imagedatabytes)
PictureBox1.Image = ToImage(imagedatabytes)
Catch ex As Exception
End Try
End Sub
Public Function func_loadEmpImage(ByVal str_query As String) As Byte()
Try
Dim ds As New DataSet
da = New SqlDataAdapter(str_query, con)
da.Fill(ds)
If ds.Tables(0).Rows.Count > 0 Then
data = New Byte(0) {}
data = ds.Tables(0).Rows(0)("userimage")
End If
Return data.ToArray()
Catch ex As Exception
Return data.ToArray()
End Try
End Function
Public Shared Function ToImage(Data As Byte()) As Image
If Data Is Nothing Then
Return Nothing
End If
Dim img As Image
Using stream As New MemoryStream(Data)
Using temp As Image = Image.FromStream(stream)
img = New Bitmap(temp)
End Using
End Using
Return img
End Function
cmd = New SqlCommand("Select userimage from table", con)
dr = cmd.ExecuteReader
dr.read
Dim ImgStream As New IO.MemoryStream(CType(sqldr("userimage"), Byte()))
PictureBox1.Image = Image.FromStream(ImgStream)
ImgStream.Dispose()
Dim stream As New IO.MemoryStream
Dim img() As Byte
img = table.Rows(0)(1)
Dim ms As New MemoryStream(img)
pddraw.Image = Image.FromStream(ms)
conn.Open()
command.ExecuteNonQuery()
conn.Close()
this is only for display not for editing
When inside the tool I want to text included in the image between the place where I want to speak, as the following picture:
enter image description here
I tried the following code but the photo does not show the speech, but end of the sentence appears:
Dim para As New Paragraph()
Dim bitmap As New BitmapImage(New Uri("D:\Happy.png"))
Dim image As New Image()
image.Source = bitmap
image.Width = 20
para.Inlines.Add(image)
RTB.Document.Blocks.Add(para)
See this link for examples Inline Images or Other Elements.
'A RichTextBox with an image.
Private Sub ImageRTB()
'Create a new RichTextBox.
Dim MyRTB As New RichTextBox()
' Create a Run of plain text and image.
Dim myRun As New Run()
myRun.Text = "Displaying text with inline image"
Dim MyImage As New Image()
MyImage.Source = New BitmapImage(New Uri("flower.jpg", UriKind.RelativeOrAbsolute))
MyImage.Height = 50
MyImage.Width = 50
Dim MyUI As New InlineUIContainer()
MyUI.Child = MyImage
' Create a paragraph and add the paragraph to the RichTextBox.
Dim myParagraph As New Paragraph()
MyRTB.Blocks.Add(myParagraph)
' Add the Run and image to it.
myParagraph.Inlines.Add(myRun)
myParagraph.Inlines.Add(MyUI)
'Add the RichTextBox to the StackPanel.
MySP.Children.Add(MyRTB)
End Sub
The solution found and this is the code:
Dim tp As TextPointer = rtb.CaretPosition.GetInsertionPosition(LogicalDirection.Forward)
Dim bm As New BitmapImage()
bm.BeginInit()
bm.UriSource = New Uri("Happy.png", UriKind.Relative)
bm.CacheOption = BitmapCacheOption.OnLoad
bm.EndInit()
Dim img As New Image()
img.Source = bm
img.Width = 20
img.Height = 20
img.Stretch = Stretch.Fill
Dim container As New InlineUIContainer(img, tp)
thank you :)
From the Page_load event of Window1 I'm calling a function of a public class and passing parameter as the same Window1. After the function is called, a thread is started. The thread is called on Page_Loaded event of Window1. The code is like this:
Private Sub StartScreen_Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Me.Loaded
Try
TmHeartbeat.Stop()
TmHeartbeat.Interval = 600000
TmHeartbeat.Start()
ResetVariables()
FormLoadSetting(Me)
SetButtonProperty(btnEnglish, "\Images\ButtonBgBig.png", GetFormLabel("Start Screen", "Common", "Button English"))
SetButtonProperty(btnSpanish, "\Images\ButtonBgBig.png", GetFormLabel("Start Screen", "Common", "Button Spanish"))
SetDisplayTimer(DGT, False, Me, 1800000)
MediaElement1.Source = New Uri(GetPath("Images\EnglishVideo\" & GetFormLabel("Start Screen", "Common", "Video")))
If GetFormLabel("Start Screen", "Common", "Audio") <> "" Then
PlayAudio(APlay, GetFormLabel("Start Screen", "Common", "Audio"))
End If
Dim AudioPlay As New System.Media.SoundPlayer
Dim sc As New Screenshot
sc.TakeScreenshot(Me)
Catch ex As Exception
AliLogFileEntry(TransactionType.ErrorOnForm, "Error In Function: StartScreen_Loaded: " & Me.Title & ", ErrorMessage: " & ex.Message)
End Try
End Sub
The function TakeScreenshot(Me) which is in class Screenshot is called. Along with the Screenshot class, I also have another class named GetScreenshot and a function TakeScreenshot1. The code for the class file is like this:
Imports System.IO
Imports System.Threading
Public Class Screenshot
Public Sub TakeScreenshot(ByVal formname As Window)
Dim GT As New GetScreenshot
GT.source = formname
Dim newThread As New Thread(AddressOf GT.TakeScreenshot1)
newThread.Start()
End Sub
End Class
Public Class GetScreenshot
Public source As Window
Public Function TakeScreenshot1()
Thread.Sleep(2000)
If OG.GetValue("TakeScreenshot") <> "0" Then
Try
AliLogFileEntry(TransactionType.System, "In Function: TakeScreenshot")
Dim scale As Double = OG.GetValue("Screenshot_Scale") / 100
AliLogFileEntry(TransactionType.System, "In Function: GetJpgImage")
Dim renderHeight As Double = source.RenderSize.Height * scale
Dim renderWidth As Double = source.RenderSize.Width * scale
Dim renderTarget As New RenderTargetBitmap(CInt(Math.Truncate(renderWidth)), CInt(Math.Truncate(renderHeight)), 96, 96, PixelFormats.Pbgra32)
Dim sourceBrush As New VisualBrush(source)
Dim drawingVisual As New DrawingVisual()
Dim drawingContext As DrawingContext = drawingVisual.RenderOpen()
Using drawingContext
drawingContext.PushTransform(New ScaleTransform(scale, scale))
drawingContext.DrawRectangle(sourceBrush, Nothing, New Rect(New Point(0, 0), New Point(source.RenderSize.Width, source.RenderSize.Height)))
End Using
renderTarget.Render(drawingVisual)
Dim jpgEncoder As New JpegBitmapEncoder()
jpgEncoder.QualityLevel = 100
jpgEncoder.Frames.Add(BitmapFrame.Create(renderTarget))
Dim _imageArray As [Byte]()
Using outputStream As New MemoryStream()
jpgEncoder.Save(outputStream)
_imageArray = outputStream.ToArray()
End Using
Dim screenshot As Byte() = _imageArray
Dim dir As DirectoryInfo = New DirectoryInfo("Screenshots")
If Not dir.Exists Then dir = Directory.CreateDirectory(dir.FullName)
Dim path As String = AppDomain.CurrentDomain.BaseDirectory
Dim fileStream As New IO.FileStream("Screenshots\" & source.Title & ".jpg", FileMode.Create, FileAccess.ReadWrite)
Dim binaryWriter As New IO.BinaryWriter(fileStream)
binaryWriter.Write(screenshot)
binaryWriter.Close()
Catch ex As Exception
AliLogFileEntry(TransactionType.ErrorOnForm, "Error In Function: TakeScreenshot , ErrorMessage: " & ex.Message)
End Try
End If
End Function
End Class
When I debug this file, I get this error:
And the error is generated on line
Dim sourceBrush As New VisualBrush(source)
Pleas help
You are using source from a different thread than it was created on. In order to use a windows control on a different thread you need to call back to the original thread.
See How to: Make Thread-Safe Calls to Windows Forms Controls for more.
I am trying to develop code to unzip file from the zip file in Silverlight 5. The files are in a directory within the zip file.
I translated this code I found elsewhere from c# to VB since we are a VB shop. It is failing on the fourth line "Object reference not set to an instance of an object.".
I realize now that the problem is that the third line is expecting a relative uri and I am passing it a file, but I don't know how to fix this.
Can you tell me what is wrong with this code. I will also welcome other ideas.
Thanks.
Public Shared Function GetZipContents(ByVal filename As String) As String()
Try
Dim zipStream As System.IO.Stream = New System.IO.MemoryStream()
Dim zipInfo As New StreamResourceInfo(zipStream, Nothing)
Dim streamInfo As StreamResourceInfo = Application.GetResourceStream(zipInfo, New Uri(filename, UriKind.Relative))
Dim fileStream As Stream = streamInfo.Stream
Dim names As New List(Of String)()
Dim reader As New BinaryReader(fileStream)
Do While reader.ReadUInt32() = &H4034B50
' Skip the portions of the header we don't care about
reader.BaseStream.Seek(14, SeekOrigin.Current)
Dim compressedSize As UInteger = reader.ReadUInt32()
Dim uncompressedSize As UInteger = reader.ReadUInt32()
Dim nameLength As Integer = reader.ReadUInt16()
Dim extraLength As Integer = reader.ReadUInt16()
Dim nameBytes() As Byte = reader.ReadBytes(nameLength)
names.Add(Encoding.UTF8.GetString(nameBytes, 0, nameLength))
reader.BaseStream.Seek(extraLength + compressedSize, SeekOrigin.Current)
Loop
' Move the stream back to the begining
fileStream.Seek(0, SeekOrigin.Begin)
Return names.ToArray()
Catch ex As Exception
MessageBox.Show(ex.Message)
Return Nothing
End Try
End Function
There is quick and dirty way to unzip in Silverlight.
Use Application.GetResourceStream Method.
http://msdn.microsoft.com/en-us/library/cc190632(v=vs.95).aspx
Check out my blogpost on this: http://www.sharpgis.net/post/2010/08/25/REALLY-small-unzip-utility-for-Silverlight-e28093-Part-2.aspx
Sorry I would have time to explore the suggestions. I did find a way to accomplish my goal on my own. See the code below. I would be using this code either because the Technical Leader here prefers I do it a different way using a WCF service. Warning I was not able to test this code 100% since I am not planning to use it, but it is close to being right.
Imports ICSharpCode.SharpZipLib.Zip
Public Shared Sub UnZip(ByVal SrcFile As String, ByVal DstFile As String, ByVal BufferSize As Integer)
Try
Dim _FileName As String
Dim _ZipEntry As ZipEntry
Dim _FileStreamOut As FileStream = Nothing
Dim _Done As Boolean = False
Dim _FileStreamIn As New FileStream(SrcFile, FileMode.Open, FileAccess.Read)
Dim _ZipInStream As New ZipInputStream(_FileStreamIn)
Do Until _Done = True
_ZipEntry = _ZipInStream.GetNextEntry()
If IsNothing(_ZipEntry) Then
_Done = True
Exit Do
End If
_FileName = DstFile & "\" & _ZipEntry.Name
_FileName = _FileName.Replace("/", "\")
If Right(_FileName, 1) = "\" Then
If Directory.Exists(_FileName) = False Then
Directory.CreateDirectory(_FileName)
End If
Else
_FileStreamOut = New FileStream(_FileName, FileMode.Create, FileAccess.Write)
Dim size As Integer
Dim buffer(BufferSize - 1) As Byte
Do
size = _ZipInStream.Read(buffer, 0, buffer.Length)
_FileStreamOut.Write(buffer, 0, size)
Loop While size > 0
End If
Loop
_ZipInStream.Close()
_FileStreamOut.Close()
_FileStreamIn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub