Skip to content

Self-hosted personal gallery application with online photo management and albums, supporting Live/Motion Photos, EXIF parsing, geolocation recognition, and an explore map.

feat(histogram): 新增照片直方图计算和展示组件

Timothy Yinf3a1391c565f
diff --git a/app/components/Histogram.vue b/app/components/Histogram.vue
new file mode 100644
index 00000000..e700b63d
--- /dev/null
+++ b/app/components/Histogram.vue
@@ -0,0 +1,113 @@
+<script lang="ts" setup>
+import { twMerge } from 'tailwind-merge'
+import {
+ calculateHistogramCompressed,
+ drawHistogramToCanvas,
+ type HistogramDataCompressed,
+} from '~/libs/histogram'
+
+const props = defineProps<{
+ thumbnailUrl: string
+ options?: Parameters<typeof drawHistogramToCanvas>[2]
+ class?: string
+}>()
+
+const canvasRef = useTemplateRef('canvasRef')
+const isLoading = ref(true)
+const isError = ref(false)
+const histogramData = ref<HistogramDataCompressed | null>(null)
+
+watchEffect(() => {
+ isLoading.value = true
+
+ const img = new Image()
+ img.crossOrigin = 'Anonymous'
+ img.src = props.thumbnailUrl
+
+ img.onerror = () => {
+ isError.value = true
+ isLoading.value = false
+ }
+
+ img.onload = () => {
+ const canvas = document.createElement('canvas')
+ const ctx = canvas.getContext('2d')
+ if (!ctx) {
+ isError.value = true
+ isLoading.value = false
+ return
+ }
+
+ const scale = 360 / Math.max(img.width, img.height)
+ const [w, h] = [
+ Math.floor(img.width * scale),
+ Math.floor(img.height * scale),
+ ]
+ canvas.width = w
+ canvas.height = h
+ ctx.drawImage(img, 0, 0, w, h)
+
+ try {
+ const imageData = ctx.getImageData(0, 0, w, h)
+ histogramData.value = calculateHistogramCompressed(imageData)
+ } catch (e) {
+ isError.value = true
+ console.error('Failed to calculate histogram', e)
+ } finally {
+ isLoading.value = false
+ }
+ }
+})
+
+watchEffect(() => {
+ if (histogramData.value && canvasRef.value) {
+ drawHistogramToCanvas(canvasRef.value, histogramData.value, props.options)
+ }
+})
+</script>
+
+<template>
+ <div :class="twMerge('relative w-full h-32 group overflow-hidden', $props.class)">
+ <Transition name="fade">
+ <div
+ v-if="isLoading"
+ class="absolute inset-0 bg-neutral-900/10 flex flex-col gap-2 items-center justify-center rounded-lg backdrop-blur-xl z-10 text-white"
+ >
+ <Icon
+ name="tabler:loader"
+ class="text-xl animate-spin"
+ />
+ <span class="text-xs font-medium">Rendering</span>
+ </div>
+ </Transition>
+ <Transition name="fade">
+ <div
+ v-if="isError"
+ class="absolute inset-0 bg-neutral-900/10 flex flex-col gap-2 items-center justify-center rounded-lg backdrop-blur-xl z-10 text-white"
+ >
+ <Icon
+ name="tabler:alert-triangle"
+ class="text-xl animate-spin"
+ />
+ <span class="text-xs font-medium">直方图加载失败</span>
+ </div>
+ </Transition>
+ <canvas
+ v-if="histogramData"
+ ref="canvasRef"
+ class="w-full h-full rounded-lg backdrop-blur-xl"
+ />
+ </div>
+</template>
+
+<style scoped>
+.fade-enter-active,
+.fade-leave-active {
+ @apply transition-all duration-150;
+}
+
+.fade-enter-from,
+.fade-leave-to {
+ @apply opacity-0;
+}
+</style>
diff --git a/app/components/photo/InfoPanel.vue b/app/components/photo/InfoPanel.vue
index c7cbf825..1aef8763 100644
--- a/app/components/photo/InfoPanel.vue
+++ b/app/components/photo/InfoPanel.vue
@@ -520,14 +520,28 @@ const onTagClick = (tag: string) => {
v-if="formatedExifData.captureParams"
:data="formatedExifData.captureParams"
/>
+
+ <div class="space-y-2">
+ <h4 class="text-sm font-medium text-white uppercase tracking-wide">
+ 直方图
+ </h4>
+
+ <Histogram
+ v-if="currentPhoto.thumbnailUrl"
+ :thumbnail-url="currentPhoto.thumbnailUrl"
+ />
+ </div>
+
<PhotoKVRenderer
v-if="formatedExifData.deviceInfo"
:data="formatedExifData.deviceInfo"
/>
+
<PhotoKVRenderer
v-if="formatedExifData.captureMode"
:data="formatedExifData.captureMode"
/>
+
<PhotoKVRenderer
v-if="formatedExifData.technicalParams"
:data="formatedExifData.technicalParams"
diff --git a/app/libs/histogram.ts b/app/libs/histogram.ts
new file mode 100644
index 00000000..2e26dff7
--- /dev/null
+++ b/app/libs/histogram.ts
@@ -0,0 +1,168 @@
+export interface HistogramData {
+ red: number[]
+ green: number[]
+ blue: number[]
+ gray: number[]
+}
+
+export interface HistogramDataCompressed {
+ red: number[]
+ green: number[]
+ blue: number[]
+ gray: number[]
+}
+
+const zeroArray = (length: number): number[] => new Array(length).fill(0)
+const compressHistogramBin = (data: number[]): number[] => {
+ const compressed: number[] = zeroArray(128)
+ for (let i = 0; i < data.length; i++) {
+ compressed[Math.floor(i / 2)]! += data[i] ?? 0
+ }
+ return compressed
+}
+
+export const calculateHistogramCompressed = (
+ imageData: ImageData,
+): HistogramDataCompressed => {
+ const histogram: HistogramData = {
+ red: zeroArray(256),
+ green: zeroArray(256),
+ blue: zeroArray(256),
+ gray: zeroArray(256),
+ }
+
+ const { data } = imageData
+ for (let i = 0; i < data.length; i += 4) {
+ const r = data[i]!
+ const g = data[i + 1]!
+ const b = data[i + 2]!
+ // const a = data[i + 3]
+ const gray = Math.round(0.299 * r + 0.587 * g + 0.114 * b)
+
+ histogram.red[r]!++
+ histogram.green[g]!++
+ histogram.blue[b]!++
+ histogram.gray[gray]!++
+ }
+
+ return {
+ red: compressHistogramBin(histogram.red),
+ green: compressHistogramBin(histogram.green),
+ blue: compressHistogramBin(histogram.blue),
+ gray: compressHistogramBin(histogram.gray),
+ }
+}
+
+export const drawHistogramToCanvas = (
+ canvas: HTMLCanvasElement,
+ histogram: HistogramDataCompressed,
+ options: {
+ padding: number
+ colors: {
+ background: string
+ border: string
+ grid: string
+ red: string
+ green: string
+ blue: string
+ gray: string
+ }
+ } = {
+ padding: 0,
+ colors: {
+ background: 'rgba(36, 36, 38, .65)',
+ border: 'rgba(255, 255, 255, .1)',
+ grid: 'rgba(255, 255, 255, .3)',
+ red: 'rgba(255, 98, 89, 1)',
+ green: 'rgba(46, 209, 87, 1)',
+ blue: 'rgba(59, 154, 255, 1)',
+ gray: 'rgba(255, 255, 255, 1)',
+ },
+ },
+) => {
+ const ctx = canvas.getContext('2d')
+ if (!ctx) return
+
+ const canvasRect = canvas.getBoundingClientRect()
+ const { width, height } = canvasRect
+ const dpr = window.devicePixelRatio || 1
+ canvas.width = width * dpr
+ canvas.height = height * dpr
+ ctx.scale(dpr, dpr)
+ canvas.style.width = `${width}px`
+ canvas.style.height = `${height}px`
+
+ ctx.clearRect(0, 0, width, height)
+
+ const maxCount = Math.max(
+ ...histogram.red,
+ ...histogram.green,
+ ...histogram.blue,
+ ...histogram.gray,
+ )
+
+ if (maxCount === 0) return
+
+ const chartWidth = width - options.padding * 2
+ const chartHeight = height - options.padding * 2
+
+ const drawBars = (data: number[], color: string, opacity: number = 1) => {
+ const barWidth = chartWidth / data.length
+ for (let i = 0; i < data.length; i++) {
+ const barHeight = ((data[i] ?? 0) / maxCount) * chartHeight
+
+ // Gradient from bar's top to bottom
+ const gradient = ctx.createLinearGradient(
+ 0,
+ options.padding + chartHeight - barHeight,
+ 0,
+ options.padding + chartHeight,
+ )
+
+ gradient.addColorStop(0, color.replace(/[\d.]+\)$/, `${opacity})`))
+ gradient.addColorStop(1, color.replace(/[\d.]+\)$/, `${opacity * 0.3})`))
+
+ ctx.fillStyle = gradient
+ ctx.globalAlpha = opacity
+
+ const x = options.padding + i * barWidth
+ const y = options.padding + chartHeight - barHeight
+ const w = barWidth * 0.8
+ const h = barHeight
+ const radius = Math.min(w / 2, 2)
+
+ ctx.beginPath()
+ ctx.roundRect(x, y, w, h, [radius, radius, 0, 0])
+ ctx.fill()
+ }
+ ctx.globalAlpha = 1
+ }
+
+ ctx.fillStyle = options.colors.background
+ ctx.fillRect(0, 0, width, height)
+
+ ctx.lineWidth = 0.2
+ ctx.strokeStyle = options.colors.grid
+ for (let i = 1; i <= 3; i++) {
+ ctx.beginPath()
+ ctx.moveTo(options.padding, options.padding + (chartHeight / 4) * i)
+ ctx.lineTo(width - options.padding, options.padding + (chartHeight / 4) * i)
+ ctx.stroke()
+ }
+
+ drawBars(histogram.gray, options.colors.gray, 0.4)
+ ctx.globalCompositeOperation = 'screen'
+ drawBars(histogram.red, options.colors.red, 0.8)
+ drawBars(histogram.green, options.colors.green, 0.8)
+ drawBars(histogram.blue, options.colors.blue, 0.8)
+ ctx.globalCompositeOperation = 'source-over'
+
+ ctx.strokeStyle = options.colors.border
+ ctx.lineWidth = 1
+ ctx.strokeRect(
+ options.padding - 0.5,
+ options.padding - 0.5,
+ chartWidth + 1,
+ chartHeight + 1,
+ )
+}
diff --git a/server/services/image/histogram.ts b/server/services/image/histogram.ts
new file mode 100644
index 00000000..a7a83cbd
--- /dev/null
+++ b/server/services/image/histogram.ts
@@ -0,0 +1,78 @@
+import sharp from 'sharp'
+
+export interface HistogramData {
+ r: number[]
+ g: number[]
+ b: number[]
+ gray: number[]
+}
+
+/**
+ * 使用现有的 Sharp 实例计算图片的直方图数据
+ * @param sharpInst Sharp 实例
+ * @returns 直方图数据,包含 RGB 和灰度通道的 256 个值
+ */
+export const calculateHistogram = async (
+ sharpInst: sharp.Sharp,
+): Promise<HistogramData> => {
+ try {
+ // 获取原始像素数据,确保是 RGB 格式
+ const { data, info } = await sharpInst
+ .clone() // 克隆 Sharp 实例以避免影响原实例
+ .removeAlpha() // 移除 alpha 通道
+ .raw()
+ .toBuffer({ resolveWithObject: true })
+
+ const { width, height, channels } = info
+ const totalPixels = width * height
+
+ // 初始化直方图数组(256个bin,对应0-255的像素值)
+ const histogramR = new Array(256).fill(0)
+ const histogramG = new Array(256).fill(0)
+ const histogramB = new Array(256).fill(0)
+ const histogramGray = new Array(256).fill(0)
+
+ // 遍历像素数据计算直方图
+ for (let i = 0; i < data.length; i += channels) {
+ const r = data[i]
+ const g = data[i + 1]
+ const b = data[i + 2]
+
+ // 累计 RGB 通道直方图
+ histogramR[r]++
+ histogramG[g]++
+ histogramB[b]++
+
+ // 计算灰度值(使用 ITU-R BT.709 标准)
+ const gray = Math.round(0.299 * r + 0.587 * g + 0.114 * b)
+ histogramGray[gray]++
+ }
+
+ // 归一化直方图(转换为百分比)
+ const normalizeHistogram = (hist: number[]) => {
+ return hist.map((count) => count / totalPixels)
+ }
+
+ return {
+ r: normalizeHistogram(histogramR),
+ g: normalizeHistogram(histogramG),
+ b: normalizeHistogram(histogramB),
+ gray: normalizeHistogram(histogramGray),
+ }
+ } catch (error) {
+ logger.image.error('Failed to calculate histogram', error)
+ throw error
+ }
+}
+
+/**
+ * 使用图片缓冲区计算直方图数据
+ * @param buffer 图片缓冲区
+ * @returns 直方图数据
+ */
+export const calculateHistogramFromBuffer = async (
+ buffer: Buffer,
+): Promise<HistogramData> => {
+ const sharpInst = sharp(buffer)
+ return calculateHistogram(sharpInst)
+}