Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(encodeImage): support Blob and ArrayBuffer too #59

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 35 additions & 9 deletions src/browser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,16 +94,42 @@ export class Ollama {
}
}

async encodeImage(image: Uint8Array | string): Promise<string> {
if (typeof image !== 'string') {
// image is Uint8Array convert it to base64
const uint8Array = new Uint8Array(image)
const numberArray = Array.from(uint8Array)
const base64String = btoa(String.fromCharCode.apply(null, numberArray))
return base64String
/**
* Encodes an image as a base64 string.
* @param image - The image to encode. Can be a Blob, Uint8Array, ArrayBuffer, or a base64 string.
* @returns A promise that resolves to the base64 encoded image.
*/
async encodeImage(
image: Blob | Uint8Array | ArrayBuffer | string,
): Promise<string> {
if (typeof image === "string" && !image.startsWith("blob:")) {
return image; // possibly already base64
}
// the string may be base64 encoded
return image

const base64url = (await new Promise((r) => {
const reader = new FileReader();
reader.onload = () => r(reader.result);
if (typeof image === "string" && image.startsWith("blob:")) {
const xhr = new XMLHttpRequest();
xhr.open("GET", image, true);
xhr.responseType = "blob";
xhr.onload = function () {
const reader = new FileReader();
reader.onload = function () {
r(reader.result);
};
reader.readAsDataURL(xhr.response);
};
xhr.send();
} else if (image instanceof Blob) {
reader.readAsDataURL(image);
} else {
reader.readAsDataURL(new Blob([image]));
}
})) as any;

// remove the `data:...;base64,` part
return base64url.slice(base64url.indexOf(",") + 1);
}

generate(
Expand Down