分享:图片识别改名,能识别图片中的文字并批量改名的工具,用WPF和阿里云来完成

下面为你详细介绍如何使用 WPF(Windows Presentation Foundation)和阿里云 OCR(光学字符识别)服务开发一个能识别图片文字并批量改名的工具。

项目背景

在日常工作和生活中,我们常常会遇到大量图片文件,这些图片文件名可能没有实际意义,手动为其命名既耗时又容易出错。借助 OCR 技术能够识别图片中的文字信息,将这些文字作为图片的新文件名,可提高文件管理效率。阿里云 OCR 具备高精度、高稳定性的特点,能准确识别多种图片格式中的文字。结合 WPF 开发的桌面应用程序,能为用户提供直观便捷的操作界面。

界面设计

  • 文件选择按钮:用于选择需要处理的图片文件夹。
  • 处理按钮:点击后开始识别图片文字并改名。
  • 进度条:显示处理进度。
  • 日志输出框:展示处理过程中的信息,如文件名、识别结果等。

详细代码步骤过程

1. 创建 WPF 项目

在 Visual Studio 中创建一个新的 WPF 应用程序项目。

2. 安装阿里云 OCR SDK

通过 NuGet 包管理器安装 Aliyun.SDK.ocr20191230 包。

3. 设计 XAML 界面

以下是 MainWindow.xaml 的代码:

复制代码
<Window x:Class="ImageOCRRenamer.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="图片识别改名工具" Height="450" Width="800">
    <Grid>
        <Button Content="选择图片文件夹" HorizontalAlignment="Left" Margin="20,20,0,0" VerticalAlignment="Top" Width="150" Click="SelectFolderButton_Click"/>
        <Button Content="开始处理" HorizontalAlignment="Left" Margin="200,20,0,0" VerticalAlignment="Top" Width="150" Click="ProcessButton_Click"/>
        <ProgressBar x:Name="ProgressBar" HorizontalAlignment="Left" Height="20" Margin="20,60,0,0" VerticalAlignment="Top" Width="740"/>
        <TextBox x:Name="LogTextBox" HorizontalAlignment="Left" Height="320" Margin="20,100,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="740" IsReadOnly="True"/>
    </Grid>
</Window>
4. 编写 C# 代码

以下是 MainWindow.xaml.cs 的代码:

复制代码
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using Aliyun.SDK.ocr20191230;
using Aliyun.SDK.ocr20191230.Models;
using AlibabaCloud.TeaUtil;
using AlibabaCloud.TeaUtil.Models;
using AlibabaCloud.DarabonbaOpenApi.Models;

namespace ImageOCRRenamer
{
    public partial class MainWindow : Window
    {
        private string _selectedFolder;
        private List<string> _imageFiles;

        public MainWindow()
        {
            InitializeComponent();
        }

        private void SelectFolderButton_Click(object sender, RoutedEventArgs e)
        {
            var dialog = new System.Windows.Forms.FolderBrowserDialog();
            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                _selectedFolder = dialog.SelectedPath;
                _imageFiles = Directory.GetFiles(_selectedFolder, "*.jpg").Concat(Directory.GetFiles(_selectedFolder, "*.png")).ToList();
                LogTextBox.Text += $"已选择文件夹:{_selectedFolder},共找到 {_imageFiles.Count} 张图片。\n";
            }
        }

