Converting an Image to Base64

Hi all,

I have been reading up and trying to figure out how to convert an image to Base64. However, I’m a bit puzzled as to how I “should” accomplish this.

I’ve read that the EncodeBase64 and DecodeBase64 methods accept a “string” … but they don’t specify anything about binary data. Can these methods accept binary data?

From what I’ve read here in the forum, (as well as my Google searches), I am thinking that the following process “might” work??

  1. Use a BinarySteam to open and read the image file’s data.
  2. Put the image file’s data into a MemoryBlock.
  3. Pass the memory block to the EncodeBase64 method.

Would this work? Thoughts? Ideas? Suggestions?

Thank you! :slight_smile:

Yes, this works. Combine steps 1 and 2 into one step: read everything into a memoryblock.

Base64 encoding is specifically intended to encode binary data; using a String datatype won’t hurt anything.

Your process will work. You may also use the Picture.GetData method to get the binary picture data from any Picture object.

Thank you! I appreciate it… I just wanted to make sure that I was not way off on a crazy, wrong track of thought. Haha. :slight_smile:

Don’t use a MemoryBlock. You’ll just get multiple copies of the data in memory at once. Read directly into a String.

Here is how I do it:

[code]Public Function PictureToString(p as Picture) as String
//Returns a base64 encoded version of the picture’s data.
If p=Nil Then
Return “”
End If
Return EncodeBase64(p.GetData(Picture.FormatJPEG, Picture.QualityMedium),0)

End Function
[/code]

And, if you need to go the other direction:

[code]Public Function StringToPicture(data as String) as Picture
// Convert a base64 encoded string back to a picture
Dim p As picture
If data="" Then
Return Nil
End If
p=picture.FromData(DecodeBase64(data))
Return p

End Function
[/code]

Thank you @Kimball! That makes a lot of good sense… Yeah, I just wasn’t sure exactly in regards to the process of converting binary data to the string format in Xojo. :slight_smile:

Happy to help. Note that I chose to use the JPEG format at a medium quality. You may want to change that to suit your needs, of course.

@Kimball Larsen, if i want to resize the image to say a thumbnail and then do a base64, what do i need to do???
i don’t want to physically resize the image…

You’d need to draw the scaled image into a fresh Picture object

Dim original As Picture Dim thumb As New Picture(WIDTH, HEIGHT [,DEPTH]) ' new blank picture, depth optional thumb.Graphics.DrawPicture(original, 0, 0, WIDTH, HEIGHT) ' scale to WIDTH/HEIGHT

Should have been:

 thumb.Graphics.DrawPicture(original, 0, 0, WIDTH, HEIGHT, 0, 0, original.Width, original.Height)

Then just pass your thumb object to the pictureToString method and there you go.