画像解析
Base64(ベース64)とは
Base64 はバイナリデータ(画像、音声、ファイルなど)を、ASCII文字(テキスト)ひ変換するエンコード方式で、メール送信やWeb通信など、バイナリを直接扱えない環境で利用されます。
各6ビットを、64種類の文字(A〜Z, a〜z, 0〜9, +, /)に変換しします。
使われる場面の例
| 使用例 | 内容 |
|---|---|
| メール添付ファイル | MIME形式でファイルをBase64化 |
| 画像の埋め込み | HTMLやCSSでdata:image/png;base64,...のように記述 |
| API通信 | JSON内に画像などを含める際にBase64で埋め込む |
| QRコード | バイナリデータをテキスト化して埋め込み |
ファイル構成
./
├── app/
│ ├── api/
│ │ └── whats_image/
│ │ └── route.ts
│ ├── repositories/
│ │ └── ImageRepository.ts
│ ├── services/
│ │ └── GeminiService.ts
│ └── components/
│ └── ImageUploadForm.tsx
└── page.tsx
Base64でエンコード
ImageRepository.ts を作成し、fileToBase64() を定義し、画像を base64 エンコードして返します。
app/services/ImageRepository.tsx
export async function fileToBase64(file: File) {
const arrayBuffer = await file.arrayBuffer();
const buffer = Buffer.from(arrayBuffer);
return {
base64: buffer.toString("base64"),
mimeType: file.type,
};
}
app/services/ImageRepository.tsx
async function fileToBase64(file: File): Promise<{ base64: string; mimeType: string }> {
// バッファ取得
const arrayBuffer = await file.arrayBuffer();
const buffer = Buffer.from(arrayBuffer);
// Base64 と MIME Type を返す
return {
base64: buffer.toString("base64"),
mimeType: file.type,
};
}
画像処理
whatsImage() を定義し、base64 と MIME Type を取得します。
app/services/GeminiService.tsx
export async function fileToBase64(file: File): Promise<{ base64: string; mimeType: string }> {
const arrayBuffer = await file.arrayBuffer();
const buffer = Buffer.from(arrayBuffer);
return {
base64: buffer.toString("base64"),
mimeType: file.type,
};
}
Gemini APIリクエスト
インポート
GoogleGenAI と Modality をインポートします。
app/services/GeminiService.tsx
import { GoogleGenAI, Modality } from "@google/genai";
プロンプト生成&画像添付
画像を添付し、画像に対するプロンプトを生成します。
export async function whatsImage(file: File): Promise<string> {
const { base64, mimeType } = await fileToBase64(file);
// プロンプト生成&画像添付
const contents = [
{
parts: [
{
inlineData: {
mimeType,
data: base64,
},
},
{ text: この写真は何?" },
],
},
];
}
リクエスト & レスポンス
Gemini APIにリクエスト&レスポンスします。
export async function whatsImage(file: File): Promise<string> {
...
// GoogleGenAIインスタンス生成
const ai = new GoogleGenAI({ apiKey: API_KEY });
// APIリクエスト
const response = await ai.models.generateContent({
model: "gemini-2.0-flash",
config: { maxOutputTokens: 1024 },
contents,
});
// APIレスポンス
const text = response?.candidates?.[0]?.content?.parts?.[0]?.text || "No response";
return text;
}
API作成
アップロード画像取得
app/api/whats_image/ のPOSTルーティングを作成します。formData() からアップロードファイル image を取得します。
app/api/whats_image/route.ts
// インポート
import { whatsImage } from "@/app/services/GeminiService";
import { NextRequest, NextResponse } from "next/server";
export async function POST(req: NextRequest) {
// formData 取得
const formData = await req.formData();
// formData からアップロードファイル取得
const imageFile = formData.get('image') as File;
}
whats_image() 実行
whatsImage() をインポートして実行し message としてJSONでレスポンスします。
app/api/whats_image/route.ts
// インポート
import { whatsImage } from "@/app/services/GeminiService";
import { NextRequest, NextResponse } from "next/server";
export async function POST(req: NextRequest) {
const formData = await req.formData();
const imageFile = formData.get('image') as File;
// Gemini API に画像を送信して内容を説明させる
const text = await whatsImage(imageFile);
// レスポンスデータ生成
const data = { message: text };
// レスポンス
return NextResponse.json(data);
}
画像アップロードフォーム
コンポーネント
ImageUploadForm コンポーネントを `use client' で作成します。
app/components/ImageUploadForm.tsx
'use client';
export default function ImageUploadForm() {
return (
<div className="mx-auto max-w-2xl p-6 bg-white rounded-lg shadow-md space-y-4">
<h2 className="text-2xl font-bold">画像を教えて!</h2>
</div>
);
}
ステート変数
以下のステート変数を定義します。
| 項目 | 変数 | 型 |
|---|---|---|
| アップロードファイル | file | File |
| プレビュー画像URL | previewUrl | string |
| プロンプトメッセージ | message | string |
| ローディングフラグ | isLoading | boolean |
| 選択画像 | fileInputRef | boolean |
app/components/ImageUploadForm.tsx
import { useRef, useState } from 'react';
import Loading from '@/app/components/Loading';
import Image from 'next/image';
export default function ImageUploadForm() {
const [file, setFile] = useState<File | null>(null);
const [url, setURL] = useState<string | null>(null);
const [message, setMessage] = useState<string>('');
const [isLoading, setIsLoading] = useState(false);
const fileInputRef = useRef<HTMLInputElement>(null);
...
}
画像プレビュー
handleFileChange() を定義して、選択した画像のプレビュー処理を作成します。
app/components/ImageUploadForm.tsx
export default function ImageUploadForm() {
const [file, setFile] = useState<File | null>(null);
const [previewUrl, setPreviewUrl] = useState<string | null>(null);
const [message, setMessage] = useState<string>('');
const [isLoading, setIsLoading] = useState(false);
const fileInputRef = useRef<HTMLInputElement>(null);
const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const selectedFile = e.target.files?.[0] || null;
setFile(selectedFile);
if (selectedFile) {
const reader = new FileReader();
reader.onloadend = () => {
setPreviewUrl(reader.result as string);
};
reader.readAsDataURL(selectedFile);
} else {
setPreviewUrl(null);
}
};
return (
<div className="mx-auto p-6 rounded-lg shadow-md space-y-4">
<h2 className="text-2xl font-bold">画像を教えて!</h2>
<input type="file" accept="image/*" className="hidden"
onChange={handleFileChange}
ref={fileInputRef}
/>
<button type="button"
className="px-4 py-2 bg-gray-300 text-black rounded shadow hover:bg-gray-400"
onClick={() => fileInputRef.current?.click()}>
画像を選択
</button>
{previewUrl && (
<div className="flex flex-col items-center justify-center p-2 text-center">
<Image
src={previewUrl}
alt="Preview"
width={300}
height={300}
unoptimized
className="rounded shadow mt-1"
/>
</div>
)}
</div>
);
}
動作確認
画像を選択してプレビューできるか確認します。
画像送信
APIリクエスト
handleSubmit() を定義し、/api/whats_image に画像アップロードします。
app/services/GeminiService.tsx
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!file) return;
try {
setIsLoading(true);
setMessage('');
// formDataを作成して画像を追加
const formData = new FormData();
formData.append('image', file);
// APIに画像を送信
const response = await fetch('/api/whats_image', {
method: 'POST',
body: formData,
});
// レスポンスを取得
const data = await response.json();
// 結果を設定
setMessage(data.message);
} catch (error) {
console.error("Error uploading image:", error);
} finally {
setIsLoading(false);
}
};
送信ボタン
画像プレビューされた時にボタンを表示し、handleSubmit() を実行します。
app/services/GeminiService.tsx
{previewUrl && (
<div className="flex flex-col items-center justify-center p-2 text-center">
<Image
src={previewUrl}
alt="Preview"
width={300}
height={300}
unoptimized
className="rounded shadow mt-1" />
<button
onClick={handleSubmit}
className="mt-4 px-6 py-3 bg-sky-600 text-white rounded-xl hover:bg-sky-700 cursor-pointer"
disabled={!file || isLoading}
>画像を送信
</button>
</div>
)}
{message && (
<div className="text-left p-3 bg-gray-100 rounded shadow text-sm whitespace-pre-wrap">
<div>{message}</div>
</div>
)}
{isLoading && <Loading />}
動作確認
画像をアップロードして、AIプロンプトが表示されるか確認します。
画像生成
ファイル構成
./
├── app/
│ ├── api/
│ │ └── generate_image/
│ │ └── route.ts
│ ├── repositories/
│ │ └── ImageRepository.ts
│ ├── services/
│ │ └── GeminiService.ts
│ └── components/
│ ├── KeywordInput.tsx
│ └── ImageGenerateForm.tsx
└── page.tsx
uuid インストール
ランダムなIDを生成するモジュール uuid をインストールします。
ターミナル
npm i uuid
リポジトリ作成
インポート
ImageRepository にファイス操作に関するモジュールをインポートします。
app/repositories/ImageRepository.ts
import { writeFile, mkdir } from "fs/promises";
import { existsSync } from "fs";
import { join } from "path";
import { v4 as uuidv4 } from 'uuid';
画像フォルダ生成
アップロード画像フォルダ public/images/ を設定し、存在しない場合は自動生成します。
| モジュール | 内容 |
|---|---|
| writeFile | ファイル書き込み |
| mkdir | フォルダ作成 |
| existsSync | ファイルチェック |
| join | ファイルパス結合 |
| uuidv4 | UUID v4で ID生成 |
app/repositories/ImageRepository.ts
// 画像フォルダ
const DATA_DIR = join(process.cwd(), "public/images");
/**
* Gemini API を使用するためのディレクトリを確認し、存在しない場合は作成
*/
export async function ensureFile() {
if (!existsSync(DATA_DIR)) {
await mkdir(DATA_DIR, { recursive: true });
}
}
画像パスとURL
uploadImageInfo() を定義し、画像ファイルパスとURLを取得します。
export function uploadImageInfo(ext = ".png"): { filePath: string; url: string } {
// ディレクトリチェック
ensureFile();
// ファイル名をUUIDで生成
const fileName = uuidv4() + ext;
const filePath = join(DATA_DIR, fileName);
const url = `/images/${fileName}`;
return { filePath, url };
}
画像ファイル保存
saveImage() を定義し、指定の画像ファイルパスで保存します。
export async function saveImage(path: string, data: string, type: BufferEncoding = "base64") {
const buffer = Buffer.from(data, type);
await writeFile(path, buffer);
}
サービス作成
プロンプト生成
GeminiService に generateImage() を追加し、画像生成のためのプロンプトを作成します。
app/services/GeminiService.tsx
export async function generateImage(text: string) {
// 画像生成のためのプロンプトを作成
const prompt = `次のキーワードで画像生成(文字なし)\n\n${text}`;
}
Gemini APIリクエスト
画像生成モデル gemini-2.0-flash-preview-image-generation を指定して、Gemini API にリクエストします。
app/services/GeminiService.tsx
export async function generateImage(text: string) {
// 画像生成のためのプロンプトを作成
const prompt = `次のキーワードで画像生成して。画像内にテキスト、サイン、説明書きなどは一切含めないで。\n\nキーワード: ${text}`;
// GeminiAPIにリクエストを送信
const ai = new GoogleGenAI({ apiKey: API_KEY });
const response = await ai.models.generateContent({
model: "gemini-2.0-flash-preview-image-generation",
contents: prompt,
config: {
responseModalities: [Modality.TEXT, Modality.IMAGE]
},
});
}
生成AI画像保存
response の中に生成AI画像があれば画像をサーバに保存し、URLを返します。
app/services/GeminiService.tsx
export async function generateImage(text: string) {
...
// レスポンスから画像データを取得
const parts = response.candidates?.[0]?.content?.parts;
if (!parts) return "";
// ファイルパスとURLを取得し、画像ファイルをサーバ保存
const { filePath, url } = uploadImageInfo();
for (const part of parts) {
if (part.inlineData?.data) {
await saveImage(filePath, part.inlineData.data);
return url;
}
}
return "";
}
API作成
インポート
GoogleGenAI と ファイル操作関連のモジュールをインポートします。
app/services/GeminiService.tsx
import { GoogleGenAI, Modality } from "@google/genai";
import { writeFile, mkdir } from "fs/promises";
import { existsSync } from "fs";
import { join } from "path";
キーワードコンポーネント
テキストボックスにキーワードを入力して一時保存するコンポーネントを作成します。
コンポーネント作成
KeywordInput コンポーネントを作成し、引数を keywords, setKeyword の Props にします。
app/components/KeywordInput.tsx
'use client';
import { useState } from 'react';
interface Props {
keywords: string[];
setKeywords: (keywords: string[]) => void;
};
export default function KeywordInput({ keywords, setKeywords }: Props) {
return (
<div>KeywordInput</div>
);
}
ステート追加
ステート text, isComposing を追加します。
app/components/KeywordInput.tsx
'use client';
import { useState } from 'react';
interface Props {
keywords: string[];
setKeywords: (keywords: string[]) => void;
};
export default function KeywordInput({ keywords, setKeywords }: Props) {
const [text, setText] = useState("");
const [isComposing, setIsComposing] = useState(false);
...
}
イベントハンドラ定義
テキストボックス入力、キーボードの Enterキーのイベントハンドラを定義します。setKeywords() で、親コンポーネントの keywords を更新 していることに注目してください。
app/components/KeywordInput.tsx
export default function KeywordInput({ keywords, setKeywords }: Props) {
const [text, setText] = useState("");
const [isComposing, setIsComposing] = useState(false);
// テキストボックス変更イベントハンドラ
const handleTextChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setText(e.target.value);
};
// キーワード追加処理
const handleAddKeyword = () => {
if (text && !keywords.includes(text)) {
// 親コンポーネントの keywords 更新
setKeywords([...keywords, text]);
}
setText("");
};
// キーワード削除処理
const handleRemoveKeyword = (index: number) => {
const updated = [...keywords];
updated.splice(index, 1);
// 親コンポーネントの keywords 更新
setKeywords(updated);
};
// Enterキーの処理
const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
if (e.key === 'Enter' && !isComposing) {
e.preventDefault();
handleAddKeyword();
}
};
...
}
キーワード入力フォーム
キーワードのテキストボックスにイベントを追加し、keywords の値を繰り返し表示します。
export default function KeywordInput({ keywords, setKeywords }: Props) {
...
return (
<div>
<div className="flex gap-2">
{/* キーワードのテキストボックス */}
<input
type="text"
className="p-2 border border-gray-300 rounded w-full"
value={text}
onChange={handleTextChange}
onKeyDown={handleKeyDown}
onCompositionStart={() => setIsComposing(true)}
onCompositionEnd={() => setIsComposing(false)}
placeholder="キーワードを入力してEnter"
/>
</div>
<div className="flex flex-wrap gap-2 mt-2">
{/* キーワードを繰り返し表示 */}
{keywords.map((word, i) => (
<span
key={i}
className="bg-sky-500 text-white px-2 py-1 rounded-full text-sm flex items-center"
>
{word}
<button
onClick={() => handleRemoveKeyword(i)}
className="ml-2 text-white"
>×
</button>
</span>
))}
</div>
</div>
);
}
画像生成フォーム
画像生成フォームのコンポーネント ImageGenerateForm を生成します。Image, Loading, KeywordInput コンポーネントなどもインポートしておきます。
app/components/ImageGenerateForm.tsx
'use client';
import { useState } from 'react';
import Loading from '@/app/components/Loading';
import Image from 'next/image';
import KeywordInput from '@/app/components/KeywordInput';
export default function ImageGenerateForm() {
return (
<div className="mx-auto p-6 rounded-lg shadow-md space-y-4">
<h2 className="text-2xl font-bold">画像を教えて!</h2>
</div>
);
}
ステート追加
各種ステートを定義します。
| モジュール | 内容 | データ型 |
|---|---|---|
| isLoading | ローディングフラグ | boolean |
| previewUrl | 画像URL | string |
| keywords | 検索キーワード | string[] |
app/components/ImageGenerateForm.tsx
import { useState } from 'react';
export default function ImageGenerateForm() {
const [isLoading, setIsLoading] = useState(false);
const [previewUrl, setPreviewUrl] = useState("");
const [keywords, setKeywords] = useState<string[]>([]);
...
}
コンポーネント利用
各種コンポーネントを読み込みます。 KeywordInput コンポーネントには、keywords と setKeywords をバインドします。
app/components/ImageGenerateForm.tsx
export default function ImageGenerateForm() {
const [isLoading, setIsLoading] = useState(false);
const [previewUrl, setPreviewUrl] = useState("");
const [keywords, setKeywords] = useState<string[]>([]);
return (
<div className="mx-auto p-6 rounded-lg shadow-md space-y-4">
<h2 className="text-2xl font-bold">画像を教えて!</h2>
<KeywordInput keywords={keywords} setKeywords={setKeywords} />
{isLoading && <Loading />}
</div>
);
}
動作確認
キーワードコンポーネントが動作するか確認します。
APIリクエスト
handleSubmit() を定義し、画像生成API /api/generate_image へキーワードをリクエストします。
export default function ImageGenerateForm() {
...
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (keywords.length === 0) return;
setIsLoading(true);
// キーワードをカンマ区切りの文字列に変換
const text = keywords.join(', ');
// /api/generate_image エンドポイントにPOSTリクエストを送信
try {
const response = await fetch('/api/generate_image', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ text }),
});
// JSONレスポンスを取得
const data = await response.json();
// 画像のURLを設定
if (data.url) setPreviewUrl(data.url);
setIsLoading(false);
} catch (error) {
console.error("Error generating image:", error);
} finally {
setIsLoading(false);
}
};
...
}
動作確認
キーワードをいくつか入力し、API経由で Geminiの生成AI画像が表示されるか確認します。

コース内レッスン
- 1
Lesson 1
はじめに
レッスンを見る - 2
Lesson 2
プロジェクト作成
レッスンを見る - 3
Lesson 3
レイアウト
レッスンを見る - 4
Lesson 4
App Router
レッスンを見る - 5
Lesson 5
コンポーネント
レッスンを見る - 6
Lesson 6
React Hook
レッスンを見る - 7
Lesson 7
Memoアプリプロジェクト
レッスンを見る - 8
Lesson 8
APIルーティング
レッスンを見る - 9
Lesson 9
useEffect
レッスンを見る - 10
Lesson 10
ファイル操作
レッスンを見る - 11
Lesson 11
Gemini API でプロンプト
レッスンを見る - 13
Lesson 13
Gemini API で画像操作
レッスンを見る - 21
Lesson 21
Postman
レッスンを見る