        private async void ProcessButton_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(_selectedFolder) || _imageFiles == null || _imageFiles.Count == 0)
            {
                MessageBox.Show("请先选择图片文件夹。");
                return;
            }

            ProgressBar.Maximum = _imageFiles.Count;
            ProgressBar.Value = 0;

            var client = CreateClient("your-access-key-id", "your-access-key-secret");

            for (int i = 0; i < _imageFiles.Count; i++)
            {
                var imageFile = _imageFiles[i];
                try
                {
                    var ocrResult = await PerformOCR(client, imageFile);
                    var newFileName = GenerateNewFileName(ocrResult);
                    RenameFile(imageFile, newFileName);
                    LogTextBox.Text += $"处理 {imageFile} 成功,新文件名:{newFileName}\n";
                }
                catch (Exception ex)
                {
                    LogTextBox.Text += $"处理 {imageFile} 失败:{ex.Message}\n";
                }
                ProgressBar.Value = i + 1;
            }

            MessageBox.Show("处理完成。");
        }

        private static Aliyun.SDK.ocr20191230.Client CreateClient(string accessKeyId, string accessKeySecret)
        {
            Config config = new Config
            {
                AccessKeyId = accessKeyId,
                AccessKeySecret = accessKeySecret
            };
            config.Endpoint = "ocr.cn-hangzhou.aliyuncs.com";
            return new Aliyun.SDK.ocr20191230.Client(config);
        }

        private async Task<string> PerformOCR(Aliyun.SDK.ocr20191230.Client client, string imageFile)
        {
            var content = File.ReadAllBytes(imageFile);
            var base64Image = Convert.ToBase64String(content);

            RecognizeGeneralRequest recognizeGeneralRequest = new RecognizeGeneralRequest
            {
                ImageBase64 = base64Image
            };
            RuntimeOptions runtime = new RuntimeOptions();
            try
            {
                var response = await client.RecognizeGeneralWithOptions(recognizeGeneralRequest, runtime);
                var result = response.Body.Data.Content;
                return result;
            }
            catch (Exception error)
            {
                Console.WriteLine(TeaException.ToJSONString(error));
                throw;
            }
        }

        private string GenerateNewFileName(string ocrResult)
        {
            // 简单处理,去除非法字符
            var validChars = new string(ocrResult.Where(c => !Path.GetInvalidFileNameChars().Contains(c)).ToArray());
            return $"{validChars}.jpg";
        }

        private void RenameFile(string oldFilePath, string newFileName)
        {
            var directory = Path.GetDirectoryName(oldFilePath);
            var newFilePath = Path.Combine(directory, newFileName);
            File.Move(oldFilePath, newFilePath);
        }
    }
}

总结

本项目借助 WPF 构建了一个直观的桌面应用程序界面,利用阿里云 OCR 服务实现了图片文字识别功能,并完成了图片批量改名操作。通过该工具,用户能够轻松地将图片文件名替换为图片中的文字信息,提高了文件管理效率。不过,在实际使用时需要注意:

  • 要在阿里云控制台创建 AccessKey 并替换代码中的 your-access-key-idyour-access-key-secret
  • 对 OCR 识别结果的处理可根据具体需求进行优化,例如去除无用字符、添加前缀后缀等。
  • 该工具仅支持 JPG 和 PNG 格式的图片,若需支持其他格式,可修改代码中的文件筛选条件。
相关推荐
小二·2 小时前
微服务架构设计与实践
微服务·架构·wpf
王莎莎-MinerU3 小时前
从 OCR 到 Context Engineering:用 MinerU 搭一个可复现文档解析评测
人工智能·深度学习·机器学习·pdf·ocr·个人开发
暖馒4 小时前
WPF-Prism学习入门步骤记录
学习·wpf
AI人工智能+4 小时前
往来港澳通行证识别系统,深度融合计算机视觉与自然语言处理,为“智慧口岸”和“数字政务”提供了强有力的技术支撑
人工智能·深度学习·ocr·往来港澳通行证识别
baivfhpwxf20234 小时前
雷赛(Leadshine)EtherCAT 数字 I/O 模块(如 EMC-E5064-8)的状态指示灯(I/O 状态)说明
c#·wpf
打小就很皮...4 小时前
基于 Python + LangChain + React 实现智能发票识别与验真系统实战
前端·react.js·langchain·ocr·发票识别
weixin_307779135 小时前
从切片迷宫到结构化智能:AI Agent解析PDF的完整范式
图像处理·人工智能·python·自动化·ocr
天天代码码天天5 小时前
用 OpenCV 5 DNN 跑 PP-OCR:一个适合新手学习的 C++ 动态库 + C# 可视化测试项目
opencv·ocr·dnn·opencv5·ppocrv6
故渊at1 天前
第二板块:Android 四大组件标准化学理 | 第十二篇:四大组件全景总结与系统服务(System Server)架构
android·架构·wpf·四大组件·system service
王莎莎-MinerU1 天前
面向大模型工作流的文档解析:从OCR到MinerU的深度技术指南
网络·ocr