Skip to content

Commit

Permalink
feat(new tool): ICO <> PNG Converter
Browse files Browse the repository at this point in the history
Fix #1271
  • Loading branch information
sharevb committed Sep 1, 2024
1 parent 80e46c9 commit 4bf7470
Show file tree
Hide file tree
Showing 8 changed files with 276 additions and 61 deletions.
35 changes: 2 additions & 33 deletions components.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,30 +87,19 @@ 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:contentCopy': typeof import('~icons/mdi/content-copy')['default']
'IconMdi:kettleSteamOutline': typeof import('~icons/mdi/kettle-steam-outline')['default']
IconMdiArrowDown: typeof import('~icons/mdi/arrow-down')['default']
IconMdiArrowRight: typeof import('~icons/mdi/arrow-right')['default']
IconMdiArrowRightBottom: typeof import('~icons/mdi/arrow-right-bottom')['default']
IconMdiCamera: typeof import('~icons/mdi/camera')['default']
IconMdiChevronDown: typeof import('~icons/mdi/chevron-down')['default']
IconMdiChevronRight: typeof import('~icons/mdi/chevron-right')['default']
IconMdiClose: typeof import('~icons/mdi/close')['default']
IconMdiContentCopy: typeof import('~icons/mdi/content-copy')['default']
IconMdiDeleteOutline: typeof import('~icons/mdi/delete-outline')['default']
IconMdiDownload: typeof import('~icons/mdi/download')['default']
IconMdiEye: typeof import('~icons/mdi/eye')['default']
IconMdiEyeOff: typeof import('~icons/mdi/eye-off')['default']
IconMdiHeart: typeof import('~icons/mdi/heart')['default']
IconMdiPause: typeof import('~icons/mdi/pause')['default']
IconMdiPlay: typeof import('~icons/mdi/play')['default']
IconMdiRecord: typeof import('~icons/mdi/record')['default']
IconMdiRefresh: typeof import('~icons/mdi/refresh')['default']
IconMdiSearch: typeof import('~icons/mdi/search')['default']
IconMdiTranslate: typeof import('~icons/mdi/translate')['default']
IconMdiTriangleDown: typeof import('~icons/mdi/triangle-down')['default']
IconMdiVideo: typeof import('~icons/mdi/video')['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 All @@ -137,42 +126,22 @@ declare module '@vue/runtime-core' {
MenuLayout: typeof import('./src/components/MenuLayout.vue')['default']
MetaTagGenerator: typeof import('./src/tools/meta-tag-generator/meta-tag-generator.vue')['default']
MimeTypes: typeof import('./src/tools/mime-types/mime-types.vue')['default']
NAlert: typeof import('naive-ui')['NAlert']
NavbarButtons: typeof import('./src/components/NavbarButtons.vue')['default']
NCheckbox: typeof import('naive-ui')['NCheckbox']
NCode: typeof import('naive-ui')['NCode']
NCollapseTransition: typeof import('naive-ui')['NCollapseTransition']
NColorPicker: typeof import('naive-ui')['NColorPicker']
NConfigProvider: typeof import('naive-ui')['NConfigProvider']
NDatePicker: typeof import('naive-ui')['NDatePicker']
NDivider: typeof import('naive-ui')['NDivider']
NDynamicInput: typeof import('naive-ui')['NDynamicInput']
NEllipsis: typeof import('naive-ui')['NEllipsis']
NForm: typeof import('naive-ui')['NForm']
NFormItem: typeof import('naive-ui')['NFormItem']
NGi: typeof import('naive-ui')['NGi']
NGrid: typeof import('naive-ui')['NGrid']
NH1: typeof import('naive-ui')['NH1']
NH2: typeof import('naive-ui')['NH2']
NH3: typeof import('naive-ui')['NH3']
NIcon: typeof import('naive-ui')['NIcon']
NImage: typeof import('naive-ui')['NImage']
NInputGroup: typeof import('naive-ui')['NInputGroup']
NInputGroupLabel: typeof import('naive-ui')['NInputGroupLabel']
NInputNumber: typeof import('naive-ui')['NInputNumber']
NLayout: typeof import('naive-ui')['NLayout']
NLayoutSider: typeof import('naive-ui')['NLayoutSider']
NMenu: typeof import('naive-ui')['NMenu']
NProgress: typeof import('naive-ui')['NProgress']
NScrollbar: typeof import('naive-ui')['NScrollbar']
NSlider: typeof import('naive-ui')['NSlider']
NStatistic: typeof import('naive-ui')['NStatistic']
NSwitch: typeof import('naive-ui')['NSwitch']
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']
NUpload: typeof import('naive-ui')['NUpload']
NUploadDragger: typeof import('naive-ui')['NUploadDragger']
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']
PdfSignatureChecker: typeof import('./src/tools/pdf-signature-checker/pdf-signature-checker.vue')['default']
Expand Down
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,8 @@
"highlight.js": "^11.7.0",
"iarna-toml-esm": "^3.0.5",
"ibantools": "^4.3.3",
"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
31 changes: 23 additions & 8 deletions pnpm-lock.yaml

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

88 changes: 71 additions & 17 deletions src/composable/downloadBase64.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,14 @@
import { extension as getExtensionFromMime } from 'mime-types';
import type { Ref } from 'vue';
import { extension as getExtensionFromMimeType, extension as getMimeTypeFromExtension } from 'mime-types';
import type { MaybeRef, Ref } from 'vue';
import _ from 'lodash';
import { get } from '@vueuse/core';

export { getMimeTypeFromBase64, useDownloadFileFromBase64 };
export {
getMimeTypeFromBase64,
getMimeTypeFromExtension, getExtensionFromMimeType,
useDownloadFileFromBase64, useDownloadFileFromBase64Refs,
previewImageFromBase64,
};

const commonMimeTypesSignatures = {
'JVBERi0': 'application/pdf',
Expand Down Expand Up @@ -36,30 +42,78 @@ function getFileExtensionFromMimeType({
defaultExtension?: string
}) {
if (mimeType) {
return getExtensionFromMime(mimeType) ?? defaultExtension;
return getExtensionFromMimeType(mimeType) ?? defaultExtension;
}

return defaultExtension;
}

function useDownloadFileFromBase64({ source, filename }: { source: Ref<string>; filename?: string }) {
function downloadFromBase64({ sourceValue, filename, extension, fileMimeType }:
{ sourceValue: string; filename?: string; extension?: string; fileMimeType?: string }) {
if (sourceValue === '') {
throw new Error('Base64 string is empty');
}

const defaultExtension = extension ?? 'txt';
const { mimeType } = getMimeTypeFromBase64({ base64String: sourceValue });
let base64String = sourceValue;
if (!mimeType) {
const targetMimeType = fileMimeType ?? getMimeTypeFromExtension(defaultExtension);
base64String = `data:${targetMimeType};base64,${sourceValue}`;
}

const cleanExtension = extension ?? getFileExtensionFromMimeType(
{ mimeType, defaultExtension });
let cleanFileName = filename ?? `file.${cleanExtension}`;
if (extension && !cleanFileName.endsWith(`.${extension}`)) {
cleanFileName = `${cleanFileName}.${cleanExtension}`;
}

const a = document.createElement('a');
a.href = base64String;
a.download = cleanFileName;
a.click();
}

function useDownloadFileFromBase64(
{ source, filename, extension }:
{ source: MaybeRef<string>; filename?: MaybeRef<string>; extension?: MaybeRef<string> }) {
return {
download() {
if (source.value === '') {
throw new Error('Base64 string is empty');
}
downloadFromBase64({ sourceValue: get(source), filename: get(filename), extension: get(extension) });
},
};
}

function previewImageFromBase64(base64String: string): HTMLImageElement {
if (base64String === '') {
throw new Error('Base64 string is empty');
}

const img = document.createElement('img');
img.src = base64String;

const container = document.createElement('div');
container.appendChild(img);

const { mimeType } = getMimeTypeFromBase64({ base64String: source.value });
const base64String = mimeType
? source.value
: `data:text/plain;base64,${source.value}`;
const previewContainer = document.getElementById('previewContainer');
if (previewContainer) {
previewContainer.innerHTML = '';
previewContainer.appendChild(container);
}
else {
throw new Error('Preview container element not found');
}

const cleanFileName = filename ?? `file.${getFileExtensionFromMimeType({ mimeType })}`;
return img;
}

const a = document.createElement('a');
a.href = base64String;
a.download = cleanFileName;
a.click();
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'),
});
Loading

0 comments on commit 4bf7470

Please sign in to comment.