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(new tool): Images Formats Converter #1328

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
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
4 changes: 4 additions & 0 deletions components.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@ declare module '@vue/runtime-core' {
IconMdiSearch: typeof import('~icons/mdi/search')['default']
IconMdiTranslate: typeof import('~icons/mdi/translate')['default']
IconMdiTriangleDown: typeof import('~icons/mdi/triangle-down')['default']
ImageConverter: typeof import('./src/tools/image-converter/image-converter.vue')['default']
InputCopyable: typeof import('./src/components/InputCopyable.vue')['default']
IntegerBaseConverter: typeof import('./src/tools/integer-base-converter/integer-base-converter.vue')['default']
Ipv4AddressConverter: typeof import('./src/tools/ipv4-address-converter/ipv4-address-converter.vue')['default']
Expand Down Expand Up @@ -135,13 +136,16 @@ declare module '@vue/runtime-core' {
NConfigProvider: typeof import('naive-ui')['NConfigProvider']
NDivider: typeof import('naive-ui')['NDivider']
NEllipsis: typeof import('naive-ui')['NEllipsis']
NFormItem: typeof import('naive-ui')['NFormItem']
NH1: typeof import('naive-ui')['NH1']
NH3: typeof import('naive-ui')['NH3']
NIcon: typeof import('naive-ui')['NIcon']
NInputNumber: typeof import('naive-ui')['NInputNumber']
NLayout: typeof import('naive-ui')['NLayout']
NLayoutSider: typeof import('naive-ui')['NLayoutSider']
NMenu: typeof import('naive-ui')['NMenu']
NSpace: typeof import('naive-ui')['NSpace']
NSpin: typeof import('naive-ui')['NSpin']
NTable: typeof import('naive-ui')['NTable']
NumeronymGenerator: typeof import('./src/tools/numeronym-generator/numeronym-generator.vue')['default']
OtpCodeGeneratorAndValidator: typeof import('./src/tools/otp-code-generator-and-validator/otp-code-generator-and-validator.vue')['default']
Expand Down
4 changes: 4 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@
"highlight.js": "^11.7.0",
"iarna-toml-esm": "^3.0.5",
"ibantools": "^4.3.3",
"image-in-browser": "^3.2.0",
"js-base64": "^3.7.6",
"json5": "^2.2.3",
"jwt-decode": "^3.1.2",
Expand All @@ -88,7 +89,9 @@
"plausible-tracker": "^0.3.8",
"qrcode": "^1.5.1",
"randexp": "^0.5.3",
"roboto-base64": "^0.1.2",
"sql-formatter": "^13.0.0",
"svg2png-wasm": "^1.4.1",
"ua-parser-js": "^1.0.35",
"ulid": "^2.3.0",
"unicode-emoji-json": "^0.4.0",
Expand All @@ -99,6 +102,7 @@
"vue-router": "^4.1.6",
"vue-shadow-dom": "^4.2.0",
"vue-tsc": "^1.8.1",
"webp-converter-browser": "^1.0.4",
"vuedraggable": "^4.1.0",
"xml-formatter": "^3.3.2",
"xml-js": "^1.6.11",
Expand Down
40 changes: 37 additions & 3 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Binary file added public/svg2png_wasm_bg.wasm
Binary file not shown.
27 changes: 14 additions & 13 deletions src/composable/downloadBase64.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { extension as getExtensionFromMimeType, extension as getMimeTypeFromExtension } from 'mime-types';
import type { Ref } from 'vue';
import type { MaybeRef, Ref } from 'vue';
import _ from 'lodash';
import { get } from '@vueuse/core';

export {
getMimeTypeFromBase64,
Expand Down Expand Up @@ -75,21 +76,11 @@ function downloadFromBase64({ sourceValue, filename, extension, fileMimeType }:
}

function useDownloadFileFromBase64(
{ source, filename, extension, fileMimeType }:
{ source: Ref<string>; filename?: string; extension?: string; fileMimeType?: string }) {
return {
download() {
downloadFromBase64({ sourceValue: source.value, filename, extension, fileMimeType });
},
};
}

function useDownloadFileFromBase64Refs(
{ source, filename, extension }:
{ source: Ref<string>; filename?: Ref<string>; extension?: Ref<string> }) {
{ source: MaybeRef<string>; filename?: MaybeRef<string>; extension?: MaybeRef<string> }) {
return {
download() {
downloadFromBase64({ sourceValue: source.value, filename: filename?.value, extension: extension?.value });
downloadFromBase64({ sourceValue: get(source), filename: get(filename), extension: get(extension) });
},
};
}
Expand All @@ -116,3 +107,13 @@ function previewImageFromBase64(base64String: string): HTMLImageElement {

return img;
}

function useDownloadFileFromBase64Refs(
{ source, filename, extension }:
{ source: Ref<string>; filename?: Ref<string>; extension?: Ref<string> }) {
return {
download() {
downloadFromBase64({ sourceValue: source.value, filename: filename?.value, extension: extension?.value });
},
};
}
170 changes: 170 additions & 0 deletions src/tools/image-converter/image-converter.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
<script setup lang="ts">
import { Base64 } from 'js-base64';
import type { MemoryImage } from 'image-in-browser';
import { decodeImage, encodeBmp, encodeGif, encodeIco, encodeJpg, encodePng, encodePvr, encodeTga, encodeTiff } from 'image-in-browser';
import { arrayBufferToWebP } from 'webp-converter-browser';
import { createSvg2png, initialize } from 'svg2png-wasm';
import { normal as robotoBase64 } from 'roboto-base64';
import { useDownloadFileFromBase64 } from '@/composable/downloadBase64';
import { useQueryParamOrStorage } from '@/composable/queryParams';

function readAsText(file: File) {
return new Promise<string>((resolve, reject) => {
const reader = new FileReader();
reader.readAsText(file);
reader.onload = () => resolve(reader.result?.toString() ?? '');
reader.onerror = error => reject(error);
});
}

const status = ref<'idle' | 'done' | 'error' | 'processing'>('idle');
const file = ref<File | null>(null);

const svgScale = ref(2);
const base64OutputFile = ref('');
const fileName = ref('');
const fileExtension = ref('');
const { download } = useDownloadFileFromBase64(
{
source: base64OutputFile,
filename: fileName,
extension: fileExtension,
});

const outputQuality = useQueryParamOrStorage({ name: 'qual', storageName: 'imgconv:q', defaultValue: 0.95 });
const outputFormats = {
png: {
mime: 'image/png',
save: (image: MemoryImage) => encodePng({ image }),
},
jpg: {
mime: 'image/jpeg',
save: (image: MemoryImage) => encodeJpg({ image, quality: outputQuality.value }),
},
bmp: {
mime: 'image/bmp',
save: (image: MemoryImage) => encodeBmp({ image }),
},
gif: {
mime: 'image/gif',
save: (image: MemoryImage) => encodeGif({ image }),
},
ico: {
mime: 'image/x-icon',
save: (image: MemoryImage) => encodeIco({ image }),
},
tga: {
mime: 'image/tga',
save: (image: MemoryImage) => encodeTga({ image }),
},
pvr: {
mime: 'image/pvr',
save: (image: MemoryImage) => encodePvr({ image }),
},
tif: {
mime: 'image/tif',
save: (image: MemoryImage) => encodeTiff({ image }),
},
webp: {
mime: 'image/webp',
save: () => null,
},
};

const outputFormat = useQueryParamOrStorage({ name: 'fmt', storageName: 'imgconv:fmt', defaultValue: 'png' });
const outputFormatHasQuality = computed(() => {
return outputFormat.value === 'jpg';
});

const svgWasmLoaded = ref(false);

async function onFileUploaded(uploadedFile: File) {
const outputFormatValue = outputFormat.value;
file.value = uploadedFile;
let fileBuffer = new Uint8Array(await uploadedFile.arrayBuffer());

fileName.value = `${uploadedFile.name}`;
status.value = 'processing';
try {
if (outputFormatValue === 'webp') {
const encodedImage = await arrayBufferToWebP(fileBuffer);
fileExtension.value = 'webp';
base64OutputFile.value = `data:image/webp;base64,${Base64.fromUint8Array(new Uint8Array(await encodedImage.arrayBuffer()))}`;
}
else {
if (uploadedFile.type === 'image/svg+xml') {
if (!svgWasmLoaded.value) {
await initialize(fetch('/svg2png_wasm_bg.wasm'));
svgWasmLoaded.value = true;
}
const svg2png = createSvg2png({
fonts: [Base64.toUint8Array(robotoBase64)],
});
fileBuffer = await svg2png(await readAsText(uploadedFile), { scale: svgScale.value });
svg2png.dispose();
}
const decodedImage = decodeImage({
data: fileBuffer,
});

if (decodedImage == null) {
throw new Error('Invalid Image file!');
};

const outConfig = outputFormats[outputFormatValue as (keyof typeof outputFormats)];
const encodedImage = outConfig.save(decodedImage);
fileExtension.value = outputFormatValue;
base64OutputFile.value = `data:${outConfig.mime};base64,${Base64.fromUint8Array(encodedImage!)}`;
}
status.value = 'done';

download();
}
catch (e) {
status.value = 'error';
}
}
</script>

<template>
<div>
<div style="flex: 0 0 100%" mb-2>
<div mx-auto max-w-600px>
<c-file-upload
title="Drag and drop an image file here, or click to select a file"
accept="image/*"
paste-image
@file-upload="onFileUploaded"
/>
</div>
</div>

<c-select
v-model:value="outputFormat"
label="Output format:"
label-position="left"
:options="Object.keys(outputFormats)"
placeholder="Select output format"
mb-2
/>

<div mb-2 flex justify-center>
<n-form-item v-if="outputFormatHasQuality" label="Output quality:" label-placement="left">
<n-input-number v-model:value="outputQuality" :max="100" :min="0" w-full />
</n-form-item>
<n-form-item label="SVG scaling:" label-placement="left">
<n-input-number v-model:value="svgScale" :min="0" />
</n-form-item>
</div>

<div mt-3 flex justify-center>
<c-alert v-if="status === 'error'" type="error">
An error occured processing {{ fileName }}
</c-alert>
<n-spin
v-if="status === 'processing'"
size="small"
/>
</div>
</div>
</template>
Loading
Loading