Initial commit

This commit is contained in:
Gašper Dobrovoljc 2023-04-13 17:36:47 +02:00
commit de93ee957b
No known key found for this signature in database
GPG Key ID: 0E7E037018CFA5A5
24 changed files with 2117 additions and 0 deletions

24
.gitignore vendored Normal file
View File

@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?

4
.prettierrc Normal file
View File

@ -0,0 +1,4 @@
{
"singleQuote": true,
"trailingComma": "all"
}

3
.vscode/extensions.json vendored Normal file
View File

@ -0,0 +1,3 @@
{
"recommendations": ["svelte.svelte-vscode"]
}

47
README.md Normal file
View File

@ -0,0 +1,47 @@
# Svelte + TS + Vite
This template should help get you started developing with Svelte and TypeScript in Vite.
## Recommended IDE Setup
[VS Code](https://code.visualstudio.com/) + [Svelte](https://marketplace.visualstudio.com/items?itemName=svelte.svelte-vscode).
## Need an official Svelte framework?
Check out [SvelteKit](https://github.com/sveltejs/kit#readme), which is also powered by Vite. Deploy anywhere with its serverless-first approach and adapt to various platforms, with out of the box support for TypeScript, SCSS, and Less, and easily-added support for mdsvex, GraphQL, PostCSS, Tailwind CSS, and more.
## Technical considerations
**Why use this over SvelteKit?**
- It brings its own routing solution which might not be preferable for some users.
- It is first and foremost a framework that just happens to use Vite under the hood, not a Vite app.
This template contains as little as possible to get started with Vite + TypeScript + Svelte, while taking into account the developer experience with regards to HMR and intellisense. It demonstrates capabilities on par with the other `create-vite` templates and is a good starting point for beginners dipping their toes into a Vite + Svelte project.
Should you later need the extended capabilities and extensibility provided by SvelteKit, the template has been structured similarly to SvelteKit so that it is easy to migrate.
**Why `global.d.ts` instead of `compilerOptions.types` inside `jsconfig.json` or `tsconfig.json`?**
Setting `compilerOptions.types` shuts out all other types not explicitly listed in the configuration. Using triple-slash references keeps the default TypeScript setting of accepting type information from the entire workspace, while also adding `svelte` and `vite/client` type information.
**Why include `.vscode/extensions.json`?**
Other templates indirectly recommend extensions via the README, but this file allows VS Code to prompt the user to install the recommended extension upon opening the project.
**Why enable `allowJs` in the TS template?**
While `allowJs: false` would indeed prevent the use of `.js` files in the project, it does not prevent the use of JavaScript syntax in `.svelte` files. In addition, it would force `checkJs: false`, bringing the worst of both worlds: not being able to guarantee the entire codebase is TypeScript, and also having worse typechecking for the existing JavaScript. In addition, there are valid use cases in which a mixed codebase may be relevant.
**Why is HMR not preserving my local component state?**
HMR state preservation comes with a number of gotchas! It has been disabled by default in both `svelte-hmr` and `@sveltejs/vite-plugin-svelte` due to its often surprising behavior. You can read the details [here](https://github.com/rixo/svelte-hmr#svelte-hmr).
If you have state that's important to retain within a component, consider creating an external store which would not be replaced by HMR.
```ts
// store.ts
// An extremely simple external store
import { writable } from 'svelte/store'
export default writable(0)
```

13
index.html Normal file
View File

@ -0,0 +1,13 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>imgproc</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>

34
package.json Normal file
View File

@ -0,0 +1,34 @@
{
"name": "imgproc",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview",
"check": "svelte-check --tsconfig ./tsconfig.json"
},
"devDependencies": {
"@popperjs/core": "^2.11.7",
"@sveltejs/vite-plugin-svelte": "^2.0.3",
"@tsconfig/svelte": "^3.0.0",
"autoprefixer": "^10.4.7",
"chart.js": "^4.2.1",
"classnames": "^2.3.2",
"flowbite": "^1.6.4",
"flowbite-svelte": "^0.34.7",
"fusioncharts": "^3.20.0",
"postcss": "^8.4.21",
"postcss-load-config": "^4.0.1",
"svelte": "^3.55.1",
"svelte-chartjs": "^3.1.2",
"svelte-check": "^2.10.3",
"svelte-fusioncharts": "^1.0.0",
"svelte-preprocess": "^4.10.7",
"tailwindcss": "^3.1.5",
"tslib": "^2.5.0",
"typescript": "^4.9.3",
"vite": "^4.2.0"
}
}

1542
pnpm-lock.yaml Normal file

File diff suppressed because it is too large Load Diff

13
postcss.config.cjs Normal file
View File

@ -0,0 +1,13 @@
const tailwindcss = require('tailwindcss');
const autoprefixer = require('autoprefixer');
const config = {
plugins: [
//Some plugins, like tailwindcss/nesting, need to run before Tailwind,
tailwindcss(),
//But others, like autoprefixer, need to run after,
autoprefixer,
],
};
module.exports = config;

1
public/vite.svg Normal file
View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>

After

Width:  |  Height:  |  Size: 1.5 KiB

84
src/App.svelte Normal file
View File

@ -0,0 +1,84 @@
<script lang="ts">
import { Button, ButtonGroup, Fileupload, Spinner } from 'flowbite-svelte';
import { applyFilter, getHistogram } from './lib/processor';
import {
boxFilter,
sharpening,
type FilterFn,
edgeDetection,
sobel,
} from './lib/filters';
import { Line } from 'svelte-chartjs';
import 'chart.js/auto';
let files: FileList;
let originalSrc: string;
let filterSrc: string;
let processing = false;
let histogram: { red: number[]; green: number[]; blue: number[] };
$: if (files) {
originalSrc = URL.createObjectURL(files[0]);
getHistogram(originalSrc).then((h) => (histogram = h));
}
async function apply(filter: FilterFn) {
processing = true;
filterSrc = await applyFilter(originalSrc, filter);
processing = false;
}
</script>
<div class="p-4 space-y-2 w-screen">
<Fileupload bind:files />
<ButtonGroup>
<Button on:click={() => apply(boxFilter(2))}>Box Filter</Button>
<Button on:click={() => apply(sharpening)}>Sharpening</Button>
<Button on:click={() => apply(edgeDetection)}>Edge detection</Button>
<Button on:click={() => apply(sobel)}>Sobel</Button>
</ButtonGroup>
<div class="flex space-x-2 w-full">
<img src={originalSrc} alt="" class="w-1/2" />
{#if processing}
<div class="flex items-center justify-center w-1/2">
<Spinner />
</div>
{:else if filterSrc}
<img src={filterSrc} alt="" class="w-1/2" />
{/if}
</div>
<div class="w-1/2">
<Line
data={{
labels: new Array(256).fill(0).map((_, i) => i),
datasets: [
{
fill: true,
label: 'Red',
borderColor: 'red',
backgroundColor: 'rgba(255, 0, 0, 0.2)',
data: histogram?.red,
},
{
fill: true,
label: 'Green',
borderColor: 'green',
backgroundColor: 'rgba(0, 255, 0, 0.2)',
data: histogram?.green,
},
{
fill: true,
label: 'Blue',
borderColor: 'blue',
backgroundColor: 'rgba(0, 0, 255, 0.2)',
data: histogram?.blue,
},
],
}}
/>
</div>
</div>

3
src/app.postcss Normal file
View File

@ -0,0 +1,3 @@
@tailwind base;
@tailwind components;
@tailwind utilities;

BIN
src/assets/anya.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 MiB

BIN
src/assets/gapi.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 393 KiB

BIN
src/assets/juan.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

BIN
src/assets/mountains.avif Normal file

Binary file not shown.

66
src/lib/filters.ts Normal file
View File

@ -0,0 +1,66 @@
import { applyMatrix, grayscale, type Filter, clone, add } from './processor';
export type FilterFn = (imageData: ImageData) => void;
export function boxFilter(amount = 2): FilterFn {
return (imageData: ImageData) => {
const size = amount * 2 + 1;
const matrix = [];
for (let i = 0; i < size; i++) {
const row = [];
for (let j = 0; j < size; j++) {
row.push(1);
}
matrix.push(row);
}
applyMatrix(imageData, {
div: size ** 2,
matrix,
});
};
}
export const sharpening: FilterFn = (imageData: ImageData) => {
applyMatrix(imageData, {
matrix: [
[0, -1, 0],
[-1, 5, -1],
[0, -1, 0],
],
});
};
export const edgeDetection: FilterFn = (imageData: ImageData) => {
grayscale(imageData);
applyMatrix(imageData, {
matrix: [
[0, -1, 0],
[-1, 4, -1],
[0, -1, 0],
],
});
};
export const sobel: FilterFn = (imageData: ImageData) => {
grayscale(imageData);
const data2 = clone(imageData);
applyMatrix(imageData, {
matrix: [
[-1, 0, 1],
[-2, 0, 2],
[-1, 0, 1],
],
});
applyMatrix(data2, {
matrix: [
[-1, -2, -1],
[0, 0, 0],
[1, 2, 1],
],
});
add(imageData, data2);
};

209
src/lib/processor.ts Normal file
View File

@ -0,0 +1,209 @@
import type { FilterFn } from './filters';
export type Filter = {
matrix: number[][];
div?: number;
};
export async function applyFilter(
src: string,
filter: FilterFn,
): Promise<string> {
const image = await loadImage(src);
const canvas = document.createElement('canvas');
canvas.width = image.naturalWidth;
canvas.height = image.naturalHeight;
const ctx = canvas.getContext('2d');
ctx.drawImage(image, 0, 0, canvas.width, canvas.height);
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
filter(imageData);
ctx.putImageData(imageData, 0, 0);
const url = canvas.toDataURL();
canvas.remove();
return url;
}
async function loadImage(src: string) {
const image = new Image();
image.src = src;
return new Promise<HTMLImageElement>((res, rej) => {
image.onload = () => res(image);
image.onerror = rej;
});
}
async function getImageData(src: string): Promise<ImageData> {
const image = await loadImage(src);
const canvas = document.createElement('canvas');
canvas.width = image.naturalWidth;
canvas.height = image.naturalHeight;
const ctx = canvas.getContext('2d');
ctx.drawImage(image, 0, 0, canvas.width, canvas.height);
return ctx.getImageData(0, 0, canvas.width, canvas.height);
}
export async function getHistogram(src: string) {
const imageData = await getImageData(src);
const data = new ImageDataProxy(imageData);
const red = new Array(256).fill(0);
const green = new Array(256).fill(0);
const blue = new Array(256).fill(0);
for (let y = 0; y < imageData.height; y++) {
for (let x = 0; x < imageData.width; x++) {
const pix = data.getPixel(x, y);
red[pix.r]++;
green[pix.g]++;
blue[pix.b]++;
}
}
return { red, green, blue };
}
export function grayscale(imageData: ImageData) {
const data = new ImageDataProxy(imageData);
for (let y = 0; y < imageData.height; y++) {
for (let x = 0; x < imageData.width; x++) {
const pix = data.getPixel(x, y);
const avg = pix.r * 0.299 + pix.g * 0.587 + pix.b * 0.114;
data.setPixel(x, y, { r: avg, g: avg, b: avg, a: pix.a });
}
}
}
export function add(imageData1: ImageData, imageData2: ImageData) {
const data1 = new ImageDataProxy(imageData1);
const data2 = new ImageDataProxy(imageData2);
for (let y = 0; y < imageData1.height; y++) {
for (let x = 0; x < imageData1.width; x++) {
const pix1 = data1.getPixel(x, y);
const pix2 = data2.getPixel(x, y);
data1.setPixel(x, y, {
r: pix1.r + pix2.r,
g: pix1.g + pix2.g,
b: pix1.b + pix2.b,
a: pix1.a,
});
}
}
}
export function subtract(imageData1: ImageData, imageData2: ImageData) {
const data1 = new ImageDataProxy(imageData1);
const data2 = new ImageDataProxy(imageData2);
for (let y = 0; y < imageData1.height; y++) {
for (let x = 0; x < imageData1.width; x++) {
const pix1 = data1.getPixel(x, y);
const pix2 = data2.getPixel(x, y);
data1.setPixel(x, y, {
r: pix1.r - pix2.r,
g: pix1.g - pix2.g,
b: pix1.b - pix2.b,
a: pix1.a,
});
}
}
}
export function clone(imageData: ImageData): ImageData {
return {
width: imageData.width,
height: imageData.height,
colorSpace: imageData.colorSpace,
data: new Uint8ClampedArray(imageData.data),
};
}
export function applyMatrix(imageData: ImageData, filter: Filter) {
const { matrix, div = 1 } = filter;
const data = new ImageDataProxy(imageData);
const offset = -(matrix.length - 1) / 2;
for (let y = 0; y < imageData.height; y++) {
for (let x = 0; x < imageData.width; x++) {
const pix = data.getPixel(x, y);
let sum: Pixel = { r: 0, g: 0, b: 0, a: pix.a };
for (let my = 0; my < matrix.length; my++) {
for (let mx = 0; mx < matrix[my].length; mx++) {
const mpix = data.getPixel(x + mx - offset, y + my - offset);
const val = matrix[my][mx];
sum.r += mpix.r * val;
sum.g += mpix.g * val;
sum.b += mpix.b * val;
}
}
sum.r /= div;
sum.g /= div;
sum.b /= div;
data.setPixel(x, y, sum);
}
}
}
type Pixel = {
r: number;
g: number;
b: number;
a: number;
};
export class ImageDataProxy {
constructor(private readonly imageData: ImageData) {}
public getPixel(x: number, y: number): Pixel {
const { data, width, height } = this.imageData;
if (x > width - 1) x = width - 1;
else if (x < 0) x = 0;
if (y > height - 1) y = height - 1;
else if (y < 0) y = 0;
const i = (y * width + x) * 4;
return {
r: data[i],
g: data[i + 1],
b: data[i + 2],
a: data[i + 3],
};
}
public setPixel(x: number, y: number, pixel: Pixel) {
const { data, width, height } = this.imageData;
if (x > width - 1 || y > height - 1) return;
if (pixel.r > 255) pixel.r = 255;
else if (pixel.r < 0) pixel.r = 0;
if (pixel.g > 255) pixel.g = 255;
else if (pixel.g < 0) pixel.g = 0;
if (pixel.b > 255) pixel.b = 255;
else if (pixel.b < 0) pixel.b = 0;
const i = (y * width + x) * 4;
data[i] = pixel.r;
data[i + 1] = pixel.g;
data[i + 2] = pixel.b;
data[i + 3] = pixel.a;
}
}

8
src/main.ts Normal file
View File

@ -0,0 +1,8 @@
import "./app.postcss";
import App from "./App.svelte";
const app = new App({
target: document.getElementById("app"),
});
export default app;

2
src/vite-env.d.ts vendored Normal file
View File

@ -0,0 +1,2 @@
/// <reference types="svelte" />
/// <reference types="vite/client" />

13
svelte.config.js Normal file
View File

@ -0,0 +1,13 @@
import preprocess from "svelte-preprocess";
import { vitePreprocess } from "@sveltejs/vite-plugin-svelte";
export default {
// Consult https://svelte.dev/docs#compile-time-svelte-preprocess
// for more information about preprocessors
preprocess: [
vitePreprocess(),
preprocess({
postcss: true,
}),
],
};

16
tailwind.config.cjs Normal file
View File

@ -0,0 +1,16 @@
const config = {
content: [
"./src/**/*.{html,js,svelte,ts}",
"./node_modules/flowbite-svelte/**/*.{html,js,svelte,ts}",
],
theme: {
extend: {},
},
plugins: [require("flowbite/plugin")],
darkMode: "class",
};
module.exports = config;

20
tsconfig.json Normal file
View File

@ -0,0 +1,20 @@
{
"extends": "@tsconfig/svelte/tsconfig.json",
"compilerOptions": {
"target": "ESNext",
"useDefineForClassFields": true,
"module": "ESNext",
"resolveJsonModule": true,
/**
* Typecheck JS in `.svelte` and `.js` files by default.
* Disable checkJs if you'd like to use dynamic types in JS.
* Note that setting allowJs false does not prevent the use
* of JS in `.svelte` files.
*/
"allowJs": true,
"checkJs": true,
"isolatedModules": true
},
"include": ["src/**/*.d.ts", "src/**/*.ts", "src/**/*.js", "src/**/*.svelte"],
"references": [{ "path": "./tsconfig.node.json" }]
}

8
tsconfig.node.json Normal file
View File

@ -0,0 +1,8 @@
{
"compilerOptions": {
"composite": true,
"module": "ESNext",
"moduleResolution": "Node"
},
"include": ["vite.config.ts"]
}

7
vite.config.ts Normal file
View File

@ -0,0 +1,7 @@
import { defineConfig } from 'vite'
import { svelte } from '@sveltejs/vite-plugin-svelte'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [svelte()],
})