How to extract an Image from HTML file using VB.net - html

I have few HTML files which has images stored in binary format like below
<img src="data:image/png;base64,iVBORw0KGgoAAAANS............>
Only one image per HTML file
I need to extract image from each file and save them to png or jpg using a .net application
Any help is appreciated
Thanks
Jiju

Try this:
Imports System.Drawing
Module Module1
Sub Main()
Dim ImageText = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIAAAAyCAMAAAAp4XiDAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAFEUExURf////+Kh/+Gg//j4//BwP97eP9jX/+Bfv+5uP/29v+HhP+Mif+mpP/b2/8tJ/8IAP+/vv9ybv8cFv9zb/+1tP9xbf/7+/8uKP/q6v/6+v9KRf9aVv/h4f/9/f/Q0P9AO/9nY/9wbP/09P/Av/85NP+Niv/w8P+tq/9fW//5+f8pI//W1v/OzP82Mf8xK/82MP+Jhv99ev8aFP8SC/8zLf8TDP83Mv81MP/s7P81L/96d/84M/9CPf/19f86Nf8sJv9va/9BPP87Nv8yLP9XU/8RCv8kHv89OP9dWf+cmv8+Of8bFf8hG/+urP90cf94df9TTv+opv9STf+2tf+Aff9EP//Cwf/Y2P9MR/9GQf9taf8gGv+Tkf+Vk/9UUP8WD//FxP9JRP+kov8mIP8XEf9hXf/V1f+0s//39//e3v/S0v/i4pkRhsgAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAE5SURBVEhL7ZJXU8JAFIWvqKgoHlE0RBGwoChWVKyI2Hvvvdf//+7evcmMZCIzvjr5HrL3nN1vNpkJeXh4ePyFMp9NuUoVlX5/VbXeqAkEArV1QT0XUw+bBqIQ0KimJt4IS9usTxXRojAQMU2TqBVtUWqPxZFQG2F0mJ1d3UjKOQcGenjpRUrHvn6kWQmpeQCDunMyJMowvxszglFbocyYrpyMizKR0YkoxteJEkVWOgeTWpnCtESKIG4rM3yhC7NaSWNOIuUwz0p+IZVFweocLGolhyWJFMQyKyura+sbVuVkU75la1snoh3ssrJnRTcKouzjQEc6xBErx5JcORHlFMYZr0mcq2cYPg6/cCEKXeIqcX1zi7t7FUorD5ZCj0/qr3p+eeX5raRC79ZK9PH5ZU0/Sg+PfwXRN1h4IRCn6GVqAAAAAElFTkSuQmCC"
'We don't need 'data:image/png;base64,'
ImageText = ImageText.Split(",")(1)
Dim bitmapData As Byte() = Convert.FromBase64String(FixBase64ForImage(ImageText))
Dim streamBitmap As System.IO.MemoryStream = New System.IO.MemoryStream(bitmapData)
Dim bitImage As Bitmap = New Bitmap(CType(Image.FromStream(streamBitmap), Bitmap))
bitImage.Save("c:\temp\test1.png", Imaging.ImageFormat.Png)
End Sub
Public Function FixBase64ForImage(ByVal Image As String) As String
Dim sbText As System.Text.StringBuilder = New System.Text.StringBuilder(Image, Image.Length)
sbText.Replace(vbCrLf, String.Empty)
sbText.Replace(" ", String.Empty)
Return sbText.ToString()
End Function
End Module

Related

How do I put a serialized object into a json file with visual basic?

