How To: Base64 Image Transfer with Swift & Python

Frank Jia
The Startup
Published in
3 min readJun 13, 2020
Photo by Charlotte Butcher on Unsplash

I’m currently building an iOS app that requires some image processing functionality — the user would scan a food label, and I would need to parse the nutritional information and return some content back to the user.

In this blog post, I’m going to explore how we can enable image transfers through a REST API — which I built with Python. I’m also going to briefly discuss how I interact with this API with Swift code within the iOS app.

This is going to be part one of a two-part series. In this blog post, I go over my initial implementation of the client and API. In the next post, I’m going to explore another method for sending images through to the API. Let’s get started!

1 Base64 Encoding

Before we dive into a rough overview of the code, we need to think about how exactly we can transfer image data over the internet. You may be familiar with HTTP requests with JSON data — but this data is completely textual. How do we transfer visual content through textual data?

In my first implementation, I POST JSON request data to my server endpoint. The JSON would have an image property - which represents some textual representation of the image that we want to send.

To convert an image into a JSON-friendly format, we can use Base64 encoding. In short, Base64 converts a binary representation (an image file) into an ASCII string that is safe for plain text systems. The downside is that the resulting representation is ~1.3x larger in size than the original file. Keep this in mind when building the system — image file sizes can quickly add up, and that extra 33% of space might add up to be quite a lot over the long run!

2 Basic Python REST Server

To implement a basic server, I used flask together with flask-restful. The docs are pretty self explanatory, so I will focus more on the specific implementation for image transfer.

With flask-restful, endpoints are defined as Python classes. In this example, we parse the image argument from the POST JSON request body.

Simple enough! Now let’s take a look at the client side.

3 Sending Images with Swift (iOS)

Let’s say that we want the user to take an image, then send it to our backend. In iOS, the output from the camera is of type AVCapturePhoto. We can extract a Base64 encoded string like so:

To make requests to our backend server, we can use a library such as Alamofire. We can then create a service with a makeRequest function:

Of course, in an actual app, we would have a callback that executes some action when the response comes back. This is a pretty simple system. I hope that it helps you make your own image transfer app :).

--

--

Frank Jia
The Startup

Engineering Physics Student. Software Engineer. Fitness Enthusiast.