resize images to 100x100 for style preset images

This commit is contained in:
Mary Hipp 2024-08-08 12:56:55 -04:00
parent 9a4d075074
commit 442fc02429
3 changed files with 20 additions and 8 deletions

View File

@ -9,21 +9,33 @@ import { useCallback } from 'react';
*/ */
export const useImageUrlToBlob = () => { export const useImageUrlToBlob = () => {
const imageUrlToBlob = useCallback( const imageUrlToBlob = useCallback(
async (url: string) => async (url: string, dimension?: number) =>
new Promise<Blob | null>((resolve) => { new Promise<Blob | null>((resolve) => {
const img = new Image(); const img = new Image();
img.onload = () => { img.onload = () => {
console.log("on load")
const canvas = document.createElement('canvas'); const canvas = document.createElement('canvas');
canvas.width = img.width; let width = img.width;
canvas.height = img.height; let height = img.height;
if (dimension) {
const aspectRatio = img.width / img.height;
if (img.width > img.height) {
width = dimension;
height = dimension / aspectRatio;
} else {
height = dimension;
width = dimension * aspectRatio;
}
}
canvas.width = width;
canvas.height = height;
const context = canvas.getContext('2d'); const context = canvas.getContext('2d');
if (!context) { if (!context) {
console.log("no context")
return; return;
} }
context.drawImage(img, 0, 0); context.drawImage(img, 0, 0, width, height);
resolve( resolve(
new Promise<Blob | null>((resolve) => { new Promise<Blob | null>((resolve) => {
canvas.toBlob(function (blob) { canvas.toBlob(function (blob) {

View File

@ -72,7 +72,7 @@ export const useImageActions = (image_name?: string) => {
if (image_name && metadata && imageDTO) { if (image_name && metadata && imageDTO) {
const positivePrompt = await handlers.positivePrompt.parse(metadata) const positivePrompt = await handlers.positivePrompt.parse(metadata)
const negativePrompt = await handlers.negativePrompt.parse(metadata) const negativePrompt = await handlers.negativePrompt.parse(metadata)
const imageBlob = await imageUrlToBlob(imageDTO.image_url) const imageBlob = await imageUrlToBlob(imageDTO.image_url, 100)
dispatch(prefilledFormDataChanged({ name: "", positivePrompt, negativePrompt, image: imageBlob ? new File([imageBlob], "stylePreset.png", { type: 'image/png', }) : null })) dispatch(prefilledFormDataChanged({ name: "", positivePrompt, negativePrompt, image: imageBlob ? new File([imageBlob], "stylePreset.png", { type: 'image/png', }) : null }))
dispatch(isModalOpenChanged(true)) dispatch(isModalOpenChanged(true))

View File

@ -28,7 +28,7 @@ export const StylePresetListItem = ({ preset }: { preset: StylePresetRecordWithI
const { positive_prompt, negative_prompt } = preset_data; const { positive_prompt, negative_prompt } = preset_data;
let imageBlob = null; let imageBlob = null;
if (preset.image) { if (preset.image) {
imageBlob = await imageUrlToBlob(preset.image); imageBlob = await imageUrlToBlob(preset.image, 100);
} }
dispatch( dispatch(