VBS to save binary64 picture data as .jpeg file - vbscript

I need to extract user pictures out of Active Directory (LDS) and save them as a .jpeg file. I am able to extract the binary 64 data for the photo attribute in AD but I don't know how to write it to a usable .jpeg file in my .vbs script. Please post sample code!

Since you already have the extracted binary data.. here's a sub to take that data and create a .jpg file. Just pass the binary data and a path to save (ie. c:\temp\pic.jpg).
Sub writeImage(binaryData, strFullPath)
Set objADO = CreateObject("ADODB.Stream")
objADO.Open
objADO.Type = 1
objADO.Position = 0
objADO.Write binaryData
objADO.SaveToFile strFullPath
Set objADO = Nothing
End Sub
If you didn't have the data, you could use this to pull it from a URL.
Function binaryURL(strURL)
Set objHttp = CreateObject("WinHttp.WinHttpRequest.5.1")
objHTTP.Open "GET", strURL, False
objHTTP.Send
binaryURL = objHTTP.ResponseBody
End Function
And then just do a..
Call writeImage(binaryURL("http://i.imgur.com/fr16Y6W.jpg"), "C:\temp\pic.jpg")

Related

MSXML2.ServerXMLHTTP and national characters

This question is related to this one: Character encoding Microsoft.XmlHttp in Vbscript, but differs in one thing, the national characters are in the domain name, not only arguments.
The task is: download a page from the given URL.
I already solved problem of passing UTF8 string into VBScript by reading it from UTF8 encoded file through ADO.
But now when I try opening it MSXML2.ServerXMLHTTP returns error: The URL is invalid.
Here is VBScript code:
Set objStream = CreateObject("ADODB.Stream")
objStream.CharSet = "utf-8"
objStream.Open
objStream.LoadFromFile("fileWithURL.txt")
url = objStream.ReadText()
objStream.Close
Set XMLHttpReq = CreateObject("MSXML2.ServerXMLHTTP")
XMLHttpReq.Open "GET", url, False
XMLHttpReq.send
WEBPAGE = XMLHttpReq.responseText
If you put something like hxxp://россия.рф/main/page5.html into the UTF8 encoded fileWithURL.txt the script will raise an error while working ok with hxxp://google.com.
The workaround is to use ascii representation of the domain name - but I yet haven't found PunnyCode encoder for vbscript (apart from Chillkat which is an overkill for my task).
Will appreciate your help on the main problem or workaround.
I've made an amazing journey in to depth of my hard drive and found a code writen by / for Jesper Høy. This was the source code of SimpleDNS Plus' IDN Conversion Tool at that time.
Archive.org page snapshot: http://www.simpledns.com/idn-convert.asp
Archive.org file snapshot: idn-convert-asp.zip
You can also copy the whole code from this gist.
Create a function to convert URLs.
Function DummyPuny(ByVal url)
Dim rSegments : rSegments = Split(url, "/")
If UBound(rSegments) > 1 Then
rSegments(2) = DomainPunyEncode(rSegments(2))
End If
DummyPuny = Join(rSegments, "/")
End Function
Then convert your url before making the request.
XMLHttpReq.Open "GET", DummyPuny(url), False

Download and save a webpage using vbscript

I am trying to give users the option to download and save a webpage to where ever they want. I have been looking all over for a solution but nothing seems to be working. I am using vbscript in classic asp.
This is what I tried last
dim xHttp: Set xHttp = createobject("Microsoft.XMLHTTP")
dim bStrm: Set bStrm = createobject("Adodb.Stream")
xHttp.Open "GET", "" &Session("ServerURL") & "/idautomation/IDAutomationStreamingLinear.aspx?D=MAPS$"&request.QueryString("catcode")&"%25"&request.QueryString("typecode")&"&X=0.09&BH=3&S=0&CC=T&LM=5&TM=7.5&ST=F", False
xHttp.Send
with bStrm
.type = 1 '//binary
.open
.write xHttp.responseBody
.savetofile "d:\DownloladPdf.pdf", 2 '//overwrite
end with
but its throwing a "Write to file failed. " on the .savetofile line.
I want the user to be able to chose where to save it to...
You can't save to the users computer from server side code VBscript directly as this would be a major security issue allowing drive by compromises of people browsing a web page. The reason possibly that it is throwing an error is that it is trying to save it server side, but there is no D: on the server.
Instead you want to serve the PDF to the browser using Response and let the browser display or save the PDF.
The below example is using a bytes array rather than a stream, but it should be similar. If you want to force it to download rather than show in the browser, change the content-disposition to attachment. You can also change the filename to whatever you like.
if Len(pdfBytes) > 0 then
Response.Clear()
Response.ContentType = "application/pdf"
Response.Charset = ""
Response.AddHeader "Cache-Control", "public, max-age=1" ' Setting Cache-Control to max-age=1 rather than no-cache due to IE8 bug
Response.AddHeader "content-disposition","inline; filename=filename.pdf"
Response.Buffer = True
Response.Expires = 0
Response.BinaryWrite(pdfBytes)
Response.Flush
Response.End
Response.Close
end if

Read files from URL

