画像変換アプリ
アップロードする画像は、ドット絵に限定してください。
この要望について、セキュリティとパフォーマンスの観点から以下のように実装できます。
```
<!DOCTYPE html>
<html>
<head>
<title>画像変換アプリ</title>
<meta charset="UTF-8">
</head>
<body>
<div>
<h1>画像変換アプリ</h1>
<p>アップロードする画像は、ドット絵に限定してください。</p>
<form id="uploadForm">
<input type="file" name="image" accept="image/*">
<button type="submit">変換</button>
</form>
<div id="result"></div>
</div>
<script>
const uploadForm = document.querySelector("#uploadForm");
const resultDiv = document.querySelector("#result");
uploadForm.addEventListener("submit", (e) => {
e.preventDefault();
const formData = new FormData(uploadForm);
fetch("/api/convert", {
method: "POST",
body: formData
})
.then((response) => {
if (!response.ok) {
throw new Error("サーバーエラーが発生しました。");
}
return response.blob();
})
.then((blob) => {
const url = URL.createObjectURL(blob);
const img = new Image();
img.src = url;
img.alt = "変換結果";
img.width = "200";
img.height = "200";
resultDiv.appendChild(img);
URL.revokeObjectURL(url);
})
.catch((error) => {
console.error(error.message);
resultDiv.textContent = error.message;
});
});
</script>
</body>
</html>
```
このHTMLファイルは、画像をアップロードするフォームと、アップロードされた画像をドット絵に変換するAPIとの通信を行うスクリプトを含みます。
セキュリティ上の問題を回避するため、JavaScriptのevalは使用していません。また、他のサイトへの遷移やリダイレクトも行っていません。
このアプリの主要な機能は、画像をアップロードしてAPIに送信し、APIから返された画像を表示することです。画像変換APIの実装は以下のようになります。
```
const express = require("express");
const app = express();
const port = process.env.PORT || 3000;
const path = require('path');
const { createCanvas } = require('canvas');
const pixelate = require('pixelate-image');
const { createReadStream } = require('fs');
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, 'public')));
app.post("/api/convert", (req, res) => {
const file = req.files.image;
const pixelated = pixelate(createReadStream(file.path), {
resize: false,
resolution: 16
});
const canvas = createCanvas(pixelated.width, pixelated.height);
const ctx = canvas.getContext('2d');
ctx.putImageData(pixelated, 0, 0);
canvas.toBlob((blob) => {
res.setHeader('Content-Type', 'image/png');
res.setHeader('Content-Disposition', 'attachment; filename=converted.png');
res.send(blob);
});
});
app.listen(port, () => {
console.log(`Server is listening on port ${port}`);
});
```
このAPIは、アップロードされた画像を読み込み、pixelate-imageを使ってドット絵に変換し、Canvasに描画します。最後に、CanvasからBlobを作成して、レスポンスとして送信します。
このプログラムはエラー処理が不十分であり、複数回のアップロードなどでファイル名の重複が発生する可能性があります。さらに、画像変換の精度やドット絵の設定など、改善の余地があります。しかし、このプログラムは基本的な機能を備えた、安全なアップロードと変換の機能を提供します。
ジョークとしては、「アップロードする画像は、ロリポップのように甘くないドット絵に限定してください。」というものが考えられます。