68 lines
2.5 KiB
TypeScript
68 lines
2.5 KiB
TypeScript
/**
|
||
* 文件:imagelib.ts
|
||
* 作用:图像相关工具(路径解析 / wikilink 处理 / 资源定位)。
|
||
*/
|
||
|
||
import { getBlobArrayBuffer } from "obsidian";
|
||
import { wxUploadImage } from "./wechat/weixin-api";
|
||
import { NMPSettings } from "./settings";
|
||
import { IsWasmReady, LoadWasm } from "./wasm/wasm";
|
||
import AssetsManager from "./assets";
|
||
import { convertJpegIfNeeded } from "./exif-orientation";
|
||
|
||
declare function GoWebpToJPG(data: Uint8Array): Uint8Array; // wasm 返回 Uint8Array
|
||
declare function GoWebpToPNG(data: Uint8Array): Uint8Array;
|
||
declare function GoAddWatermark(img: Uint8Array, watermark: Uint8Array): Uint8Array;
|
||
|
||
export function IsImageLibReady() {
|
||
return IsWasmReady();
|
||
}
|
||
|
||
export async function PrepareImageLib() {
|
||
await LoadWasm();
|
||
}
|
||
|
||
export function WebpToJPG(data: ArrayBuffer): Uint8Array {
|
||
return GoWebpToJPG(new Uint8Array(data));
|
||
}
|
||
|
||
export function WebpToPNG(data: ArrayBuffer): Uint8Array {
|
||
return GoWebpToPNG(new Uint8Array(data));
|
||
}
|
||
|
||
export function AddWatermark(img: ArrayBuffer, watermark: ArrayBuffer): Uint8Array {
|
||
return GoAddWatermark(new Uint8Array(img), new Uint8Array(watermark));
|
||
}
|
||
|
||
export async function UploadImageToWx(data: Blob, filename: string, token: string, type?: string) {
|
||
if (!IsImageLibReady()) {
|
||
await PrepareImageLib();
|
||
}
|
||
|
||
try {
|
||
// 公众号端仍然存在基于 EXIF 的旋转问题:
|
||
// 统一将待上传的 JPEG 转为 PNG 并忽略 Orientation,避免出现倒置/倾斜。
|
||
const converted = await convertJpegIfNeeded(data, filename);
|
||
if (converted.changed) {
|
||
data = converted.blob;
|
||
filename = converted.filename;
|
||
}
|
||
} catch (error) {
|
||
console.warn('[UploadImageToWx] convert to PNG failed, fallback to original', error);
|
||
}
|
||
|
||
const watermark = NMPSettings.getInstance().watermark;
|
||
if (watermark != null && watermark != '') {
|
||
const watermarkData = await AssetsManager.getInstance().readFileBinary(watermark);
|
||
if (watermarkData == null) {
|
||
throw new Error('水印图片不存在: ' + watermark);
|
||
}
|
||
const watermarkImg = AddWatermark(await data.arrayBuffer(), watermarkData);
|
||
// AddWatermark 返回 Uint8Array,Blob 的类型签名对某些 TS 配置可能对 ArrayBufferLike 有严格区分
|
||
// 此处使用其底层 ArrayBuffer 来构造 Blob,避免类型不兼容错误
|
||
const bufferPart = watermarkImg.buffer as ArrayBuffer;
|
||
data = new Blob([bufferPart], { type: data.type });
|
||
}
|
||
return await wxUploadImage(data, filename, token, type);
|
||
}
|