I currently have data being pulled from textboxes and comboboxes that are converted into properties of an object, and then that object is seralized into json. I then use the streamwriter function to put that into a json file that has already been created but I just end up with a bunch of weird formatting and things not updating and being added.
Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
Dim monsterName As String
monsterName = TextBox2.Text
TextBox2.Text = ""
Dim monsterCB As Integer
monsterCB = TextBox3.Text
TextBox3.Text = ""
Dim monsterType As String
monsterType = ComboBox3.SelectedItem
ComboBox3.Text = ""
Dim Monster As New Monster
Monster.MonsterName = monsterName
Monster.MonsterCombatRating = monsterCB
Monster.MonsterType = monsterType
Dim output As String
output = JsonConvert.SerializeObject(Monster)
Dim file As System.IO.StreamWriter
file = My.Computer.FileSystem.OpenTextFileWriter("C:\Program Files (x86)\D&DLoot\data.json", True)
file.WriteLine(Monster)
file.Close()
End Sub
This is within my form code and is the snippet of when my button is clicked for the current form.
Then, in my json file it just writes a new line of
WinFormsApp1.Monster
So I'm not entirely sure whats going on and what I have missed. I can't see whats wrong with the code above.
Should be using output in the code below instead of monster. Since the serialized object is in the output, not the monster.
file.WriteLine(Monster)
output = JsonConvert.SerializeObject(Monster)

Convert image stored on remote folder to base64 in web app

