Tuesday, April 24, 2012

Base64 Encoding Images in CSS

I am writing a little project to parse a CSS file, and base64 encode all the background images.

While I am able to parse the CSS correctly, it seems that everytime I try to convert the image file into a base64Encoded string, the string returned is always exactly the same.

What am I doing wrong?

Here's the encoder. Please assume that all image paths are passing correctly to the method. In this instance, all images are fully qualified urls, so the first section of the method is what is doing the conversion.

Public Sub EncodeImage(ByVal _File As String)
If _File.StartsWith("http") OrElse _File.StartsWith("https") Then
Using _wc As New WebClient()
_wc.Headers.Add("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv: Gecko/20101203 Firefox/3.6.13")
_wc.DownloadFile(_File, "c:\temp.png")
Dim _d As Byte() = _wc.DownloadData(_File)
ImageStrings.Add(New ImageTyping() With {
.SourceFile = _File,
.Base64String = Convert.ToBase64String(_d)
_d = Nothing
End Using
Using _fs As New FileStream(_File, IO.FileMode.Open)
Using _br As New BinaryReader(_fs)
Dim _i As Byte() = _br.ReadBytes(_fs.Length)
ImageStrings.Add(New ImageTyping() With {
.SourceFile = _File,
.Base64String = Convert.ToBase64String(_i)
_i = Nothing
End Using
End Using
End If
End Sub

Each and every string returned from this is: iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAAGXcA1uAAAAKUlEQVRIx2P4//+/DwwzUJUzoiRGNYxqGNUwGDSMWjBqwagFoxbQAAMAfS9kqktT8qQAAAAASUVORK5CYII=

No comments:

Post a Comment