在快速发展的电商行业中,商品上架是一项繁琐且关键的工作。某电商店铺每天都要上架大量新商品,每个商品都配有多张展示图片,这些图片往往是从不同渠道收集而来,原始文件名毫无规律,如 “IMG_001.jpg”“product_pic2.png” 等。在上架商品时,运营人员需要逐一查看图片内容,确认商品款式、颜色、尺码等信息,然后手动将图片重命名为有意义的格式,例如 “商品名称_颜色_尺码_展示角度.jpg”,以便后续在商品详情页精准调用。这个过程耗时费力,一旦图片数量众多,还容易出现信息匹配错误。运用 OCR 指定区域图片自动识别内容重命名技术后,情况大为改观。运营人员预先设定好图片中包含商品名称、规格参数等信息的区域,OCR 系统自动识别这些区域文字,按照设定规则批量重命名图片。这一技术极大地提高了商品上架效率,降低出错率,让电商店铺运营更加高效有序,助力业务快速发展。
以下是使用 WPF 和腾讯 OCR 实现指定区域图片自动识别内容重命名的详细步骤和完整代码:
打开 Visual Studio,选择 “创建新项目”,选择 “WPF 应用程序” 模板,命名项目并创建。
在 Visual Studio 的 “工具” -> “NuGet 包管理器” -> “管理解决方案的 NuGet 程序包” 中,搜索并安装TencentCloudSDK_dotnet
。
MainWindow.xaml
)<Window x:Class="OCRImageRename.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="OCR图片重命名" Height="450" Width="800">
<Grid>
<Button Content="选择图片文件夹" HorizontalAlignment="Left" Margin="20,20,0,0" VerticalAlignment="Top" Width="150" Click="SelectFolderButton_Click"/>
<TextBox x:Name="FolderPathTextBox" HorizontalAlignment="Left" Height="23" Margin="180,20,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="500" IsReadOnly="True"/>
<Label Content="识别区域(格式:X,Y,Width,Height 多个区域用分号分隔)" HorizontalAlignment="Left" Margin="20,60,0,0" VerticalAlignment="Top"/>
<TextBox x:Name="RegionsTextBox" HorizontalAlignment="Left" Height="23" Margin="20,80,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="740"/>
<Button Content="开始识别重命名" HorizontalAlignment="Left" Margin="20,120,0,0" VerticalAlignment="Top" Width="150" Click="StartRenameButton_Click"/>
<TextBlock x:Name="StatusTextBlock" HorizontalAlignment="Left" Margin="20,160,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="740"/>
</Grid>
</Window>
MainWindow.xaml.cs
)using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows;
using Microsoft.Win32;
using TencentCloud.Common;
using TencentCloud.Common.Profile;
using TencentCloud.Ocr.V20181119;
using TencentCloud.Ocr.V20181119.Models;
namespace OCRImageRename
{
public partial class MainWindow : Window
{
private string _selectedFolder;
public MainWindow()
{
InitializeComponent();
}
private void SelectFolderButton_Click(object sender, RoutedEventArgs e)
{
var dialog = new OpenFileDialog();
dialog.Multiselect = false;
dialog.CheckFileExists = false;
dialog.CheckPathExists = true;
dialog.FileName = "文件夹选择";
dialog.Filter = "所有文件 (*.*)|*.*";
dialog.ValidateNames = false;
if (dialog.ShowDialog() == true)
{
_selectedFolder = Path.GetDirectoryName(dialog.FileName);
FolderPathTextBox.Text = _selectedFolder;
}
}
private void StartRenameButton_Click(object sender, RoutedEventArgs e)
{
if (string.IsNullOrEmpty(_selectedFolder))
{
MessageBox.Show("请先选择图片文件夹");
return;
}
var regions = ParseRegions(RegionsTextBox.Text);
if (regions == null || regions.Count == 0)
{
MessageBox.Show("请输入有效的识别区域");
return;
}
try
{
var imageFiles = Directory.GetFiles(_selectedFolder, "*.jpg;*.png;*.jpeg", SearchOption.TopDirectoryOnly);
foreach (var imageFile in imageFiles)
{
var ocrResult = PerformOCR(imageFile, regions);
var newFileName = string.Join("", ocrResult);
if (!string.IsNullOrEmpty(newFileName))
{
var newFilePath = Path.Combine(_selectedFolder, newFileName + Path.GetExtension(imageFile));
File.Move(imageFile, newFilePath);
StatusTextBlock.Text += $"已将 {Path.GetFileName(imageFile)} 重命名为 {Path.GetFileName(newFilePath)}\n";
}
}
MessageBox.Show("重命名完成");
}
catch (Exception ex)
{
MessageBox.Show($"发生错误:{ex.Message}");
}
}
private List<(int X, int Y, int Width, int Height)> ParseRegions(string input)
{
var regions = new List<(int X, int Y, int Width, int Height)>();
var regionStrings = input.Split(';', StringSplitOptions.RemoveEmptyEntries);
foreach (var regionString in regionStrings)
{
var parts = regionString.Split(',');
if (parts.Length == 4 && int.TryParse(parts[0], out int x) && int.TryParse(parts[1], out int y) && int.TryParse(parts[2], out int width) && int.TryParse(parts[3], out int height))
{
regions.Add((x, y, width, height));
}
}
return regions;
}
private List<string> PerformOCR(string imageFile, List<(int X, int Y, int Width, int Height)> regions)
{
var result = new List<string>();
var cred = new Credential
{
SecretId = "your_secret_id",
SecretKey = "your_secret_key"
};
var clientProfile = new ClientProfile();
var httpProfile = new HttpProfile();
httpProfile.Endpoint = "ocr.tencentcloudapi.com";
clientProfile.HttpProfile = httpProfile;
var client = new OcrClient(cred, "ap-guangzhou", clientProfile);
var imageBytes = File.ReadAllBytes(imageFile);
var base64Image = Convert.ToBase64String(imageBytes);
foreach (var region in regions)
{
var req = new GeneralBasicOCRRequest();
req.ImageBase64 = base64Image;
req.RegionCoordPoint = new Coord[]
{
new Coord { X = region.X, Y = region.Y },
new Coord { X = region.X + region.Width, Y = region.Y },
new Coord { X = region.X + region.Width, Y = region.Y + region.Height },
new Coord { X = region.X, Y = region.Y + region.Height }
};
var resp = client.GeneralBasicOCRSync(req);
result.AddRange(resp.TextDetections.Select(d => d.DetectedText));
}
return result;
}
}
}
MainWindow.xaml
中创建了一个简单的界面,包含选择图片文件夹、输入识别区域、开始识别重命名等功能。SelectFolderButton_Click
方法用于选择图片文件夹,并将文件夹路径显示在文本框中。StartRenameButton_Click
方法用于开始识别和重命名操作,首先检查是否选择了文件夹和输入了有效的识别区域,然后遍历文件夹中的所有图片文件,调用PerformOCR
方法进行 OCR 识别,并根据识别结果对图片文件进行重命名。ParseRegions
方法用于解析用户输入的识别区域,将其转换为(int X, int Y, int Width, int Height)
类型的列表。PerformOCR
方法用于调用腾讯云 OCR 服务进行指定区域的识别,将图片文件转换为 Base64 编码的字符串,并设置识别区域,最后返回识别结果。your_secret_id
和your_secret_key
替换为你自己的腾讯云 API 密钥和 Secret Key。X,Y,Width,Height
,多个区域用分号分隔。通过以上步骤和代码,你可以实现使用 WPF 和腾讯 OCR 对指定区域图片进行自动识别内容重命名的功能。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。