Code Examples

Below you´ll find code examples on how to convert your images to base64 format in common programming languages.

C#

Convert image to base64 with C# code example. The following example demonstrates how to use the ToBase64String method to encode the byte array to a base64 string representation.

using (Image image = Image.FromFile(Path))
{
using (MemoryStream m = new MemoryStream())
{
image.Save(m, image.RawFormat);
byte[] imageBytes = m.ToArray();
// Convert byte[] to Base64 String
string base64String = Convert.ToBase64String(imageBytes);
return base64String;
}
}

Java

Convert image to base64 with Java code example.

public static String encodeToString(BufferedImage image, String type) {
String base64String = null;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
ImageIO.write(image, type, bos);
byte[] imageBytes = bos.toByteArray();
BASE64Encoder encoder = new BASE64Encoder();
base64String = encoder.encode(imageBytes);
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
return base64String;
}

Python

Convert image to base64 with Python code example.

import base64
imgdata = base64.b64decode(imgstring)
filename = 'some_image.jpg'
with open(filename, 'wb') as f:
f.write(imgdata)

PHP

Convert image to base64 with PHP code example.

$path = 'folder/image.png';
$type = pathinfo($path, PATHINFO_EXTENSION);
$data = file_get_contents($path);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);

Ruby

Convert image to base64 with Ruby code example. Use the built-in Base64 encoding library.

#!/usr/bin/env ruby
require 'base64'
File.open('imagetobase64.png', 'r') do|image_file|
puts Base64.encode64(image_file.read)
end