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): ICO <> PNG Converter #1276

Open
wants to merge 4 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
7 changes: 5 additions & 2 deletions components.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,7 @@ declare module '@vue/runtime-core' {
HtmlWysiwygEditor: typeof import('./src/tools/html-wysiwyg-editor/html-wysiwyg-editor.vue')['default']
HttpStatusCodes: typeof import('./src/tools/http-status-codes/http-status-codes.vue')['default']
IbanValidatorAndParser: typeof import('./src/tools/iban-validator-and-parser/iban-validator-and-parser.vue')['default']
IcoConverter: typeof import('./src/tools/ico-converter/ico-converter.vue')['default']
'IconMdi:brushVariant': typeof import('~icons/mdi/brush-variant')['default']
'IconMdi:kettleSteamOutline': typeof import('~icons/mdi/kettle-steam-outline')['default']
IconMdiChevronDown: typeof import('~icons/mdi/chevron-down')['default']
Expand Down Expand Up @@ -135,14 +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']
NGi: typeof import('naive-ui')['NGi']
NGrid: typeof import('naive-ui')['NGrid']
NH1: typeof import('naive-ui')['NH1']
NH3: typeof import('naive-ui')['NH3']
NIcon: typeof import('naive-ui')['NIcon']
NLayout: typeof import('naive-ui')['NLayout']
NLayoutSider: typeof import('naive-ui')['NLayoutSider']
NMenu: typeof import('naive-ui')['NMenu']
NSpace: typeof import('naive-ui')['NSpace']
NTable: typeof import('naive-ui')['NTable']
NSpin: typeof import('naive-ui')['NSpin']
NTag: typeof import('naive-ui')['NTag']
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']
PasswordStrengthAnalyser: typeof import('./src/tools/password-strength-analyser/password-strength-analyser.vue')['default']
Expand Down
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,8 @@
"iarna-toml-esm": "^3.0.5",
"ibantools": "^4.3.3",
"js-base64": "^3.7.6",
"image-in-browser": "^3.1.0",
"js-base64": "^3.7.7",
"json5": "^2.2.3",
"jwt-decode": "^3.1.2",
"libphonenumber-js": "^1.10.28",
Expand Down
9 changes: 8 additions & 1 deletion pnpm-lock.yaml

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

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 });
},
};
}
92 changes: 92 additions & 0 deletions src/tools/ico-converter/ico-converter.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
<script setup lang="ts">
import { Base64 } from 'js-base64';
import { Transform, decodeIco, decodeImage, encodeIcoImages, encodePng } from 'image-in-browser';
import { useDownloadFileFromBase64 } from '@/composable/downloadBase64';

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

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

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

