Team Ai
Apppublic

huggingface-projects/stable-diffusion-multiplayer

sourceHugging Faceupdated 3y agoView on Hugging Face
351likes
utils.ts74 linesDownload Raw Back to lib
1import { PUBLIC_API_BASE } from '$env/static/public';2import { GRID_SIZE, FRAME_SIZE } from '$lib/constants';3export function base64ToBlob(base64image: string): Promise<Blob> {4	return new Promise((resolve) => {5		const img = new Image();6		img.onload = async () => {7			const w = img.width;8			const h = img.height;9			const canvas = document.createElement('canvas');10			canvas.width = w;11			canvas.height = h;12			const ctx = canvas.getContext('2d') as CanvasRenderingContext2D;13			ctx.drawImage(img, 0, 0, w, h);14 15			const imgBlob: Blob = await new Promise((r) =>16				canvas.toBlob(r as BlobCallback, 'image/jpeg', 0.95)17			);18			resolve(imgBlob);19		};20		img.src = base64image;21	});22}23 24export async function uploadImage(imagBlob: Blob, params: {25	prompt: string;26	position: { x: number; y: number };27	date: number;28	id: string;29	room: string;30}): Promise<{31	url: string;32	filename: string;33}> {34	// simple regex slugify string	for file name35	const promptSlug = slugify(params.prompt);36	const key = `${params.position.x}_${params.position.y}`;37	const fileName = `sd-${params.room}-${params.id}-${promptSlug}-${key}.jpeg`;38 39	const file = new File([imagBlob], fileName, { type: 'image/jpeg' });40 41	const formData = new FormData()42	formData.append('file', file)43 44	const response = await fetch(PUBLIC_API_BASE + "/uploadfile", {45		method: 'POST',46		body: formData47	});48	if (response.status === 200) {49		const data = await response.json();50		return data;51	}52	throw new Error('Failed to upload image');53}54export function round(pos: number, canvasSize: {55	width: number;56	height: number;57}) {58	const max = canvasSize.width - FRAME_SIZE59	const value = pos % GRID_SIZE < GRID_SIZE / 2 ? pos - (pos % GRID_SIZE) : pos + GRID_SIZE - (pos % GRID_SIZE);60	return Math.max(0, Math.min(Math.round(value), max))61}62 63 64function slugify(text: string) {65	if (!text) return '';66	return text67		.toString()68		.toLowerCase()69		.replace(/\s+/g, '-')70		.replace(/[^\w\-]+/g, '')71		.replace(/\-\-+/g, '-')72		.replace(/^-+/, '')73		.replace(/-+$/, '');74}