Is it possible to read files like .css and .js from a URL? For instance, I have a file, which is located at http://main/shared/css/main.css, and want to read this file and store its content in another file at c:\main.txt. I know how to read files in local drives but not sure how to do it for a URL. Any help is much appreciated.
You can use an XMLHttpRequest for this:
url = "http://main/shared/css/main.css"
Set req = CreateObject("Msxml2.XMLHttp.6.0")
req.open "GET", url, False
req.send
If req.Status = 200 Then
Set fso = CreateObject("Scripting.FileSystemObject")
fso.OpenTextFile("C:\main.txt", 2).Write req.responseText
End If
Yes as long as you know the file names in question you should be able to do a simple XMLHttpRequest
url = "http://main/shared/css/main.css"
Set req = CreateObject("Msxml2.XMLHttp.6.0")
req.open "GET", url, False
req.send
If req.Status = 200 Then
Set fso = CreateObject("Scripting.FileSystemObject")
fso.OpenTextFile("C:\main.txt", 8, true, 0).Write req.responseText
End If
A slight amend to the OpenTextFile line so the text file is created
locally if it does not exist.

How do I display an image from Sql Server with Microsoft Access?

I upsized an Access 2007 database to SQL Server 2008 R2. The images are in SQL Server as image type. Access has link to the table containing the image. When I try to display from within Access, it won't do it. It still has the OLE Object wrapper.
How can I get that image and display it on my forms in Access? I do not have the option, at the moment, to remove the images, put them in a directory and point to them (the best way I know but not an option). I need to read the image / blob file directly from SQL Server and display it on an Access form.
Thank you for any ideas.
I saw this but it did not help:
How to display image from sql server in ms access
http://access.bukrek.net/documentation looks like the file in folder method
Since Access 2010, you can use the PictureData property to store and display images from SQL Server. You will need a bound control for an SQL Server data type varbinary(max), which can be hidden, and an unbound Image control in MS Access. You can now simply say:
Private Sub Form_Current()
Me.MSAccessImageControl.PictureData = Me.SQLServerImage
End Sub
And vice versa. You will need to add some error management to that, but very little else.
Below is a function I have successfully used called BlobToFile. And I also posted the code that I use to test it. The picture gets dumped to a so-called temp file but its not truly temp because it isn't in the temp directory. You can manually delete the image file or else you'll have to write it to your temp folder instead. Then I have an image control where I display the picture.
Private Sub Command1_Click()
Dim r As DAO.Recordset, sSQL As String, sTempPicture As String
sSQL = "SELECT ID, PictureBlobField FROM MyTable"
Set r = CurrentDb.OpenRecordset(sSQL, dbSeeChanges)
If Not (r.EOF And r.BOF) Then
sTempPicture = "C:\MyTempPicture.jpg"
Call BlobToFile(sTempPicture, r("PictureBlobField"))
If Dir(sTempPicture) <> "" Then
Me.imagecontrol1.Picture = sTempPicture
End If
End If
r.Close
Set r = Nothing
End Sub
'Function: BlobToFile - Extracts the data in a binary field to a disk file.
'Parameter: strFile - Full path and filename of the destination file.
'Parameter: Field - The field containing the blob.
'Return: The length of the data extracted.
Public Function BlobToFile(strFile As String, ByRef Field As Object) As Long
On Error GoTo BlobToFileError
Dim nFileNum As Integer
Dim abytData() As Byte
BlobToFile = 0
nFileNum = FreeFile
Open strFile For Binary Access Write As nFileNum
abytData = Field
Put #nFileNum, , abytData
BlobToFile = LOF(nFileNum)
BlobToFileExit:
If nFileNum > 0 Then Close nFileNum
Exit Function
BlobToFileError:
MsgBox "Error " & Err.Number & ": " & Err.Description, vbCritical, _
"Error writing file in BlobToFile"
BlobToFile = 0
Resume BlobToFileExit
End Function

Display JPEG using Response.BinaryWrite

I'm displaying an image like this:
<img src='counter.asp'>
counter.asp is doing a hit-counter do determine how often the image was displayed (I'll replace it with a modrewrite URL).
The problem: in the counter.asp script I need to send the actual .jpg image to the browser. How could this be done? I suppose I need to load the image through FSO, and then send it using Response.BinaryWrite - any ideas?
To read and output binary you can simply use the ADODB.Stream object.
See the ADODB.Stream MSDN Library:
http://msdn.microsoft.com/en-us/library/ms675032(VS.85).aspx
Here's an example I found from Experts Exchange as well:
Function ReadBinaryFile(strFileName)
on error resume next
Set oStream = Server.CreateObject("ADODB.Stream")
if Err.Number <> 0 then
ReadBinaryFile=Err.Description
Err.Clear
exit function
end if
oStream.Type = 1
oStream.Open
oStream.LoadFromFile strFileName
if Err.Number<>0 then
ReadBinaryFile=Err.Description
Err.Clear
exit function
end if
ReadBinaryFile=oStream.Read
oStream.Close
set oStream = nothing
if Err.Number<>0 then ReadBinaryFile=Err.Description
End Function
you can just redirect your counter.asp to the image you want..
<%
response.redirect("/virtual/path/to/yourimage.jpg")
%>
FSO cannot load a binary file, only text. You will need to use a 3th party component.

Resources