fileName.value = `${uploadedFile.name}`;
status.value = 'processing';
try {
if (uploadedFile.type.includes('icon')) {
const decodedIco = decodeIco({
data: fileBuffer,
largest: true,
});
if (decodedIco == null) {
throw new Error('Invalid ICO file!');
}
const encodedPng = encodePng({
image: decodedIco,
});
fileExtension.value = 'png';
base64OutputFile.value = `data:image/png;base64,${Base64.fromUint8Array(encodedPng)}`;
}
else {
const decodedImage = decodeImage({
data: fileBuffer,
});

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

const encodedICO = encodeIcoImages({
images: [16, 32, 64, 128, 256].map(size => Transform.copyResize({
image: decodedImage,
width: size,
maintainAspect: true,
})),
});
fileExtension.value = 'ico';
base64OutputFile.value = `data:image/x-icon;base64,${Base64.fromUint8Array(encodedICO)}`;
}
status.value = 'done';

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

<template>
<div>
<div style="flex: 0 0 100%">
<div mx-auto max-w-600px>
<c-file-upload
title="Drag and drop an ICO or PNG/JPEG file here, or click to select a file"
accept=".ico,.png,.jpg"
paste-image
@file-upload="onFileUploaded"
/>
</div>
</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>
12 changes: 12 additions & 0 deletions src/tools/ico-converter/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { PictureInPicture } from '@vicons/tabler';
import { defineTool } from '../tool';

export const tool = defineTool({
name: 'ICO/PNG converter',
path: '/ico-converter',
description: 'Convert from PNG/JPEG to/from ICO',
keywords: ['ico', 'png', 'jpeg', 'icon', 'converter'],
component: () => import('./ico-converter.vue'),
icon: PictureInPicture,
createdAt: new Date('2024-08-15'),
});
9 changes: 8 additions & 1 deletion src/tools/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { tool as base64FileConverter } from './base64-file-converter';
import { tool as base64StringConverter } from './base64-string-converter';
import { tool as basicAuthGenerator } from './basic-auth-generator';
import { tool as icoConverter } from './ico-converter';
import { tool as emailNormalizer } from './email-normalizer';

import { tool as asciiTextDrawer } from './ascii-text-drawer';
Expand Down Expand Up @@ -141,7 +142,13 @@ export const toolsByCategory: ToolCategory[] = [
},
{
name: 'Images and videos',
components: [qrCodeGenerator, wifiQrCodeGenerator, svgPlaceholderGenerator, cameraRecorder],
components: [
qrCodeGenerator,
wifiQrCodeGenerator,
svgPlaceholderGenerator,
cameraRecorder,
icoConverter,
],
},
{
name: 'Development',
Expand Down
68 changes: 66 additions & 2 deletions src/ui/c-file-upload/c-file-upload.vue
Original file line number Diff line number Diff line change
Expand Up @@ -5,22 +5,44 @@ const props = withDefaults(defineProps<{
multiple?: boolean
accept?: string
title?: string
pasteImage?: boolean
}>(), {
multiple: false,
accept: undefined,
title: 'Drag and drop files here, or click to select files',
pasteImage: false,
});

const emit = defineEmits<{
(event: 'filesUpload', files: File[]): void
(event: 'fileUpload', file: File): void
}>();

const { multiple } = toRefs(props);
const { multiple, pasteImage } = toRefs(props);

const isOverDropZone = ref(false);

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

const fileInput = ref<HTMLInputElement | null>(null);
const imgPreview = ref<HTMLImageElement | null>(null);
async function handlePreview(image: File) {
if (imgPreview.value) {
imgPreview.value.src = await toBase64(image);
}
}
function clearPreview() {
if (imgPreview.value) {
imgPreview.value.src = '';
}
}

function triggerFileInput() {
fileInput.value?.click();
Expand All @@ -39,7 +61,30 @@ function handleDrop(event: DragEvent) {
handleUpload(files);
}

function handleUpload(files: FileList | null | undefined) {
async function onPasteImage(evt: ClipboardEvent) {
if (!pasteImage.value) {
return false;
}

const items = evt.clipboardData?.items;
if (!items) {
return false;
}
for (let i = 0; i < items.length; i++) {
if (items[i].type.includes('image')) {
const imageFile = items[i].getAsFile();
if (imageFile) {
await handlePreview(imageFile);
emit('fileUpload', imageFile);
}
}
}
return true;
}

async function handleUpload(files: FileList | null | undefined) {
clearPreview();

if (_.isNil(files) || _.isEmpty(files)) {
return;
}
Expand All @@ -49,6 +94,7 @@ function handleUpload(files: FileList | null | undefined) {
return;
}

await handlePreview(files[0]);
emit('fileUpload', files[0]);
}
</script>
Expand All @@ -60,6 +106,7 @@ function handleUpload(files: FileList | null | undefined) {
'border-primary border-opacity-100': isOverDropZone,
}"
@click="triggerFileInput"
@paste.prevent="onPasteImage"
@drop.prevent="handleDrop"
@dragover.prevent
@dragenter="isOverDropZone = true"
Expand All @@ -73,6 +120,7 @@ function handleUpload(files: FileList | null | undefined) {
:accept="accept"
@change="handleFileInput"
>

<slot>
<span op-70>
{{ title }}
Expand All @@ -90,6 +138,22 @@ function handleUpload(files: FileList | null | undefined) {
<c-button>
Browse files
</c-button>

<div v-if="pasteImage">
<!-- separator -->
<div my-4 w-full flex items-center justify-center op-70>
<div class="h-1px max-w-100px flex-1 bg-gray-300 op-50" />
<div class="mx-2 text-gray-400">
or
</div>
<div class="h-1px max-w-100px flex-1 bg-gray-300 op-50" />
</div>

<p>Paste an image from clipboard</p>
</div>
</slot>
<div mt-2>
<img ref="imgPreview" width="150">
</div>
</div>
</template>
Loading