In my web app i need to convert images on catalog to string
Catalogue are created in a listview with .NET Framework 4 using webform
Protected Sub ProductsLv_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ListViewItemEventArgs) Handles ProductsLv.ItemDataBound
If e.Item.ItemType = ListViewItemType.DataItem Then
Dim dataRow = DirectCast(e.Item.DataItem, DataRowView)
Dim path = Replace("~/Products/Immagine.ashx?FileName=" & dataRow("ImageName"), "\\machine\Foto\", "")
path = "http://" & Me.Request.Url.Host & ResolveUrl(path)
Dim sBase64 As String = "data:image/jpeg;base64,"
Using w As New System.Net.WebClient()
Dim buffer As Byte() = w.DownloadData(path)
sBase64 &= Convert.ToBase64String(buffer)
End Using
DirectCast(e.Item.FindControl("myIMG"), System.Web.UI.WebControls.Image).ImageUrl = sBase64
End If
End Sub
Code above seems works well because i found string on image source of html produced by server response
but images are not visible
What mistake i making?
The value of sBase64 is
data:image/jpeg;base64,DQo8IURPQ1RZUEUgaHRtbCBQVUJMSUMgIi0vL1czQy8vRFREIFhIVE1MIDEuMCBUcmFuc2l0aW9uYWwvL0VOIiAiaHR0cDovL3d3dy53My5vcmcvVFIveGh0bWwxL0RURC94aHRtbDEtdHJhbnNpdGlvbmFsLmR0ZCI+DQoNCjxodG1sIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hodG1sIj4NCjxoZWFkPjx0aXRsZT4NCglMb2dpbg0KPC90aXRsZT4NCiAgICA8c3R5bGUgdHlwZT0idGV4dC9jc3MiPg0KICAgICAgIC5mYWlsdXJlTm90aWZpY2F0aW9uDQp7DQogICAgZm9udC1zaXplOiAxLjJlbTsNCiAgICBjb2xvcjogI0ZGMDA2NjsNCiAgICBmb250LXdlaWdodDpib2xkOw0KfQ0KICAgIDwvc3R5bGU+DQoNCiAgICA8bGluayBocmVmPSIuLi9Db250ZW50L2Jvb3RzdHJhcC5jc3MiIHJlbD0ic3R5bGVzaGVldCIgLz48b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ICAgICANCiAgICAgICAgICAgICAgICAgICAgICAgIDxpbnB1dCBuYW1lPSJMb2dpblVzZXIkVXNlck5hbWUiIHR5cGU9InRleHQiIGlkPSJMb2dpblVzZXJfVXNlck5hbWUiIGNsYXNzPSJmb3JtLWNvbnRyb2wiIHBsYWNlaG9sZGVyPSJ1dGVudGUiIC8+DQogICAgICAgICAgICAgICAgICAgICAgICAmbmJzcDsNCiAgICAgICAgICAgICAgICAgICAgPC9wPg0KICAgICAgICAgICAgICAgICAgICA8cD4NCiAgICAgICAgICAgICAgICAgICAgICAgIA0KICAgICAgICAgICAgICAgICAgICAgICAgPGlucHV0IG5hbWU9IkxvZ2luVXNlciRQYXNzd29yZCIgdHlwZT0icGFzc3dvcmQiIGlkPSJMb2dpblVzZXJfUGFzc3dvcmQiIGNsYXNzPSJmb3JtLWNvbnRyb2wiIHBsYWNlaG9sZGVyPSJwYXNzd29yZCIgLz4NCiAgICAgICAgICAgICAgICAgICAgICAgICZuYnNwOw0KICAgICAgICAgICAgICAgICAgICA8L3A+DQogICAgICAgICAgICAgICAgICAgDQogICAgICAgICAgICAgICAgPC9maWVsZHNldD4NCiAgICAgICAgICAgICAgICA8cCBjbGFzcz0ic3VibWl0QnV0dG9uIj4NCiAgICAgICAgICAgICAgICAgICAgPGlucHV0IHR5cGU9InN1Ym1pdCIgbmFtZT0iTG9naW5Vc2VyJExvZ2luQnV0dG9uIiB2YWx1ZT0iQWNjZWRpIiBvbmNsaWNrPSJqYXZhc2NyaXB0OldlYkZvcm1fRG9Qb3N0QmFja1dpdGhPcHRpb25zKG5ldyBXZWJGb3JtX1Bvc3RCYWNrT3B0aW9ucygmcXVvdDtMb2dpblVzZXIkTG9naW5CdXR0b24mcXVvdDssICZxdW90OyZxdW90OywgdHJ1ZSwgJnF1b3Q7TG9naW5Vc2VyVmFsaWRhdGlvbkdyb3VwJnF1b3Q7LCAmcXVvdDsmcXVvdDssIGZhbHNlLCBmYWxzZSkpIiBpZD0iTG9naW5Vc2VyX0xvZ2luQnV0dG9uIiBjbGFzcz0iYnRuIGJ0bi1sZyBidG4tcHJpbWFyeSBidG4tYmxvY2siIC8+DQogICAgICAgICAgICAgICAgPC9wPg0KICAgICAgICAgICAgPC9kaXY+DQogICAgICAgIA0KICAgICANCiAgICA8L2Rpdj4NCiAgICA8L2Zvcm0+DQo8L2JvZHk+DQo8L2h0bWw+DQo=
ImageUrl needs a relative or absolute path. So try setting “src” attribute instead, as follows.
DirectCast(e.Item.FindControl("myIMG"), System.Web.UI.WebControls.Image).Attributes("src") = sBase64

How To Display Image Into Devexpress GridView / Devexpress Card View From Mysql

Here I would like to ask, how to display the image data into DevExpress DevExpress gridview or CardView.
For I will take a picture of data from mysql database that I keep with BLOB data type.
how or its code if using visual basic.?
for Code that I use:
Dim Query As String = "SELECT FTO.ALM_NIM as FOTO_ID, FTO.ALM_FOTO as FOTO FROM tbl_foto_alumni as FTO"
Using DA As New MySql.Data.MySqlClient.MySqlDataAdapter(Query, MyKonection)
Dim DTwisda As New DataTable
DA.Fill(DTwisda)
if Dtwisda.Rows.Count > 0 Then
GridControl.Datasource = DTwisda
MainView = CardView1
Dim RepItemImg As New Repository.RepositoryItemPictureEdit()
RepItemImg.SizeMode = DevExpress.XtraEditors.Controls.PictureSizeMode.Stretch
RepItemImg.BestFitWidth = 100
RepItemImg.CustomHeight = 150
With CardView1.Columns("FOTO")
.ColumnEdit = RepItemImg
End With
With CardView1
.OptionsBehavior.FieldAutoHeight = True
.MaximumCardRows = 2
.MaximumCardColumns = 6
End With
End If
End Using
To Screnshoot my program and the results of calling the data from the database, Please Check The Attachment.
already I attach the following word file.
ScreenShoot_Program
Please Help and Give The Solution.
Regards,
Tafary
Try This Code:
Dim row As DataRow
Dim i As Integer
For Each row In myDt.Rows
Column = New DataColumn
With Column
.DataType = GetType(Bitmap)
' .DefaultValue = Base64ToImage(row("Photo"))
.Unique = False
.ColumnName = "EmpPhoto"
End With
If Not myDt.Columns.Contains("EmpPhoto") Then
myDt.Columns.Add(Column)
End If
myDt.Rows(i)("EmpPhoto") = Base64ToImage(row("Photo"))
i += 1
myDt.AcceptChanges()
Next
i = 0
'myDt.Rows.Add(Column.DefaultValue)
Public Function Base64ToImage(base64String As String) As Image
Try
' Convert Base64 String to byte[]
Dim imageBytes As Byte() = Convert.FromBase64String(base64String)
Dim ms As New MemoryStream(imageBytes, 0, imageBytes.Length)
' Convert byte[] to Image
ms.Write(imageBytes, 0, imageBytes.Length)
Dim image1 As Image = Image.FromStream(ms, True)
Return image1
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Function

Add VB.NET Image object to HTML

I'm new in VB.NET and I create an object image Dim myimg As Image that contains an image generated with VB.NET and showing in a picture box.
I wanna add this image to HTML like this : Dim value$ = "<img src='myimg'>
"
Where value is used to replace tag in html file to show the picture generated in VB.NET
Is there a way to do this
Borrowing from this question and this article's helper class, you can do something like this:
Imports System.IO
Imports System.Drawing.Imaging
Public Class ImageHelper
' Convert an image to a Base64 string by using a MemoryStream. Save the
' image to the MemoryStream and use Convert.ToBase64String to convert
' the content of that MemoryStream to a Base64 string.
Public Shared Function ImageToBase64String(ByVal image As Image, _
ByVal imageFormat As ImageFormat)
Using memStream As New MemoryStream
image.Save(memStream, imageFormat)
Dim result As String = Convert.ToBase64String(memStream.ToArray())
memStream.Close()
Return result
: End Using
End Function
' Convert a Base64 string back to an image. Fill a MemorySTream based
' on the Base64 string and call the Image.FromStream() methode to
' convert the content of the MemoryStream to an image.
Public Shared Function ImageFromBase64String(ByVal base64 As String)
Using memStream As New MemoryStream(Convert.FromBase64String(base64))
Dim result As Image = Image.FromStream(memStream)
memStream.Close()
Return result
End Using
End Function
End Class
Within a button:
Dim myImage As Image = Image.FromFile("C:\test.png")
Dim base64 As String = ImageHelper.ImageToBase64String(myImage, ImageFormat.Png)
WebBrowser1.DocumentText = "<img alt=""Embedded Image"" src=""data:image/png;base64," & base64 & """ />"

VB .NET server generating Excel file on the fly

I have a VB .NET web application running on a server with multiple requests and performance requirements.
I have a function that retrieves some data from a DB and has to generate an excel report to show to the system users.
I somehow did it, but my solution has not the performance I'd like it to have: basically what my code does is:
The server accepts the request of report generating
The server fills an excel file
The server saves locally the xls file
The server attaches the file to the html response and the user downloads it
The server deletes the file (when? I need to handle borderline cases too)
The code snippet is like:
Public Sub ExportaDataTableToExcel(ByVal dt As System.Data.DataTable, ByVal Page As System.Web.UI.Page, ByVal ReportName As String)
Dim oExcel As Excel.Application
Dim oBook As Excel.Workbook
Dim oSheet As Excel.Worksheet
Dim colIndex As Integer
Dim rowIndex As Integer
oExcel = New Excel.Application
oBook = oExcel.Workbooks.Add(Type.Missing)
oSheet = oBook.Worksheets(1)
'Export the Columns to excel file
For Each dc In dt.Columns
colIndex = colIndex + 1
oSheet.Cells(1, colIndex) = dc.ColumnName
Next
oBook.SaveAs("C:\file.xls")
oSheet = Nothing
oBook.Close()
Page.Response.AddHeader("content-disposition", "attachment;filename=" & ReportName & ".xls")
Page.Response.Charset = String.Empty
Page.Response.ContentType = "vnd.application/ms-excel"
Page.Response.TransmitFile("C:\file.xls")
Page.Response.Flush()
Page.Response.End()
oExcel.Quit()
End Sub
As you can see the server generates the xls file locally in C:\file.xls, then trasmittes the file in the response page.
What I'd like to do, and I really don't know if it's possible as I did not found any example on this, is generating the xls file on the fly without saving it locally (maybe returning as a Stream of bytes or something like this) and then assembling this as xls file in the response page, without saving the file locally.
I tried using both Page and System.IO.StringWriter with no luck, maybe I'm doing something wrong.
The following code acts abnormally, asking me to save modifies on the file (on the server side), and downloading an xls file that has parts of the html of the page, generating errors about missing css files and displaying part of the page. So, with this approach I'm almost at zero. Here it is the code:
Public Sub ExportaDataTableToExcel(ByVal dt As System.Data.DataTable, ByVal Page As System.Web.UI.Page, ByVal ReportName As String)
Dim oExcel As Excel.Application
Dim oBook As Excel.Workbook
Dim oSheet As Excel.Worksheet
Dim colIndex As Integer
Dim rowIndex As Integer
oExcel = New Excel.Application
oBook = oExcel.Workbooks.Add(Type.Missing)
oSheet = oBook.Worksheets(1)
'Export the Columns to excel file
For Each dc In dt.Columns
colIndex = colIndex + 1
oSheet.Cells(1, colIndex) = dc.ColumnName
Next
oSheet = Nothing
oBook.Close()
Dim stringWrite As System.IO.StringWriter = New System.IO.StringWriter
Dim htmlWrite As System.Web.UI.Html32TextWriter = New System.Web.UI.Html32TextWriter(stringWrite)
Page.Response.Clear()
Page.Response.AddHeader("content-disposition", "attachment;filename=" & ReportName & ".xls")
Page.Response.Charset = String.Empty
Page.Response.ContentType = "vnd.application/ms-excel"
Page.Response.WriteFile(stringWrite.ToString)
Page.Response.Flush()
Page.Response.End()
oExcel.Quit()
End Sub
I know I can help with at least one of those problems you are having, Lateralus. Ive taken a snippet from our live server here to show you.
Edit: This one transmits a CSV file and we had the problem initially with the HTML showing up in the file. We opted to not use excel in this particular instance but, the problems are likely one in the same.
I believe that you need to add an additional header to your page response in order to remove the HTML that you are getting in the file.
Here is an example. As a warning, I'm not entirely sure how secure this method is. We use this within our network so it didn't need to be as locked down.
Dim LiveFileStream As FileStream = New FileStream("C:\inetpub\wwwroot\" &_
"Website\CSVFile.csv", FileMode.Open, FileAccess.Read)
Dim fileBuffer(CInt(LiveFileStream.Length)) As Byte
LiveFileStream.Read(fileBuffer, 0, CInt(LiveFileStream.Length))
LiveFileStream.Close()
Response.Clear()
Response.Charset = "utf-8"
Response.ContentType = "text/plain"
'I believe if you are to add the following header
'it will fix the problem with HTML showing in document
Response.AddHeader("Content-Length", fileBuffer.Length.ToString)
Response.AddHeader("Content-Disposition", "attachment; filename=CSVFile.csv")
Response.BinaryWrite(fileBuffer)
Response.End()