DIY Image Hosting on Cloudflare Workers with KV

Requirements

Posting on NodeSeek requires you to bring your own image hosting.

We have already implemented a simple KV database. So, by the same principle, isn't image hosting just the same thing? You send the system a path, and the system returns the image data to you.


Approach

I designed to store the image's base64 data in KV.

Because this way you can manage it directly in the KV backend; when the human eye reads the backend data, there won't be any weird characters; and it's more convenient to copy-paste and transfer between different systems.

The downside is that the data size will increase, by 33%.


Practice

First, convert the image to base64 using other websites, such as https://oktools.net/image2base64

A gif image like this

gets the following large chunk of base64 data.

OKTools image to Base64 page showing 233.gif and Base64 restore image button

On the basis of pastebin, we use these base64 data as the value, and set 233.gif as the key.

PasteBin notepad: key is 233.gif, with Save and localStorage buttons

After saving, we can retrieve these base64 data through 233.gif, like this:

Visiting 233.gif in the address bar shows a long block of base64 data

Asking GPT for help, we get the following code to convert base64 data into an image and return it to the http request.

GPT-provided code returning base64 data as an image

Add the function from this code to worker.js

function base64ToBlob(base64String) {
  var parts = base64String.split(';base64,');
  var contentType = parts[0].split(':')[1];
  var raw = atob(parts[1]);
  var rawLength = raw.length;
  var uInt8Array = new Uint8Array(rawLength);
  for (var i = 0; i < rawLength; ++i) {
    uInt8Array[i] = raw.charCodeAt(i);
  }
  return new Blob([uInt8Array], { type: contentType });
}

Then before returning the http request, just add this one extra processing step.

Code editor with a red box highlighting the base64ToBlob function call

The effect is as follows:

Accessing 233.gif through imghost returns an animated image, page shows pixel dog animation


========

End

Clean up the code a bit, then upload.

Use a configuration item to set the system type.

config option system_type highlighted as imghost in the code

Github: https://github.com/crazypeace/url-Shorten-Worker/

Demo site: https://imghost.crazypeace.workers.dev/imghostimghost


Comments