daShangDao_kfzgw-info/image/imageDllTest.go
2025-12-24 09:00:38 +08:00

110 lines
2.8 KiB
Go

package main
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"syscall"
"unsafe"
)
// ImageDLL 图片处理DLL结构
type imageDLL struct {
dll *syscall.DLL
processImage *syscall.Proc
createWhiteBottomCenteredImage *syscall.Proc
freeCString *syscall.Proc
}
// 初始化imageDLL
func InitImageDll() (*imageDLL, error) {
dllPath := filepath.Join("image", "dll", "image.dll")
if _, err := os.Stat(dllPath); os.IsNotExist(err) {
return nil, fmt.Errorf("image DLL 不存在: %s", dllPath)
}
if dll, err := syscall.LoadDLL(dllPath); err != nil {
return nil, fmt.Errorf("加载image DLL 失败: %s", err)
} else {
return &imageDLL{
dll: dll,
processImage: dll.MustFindProc("ProcessImage"),
createWhiteBottomCenteredImage: dll.MustFindProc("CreateWhiteBottomCenteredImage"),
freeCString: dll.MustFindProc("FreeCString"),
}, nil
}
}
func (m *imageDLL) ProcessImage(config *Config) error {
marshal, err := json.Marshal(config)
if err != nil {
return fmt.Errorf("json转换失败: %s", err)
}
fromString, _ := syscall.BytePtrFromString(string(marshal))
info, _, _ := m.processImage.Call(uintptr(unsafe.Pointer(fromString)))
cStr(info)
return nil
}
func (m *imageDLL) CreateWhiteBottomCenteredImage(config *Config, w int, h int) (string, error) {
proc, err2 := m.dll.FindProc("CreateWhiteBottomCenteredImage")
if err2 != nil {
return "", err2
}
marshal, err := json.Marshal(config)
if err != nil {
return "", fmt.Errorf("json转换失败: %s", err)
}
fromString, _ := syscall.BytePtrFromString(string(marshal))
info, _, _ := proc.Call(uintptr(unsafe.Pointer(fromString)), uintptr(w), uintptr(h))
return cStr(info), nil
}
// cStr 将 C 字符串指针转换为 Go 字符串
func cStr(ptr uintptr) string {
if ptr == 0 {
return ""
}
var b []byte
for {
c := *(*byte)(unsafe.Pointer(ptr))
if c == 0 {
break
}
b = append(b, c)
ptr++
}
return string(b)
}
func main() {
config := &Config{
OutputDir: "D:\\isbn_images\\result", // 输出根目录
FileName: "D:\\isbn_images\\result\\9771671688095.jpg",
MatchDir: "matched", // 满足条件的图片目录
UnmatchDir: "unmatched", // 不满足条件的图片目录
WhiteDir: "white",
EqualHeightDir: "equalHeight",
MinWhitePct: 0.1, // 纯白占比下限 10%
MaxWhitePct: 0.65, // 纯白占比上限 90%
Extensions: []string{"jpg", "jpeg", "png", "gif", "bmp", "webp"},
}
dll, err := InitImageDll()
if err != nil {
fmt.Println(err)
}
//err = dll.ProcessImage(config)
//if err != nil {
// fmt.Println(err)
//}
image, err := dll.CreateWhiteBottomCenteredImage(config, 800, 800)
if err != nil {
fmt.Println(err)
}
fmt.Println(image)
}