This commit is contained in:
陈皓 2018-10-04 16:55:25 +08:00
parent 04a80e44e1
commit 3f5b853a9d
18 changed files with 1112 additions and 0 deletions

63
.gitattributes vendored Normal file
View File

@ -0,0 +1,63 @@
###############################################################################
# Set default behavior to automatically normalize line endings.
###############################################################################
* text=auto
###############################################################################
# Set default behavior for command prompt diff.
#
# This is need for earlier builds of msysgit that does not have it on by
# default for csharp files.
# Note: This is only used by command line
###############################################################################
#*.cs diff=csharp
###############################################################################
# Set the merge driver for project and solution files
#
# Merging from the command prompt will add diff markers to the files if there
# are conflicts (Merging from VS is not affected by the settings below, in VS
# the diff markers are never inserted). Diff markers may cause the following
# file extensions to fail to load in VS. An alternative would be to treat
# these files as binary and thus will always conflict and require user
# intervention with every merge. To do so, just uncomment the entries below
###############################################################################
#*.sln merge=binary
#*.csproj merge=binary
#*.vbproj merge=binary
#*.vcxproj merge=binary
#*.vcproj merge=binary
#*.dbproj merge=binary
#*.fsproj merge=binary
#*.lsproj merge=binary
#*.wixproj merge=binary
#*.modelproj merge=binary
#*.sqlproj merge=binary
#*.wwaproj merge=binary
###############################################################################
# behavior for image files
#
# image files are treated as binary by default.
###############################################################################
#*.jpg binary
#*.png binary
#*.gif binary
###############################################################################
# diff behavior for common document formats
#
# Convert binary document formats to text before diffing them. This feature
# is only available from the command line. Turn it on by uncommenting the
# entries below.
###############################################################################
#*.doc diff=astextplain
#*.DOC diff=astextplain
#*.docx diff=astextplain
#*.DOCX diff=astextplain
#*.dot diff=astextplain
#*.DOT diff=astextplain
#*.pdf diff=astextplain
#*.PDF diff=astextplain
#*.rtf diff=astextplain
#*.RTF diff=astextplain

Binary file not shown.

View File

@ -0,0 +1,25 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.27703.2026
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HaoYue.Image2Thumbnail", "HaoYue.Image2Thumbnail\HaoYue.Image2Thumbnail.csproj", "{2E03FC1D-AF90-4124-BFA0-29065513169B}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{2E03FC1D-AF90-4124-BFA0-29065513169B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{2E03FC1D-AF90-4124-BFA0-29065513169B}.Debug|Any CPU.Build.0 = Debug|Any CPU
{2E03FC1D-AF90-4124-BFA0-29065513169B}.Release|Any CPU.ActiveCfg = Release|Any CPU
{2E03FC1D-AF90-4124-BFA0-29065513169B}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {B70DB4FC-AC1A-4966-B361-5332ACF56311}
EndGlobalSection
EndGlobal

View File

@ -0,0 +1,17 @@
<Application x:Class="HaoYue.Image2Thumbnail.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:HaoYue.Image2Thumbnail"
StartupUri="MainWindow.xaml">
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Controls.xaml" />
<ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Fonts.xaml" />
<ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Colors.xaml" />
<ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Accents/Blue.xaml" />
<ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Accents/BaseLight.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
</Application>

View File

@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Windows;
namespace HaoYue.Image2Thumbnail
{
/// <summary>
/// App.xaml 的交互逻辑
/// </summary>
public partial class App : Application
{
}
}

View File

@ -0,0 +1,107 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{2E03FC1D-AF90-4124-BFA0-29065513169B}</ProjectGuid>
<OutputType>WinExe</OutputType>
<RootNamespace>HaoYue.Image2Thumbnail</RootNamespace>
<AssemblyName>HaoYue.Image2Thumbnail</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<ProjectTypeGuids>{60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup>
<ApplicationIcon>
</ApplicationIcon>
</PropertyGroup>
<ItemGroup>
<Reference Include="ControlzEx, Version=3.0.2.4, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\packages\ControlzEx.3.0.2.4\lib\net40\ControlzEx.dll</HintPath>
</Reference>
<Reference Include="MahApps.Metro, Version=1.6.5.1, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\packages\MahApps.Metro.1.6.5\lib\net40\MahApps.Metro.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Data" />
<Reference Include="System.Drawing" />
<Reference Include="System.Windows.Interactivity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\packages\ControlzEx.3.0.2.4\lib\net40\System.Windows.Interactivity.dll</HintPath>
</Reference>
<Reference Include="System.Xml" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="System.Xaml">
<RequiredTargetFramework>4.0</RequiredTargetFramework>
</Reference>
<Reference Include="WindowsBase" />
<Reference Include="PresentationCore" />
<Reference Include="PresentationFramework" />
</ItemGroup>
<ItemGroup>
<ApplicationDefinition Include="App.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</ApplicationDefinition>
<Page Include="MainWindow.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
<Compile Include="App.xaml.cs">
<DependentUpon>App.xaml</DependentUpon>
<SubType>Code</SubType>
</Compile>
<Compile Include="MainWindow.xaml.cs">
<DependentUpon>MainWindow.xaml</DependentUpon>
<SubType>Code</SubType>
</Compile>
</ItemGroup>
<ItemGroup>
<Compile Include="Properties\AssemblyInfo.cs">
<SubType>Code</SubType>
</Compile>
<Compile Include="Properties\Resources.Designer.cs">
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
<Compile Include="Properties\Settings.Designer.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Settings.settings</DependentUpon>
<DesignTimeSharedInput>True</DesignTimeSharedInput>
</Compile>
<EmbeddedResource Include="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
</EmbeddedResource>
<None Include="packages.config" />
<None Include="Properties\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<LastGenOutput>Settings.Designer.cs</LastGenOutput>
</None>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>

View File

@ -0,0 +1,65 @@
<controls:MetroWindow x:Class="HaoYue.Image2Thumbnail.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:HaoYue.Image2Thumbnail"
xmlns:controls="clr-namespace:MahApps.Metro.Controls;assembly=MahApps.Metro"
mc:Ignorable="d"
Title="批量缩略图(压缩)工具 HaoYue.ImageTools Ver.1.0 (试用)" Height="395.065" Width="526.649" AllowDrop="True">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="43*"/>
<RowDefinition Height="139*"/>
</Grid.RowDefinitions>
<CheckBox x:Name="CheckBox_MaxMinWH" Checked="MaxMinWH_Checked" Unchecked="MaxMinWH_unChecked" Content="限制缩略图最大宽高:" HorizontalAlignment="Left" Margin="262,10,0,0" VerticalAlignment="Top" />
<TextBox x:Name="Text_MaxW" PreviewTextInput="tb_PreviewTextInput" InputMethod.IsInputMethodEnabled="False" HorizontalAlignment="Left" Height="18" Margin="413,10,0,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="39" IsEnabled="False" FontSize="10"/>
<TextBox x:Name="Text_MaxH" PreviewTextInput="tb_PreviewTextInput" InputMethod.IsInputMethodEnabled="False" HorizontalAlignment="Left" Height="23" Margin="465,10,0,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="39" IsEnabled="False" FontSize="10"/>
<Label Content="图片分辨率缩小倍率:" HorizontalAlignment="Left" Margin="10,7,0,0" VerticalAlignment="Top"/>
<Label Content="{Binding ElementName=Slider_ReductionRatio,Path=Value}" HorizontalAlignment="Left" Margin="234,10,0,0" VerticalAlignment="Top"/>
<Slider Name="Slider_ReductionRatio" Value="6" Ticks="2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20" IsSnapToTickEnabled="True" HorizontalAlignment="Left" Margin="140,12,0,0" VerticalAlignment="Top" Width="89" Minimum="2" Maximum="20"/>
<Label Content="处理方式:" HorizontalAlignment="Left" Margin="295,39,0,0" VerticalAlignment="Top"/>
<TextBox HorizontalAlignment="Left" IsEnabled="False" Height="23" Margin="128,33,0,0" TextWrapping="Wrap" Text="&lt;原文件名&gt;_small.&lt;扩展名&gt;" VerticalAlignment="Top" Width="375" Grid.Row="1"/>
<Label Content="输出图片命名规则:" HorizontalAlignment="Left" Margin="10,34,0,0" VerticalAlignment="Top" Grid.Row="1"/>
<Grid HorizontalAlignment="Left" Background="#87CEFA" Height="139" Margin="9,67,0,0" VerticalAlignment="Top" Width="495"
Grid.Row="1"
Drop="FileDrop"
/>
<Label x:Name="label1" Content="请拖入要处理的图片或文件夹到这里" HorizontalAlignment="Left" Margin="29,118,0,0" VerticalAlignment="Top" FontSize="27"
Grid.Row="1"
Drop="FileDrop"
/>
<ProgressBar x:Name="myp" HorizontalAlignment="Left" Margin="111,215,0,0" VerticalAlignment="Top" Width="392" Height="14" Grid.Row="1"/>
<Label Content="处理进度:" HorizontalAlignment="Left" Margin="107,245,0,0" VerticalAlignment="Top" Grid.Row="1"/>
<Label x:Name="myPercentage" Content=" - %" HorizontalAlignment="Left" Margin="165,245,0,0" VerticalAlignment="Top" Grid.Row="1"/>
<Label Content="文件数量:" HorizontalAlignment="Left" Margin="201,245,0,0" VerticalAlignment="Top" Grid.Row="1"/>
<Label x:Name="myFilePercentage" Content=" - / - " HorizontalAlignment="Left" Margin="271,245,0,0" VerticalAlignment="Top" Grid.Row="1"/>
<Button x:Name="button_About" Click="adout" Content="说明" HorizontalAlignment="Left" Margin="9,214.623,0,0" VerticalAlignment="Top" Width="88" FontSize="20" Height="51" Grid.Row="1"/>
<Slider x:Name="Slider_ThreadCount" IsEnabled="False" HorizontalAlignment="Left" Margin="140,42,0,0" VerticalAlignment="Top" Width="89" Minimum="1" Maximum="10"/>
<Label Content="处理线程数量:" HorizontalAlignment="Left" Margin="10,39,0,0" VerticalAlignment="Top"/>
<Label Content="{Binding ElementName=Slider_ThreadCount,Path=Value}" HorizontalAlignment="Left" Margin="234,39,0,0" VerticalAlignment="Top"/>
<TextBox HorizontalAlignment="Left" Height="23" Margin="250,69,0,0" TextWrapping="Wrap" Text="D:/" VerticalAlignment="Top" Width="226" IsEnabled="False" Grid.RowSpan="2"/>
<Label Content="处理信息:" HorizontalAlignment="Left" Margin="107,227,0,0" Grid.Row="1" VerticalAlignment="Top"/>
<Label Name="Lable_SetFileInfo" Content="-" HorizontalAlignment="Left" Margin="165,227,0,0" Grid.Row="1" VerticalAlignment="Top" FontSize="9"/>
<RadioButton Content="指定输出目录" IsEnabled="False" HorizontalAlignment="Left" Margin="148,71,0,0" VerticalAlignment="Top" Grid.RowSpan="2"/>
<RadioButton Content="在原图同目录输出" HorizontalAlignment="Left" Margin="13,71,0,0" VerticalAlignment="Top" IsChecked="True" RenderTransformOrigin="0.867,1" Grid.RowSpan="2"/>
<Button Content="..." HorizontalAlignment="Left" Margin="481,70,0,0" VerticalAlignment="Top" Width="26" Height="24" IsEnabled="False" Grid.RowSpan="2"/>
<Label x:Name="label" Content="Powered by axibug.com - 皓月" HorizontalAlignment="Left" Margin="324,256,0,-3" VerticalAlignment="Top" Grid.Row="1"/>
<CheckBox x:Name="CheckBox_IsDeleteSrcFile" IsEnabled ="False" Content="删除原图文件" HorizontalAlignment="Left" Margin="13,11,0,0" Grid.Row="1" VerticalAlignment="Top"/>
<ComboBox x:Name="ComboBox_OutImagequality" HorizontalAlignment="Left" Margin="370,40,0,0" VerticalAlignment="Top" Width="139" Height="22">
<ComboBoxItem IsSelected="True">默认质量</ComboBoxItem>
<ComboBoxItem>高质量,低速度</ComboBoxItem>
<ComboBoxItem>低质量,高速度</ComboBoxItem>
<ComboBoxItem >假定线性值</ComboBoxItem>
<ComboBoxItem>灰度修正</ComboBoxItem>
</ComboBox>
</Grid>
</controls:MetroWindow >

View File

@ -0,0 +1,534 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
//引用
using MahApps.Metro.Controls;
using MahApps.Metro.Controls.Dialogs;
using System.IO;
using System.Security.Cryptography;
using System.Threading;
using System.Threading.Tasks;
namespace HaoYue.Image2Thumbnail
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : MetroWindow
{
public int FileALLCount = 0;
public int FinishedFileCount = 0;
//图片压缩比率
public double ReductionRatio = 0;
//图片压缩质量
public int OutImagequality = 0;
public int ThreadCount = 0;
public bool IsSetMaxWH = false;
public int MaxW = 0;
public int MaxH = 0;
public bool IsDeleteSrcFile = false;
public DateTime StartDT;
public MainWindow()
{
InitializeComponent();
}
private void MaxMinWH_Checked(object sender, RoutedEventArgs e)
{
Text_MaxW.IsEnabled = true;
Text_MaxH.IsEnabled = true;
Text_MaxH.Text = "480";
Text_MaxW.Text = "640";
}
private void MaxMinWH_unChecked(object sender, RoutedEventArgs e)
{
Text_MaxW.IsEnabled = false;
Text_MaxH.IsEnabled = false;
}
private void adout(object sender, RoutedEventArgs e)
{
this.ShowMessageAsync("批量缩略图(压缩)处理工具 XueyiImageTools Ver 1.0.0", "设置好您需要的设置(不设置默认也行)之后、\n拖入您需要处理的图片或者包含图片的文件夹即可", MessageDialogStyle.Affirmative, new MetroDialogSettings() { AffirmativeButtonText = "确定" });
}
//文件拖拽
private void FileDrop(object sender, DragEventArgs e)
{
ReductionRatio = this.Slider_ReductionRatio.Value;
switch (ComboBox_OutImagequality.Text)
{
case "默认质量":
OutImagequality = 0;
break;
case "低质量,高速度":
OutImagequality = 1;
break;
case "高质量,低速度":
OutImagequality = 2;
break;
case "灰度修正":
OutImagequality = 3;
break;
case "假定线性值":
OutImagequality = 4;
break;
}
ThreadCount = (int)this.Slider_ThreadCount.Value;
IsSetMaxWH = (bool)this.CheckBox_MaxMinWH.IsChecked;
if (IsSetMaxWH)
{
try
{
MaxH = Convert.ToInt32(this.Text_MaxH.Text);
MaxW = Convert.ToInt32(this.Text_MaxW.Text);
}
catch
{
new Thread(() =>
{
this.Dispatcher.Invoke(new Action(() =>
{
this.ShowMessageAsync("错误!", "使用尺寸限制、请正确填写尺寸大小限制".ToString(), MessageDialogStyle.Affirmative, new MetroDialogSettings() { AffirmativeButtonText = "确定" });
}));
}).Start();
return;
}
}
IsDeleteSrcFile = (bool)this.CheckBox_IsDeleteSrcFile.IsChecked;
Thread t = new Thread(delegate ()
{
SetAsyncFile(e);
});
t.Start();
}
private void SetAsyncFile(DragEventArgs e)
{
StartDT = DateTime.Now;
//统计文件数量先
FileALLCount = 0;
FinishedFileCount = 0;
for (int i = 0; i < ((System.Array)e.Data.GetData(DataFormats.FileDrop)).Length; i++)
{
string fileName = ((System.Array)e.Data.GetData(DataFormats.FileDrop)).GetValue(i).ToString();
//然后你要做的事情
if (Directory.Exists(fileName))//是文件夹的情况
{
FileALLCount += GetDirWithDirGetNumber(fileName);
}
else if (File.Exists(fileName))//是文件的情况
{
switch (fileName.Substring(fileName.LastIndexOf(".") + 1).ToLower())
{
case "jpeg":
case "jpg":
case "png":
case "bmp":
case "gif":
case "wmf":
FileALLCount++;
break;
default:
continue;
break;
}
}
}
SetmyFilePercentage();
//处理
int index = 0;
for (int i = 0; i < ((System.Array)e.Data.GetData(DataFormats.FileDrop)).Length; i++)
{
string fileName = ((System.Array)e.Data.GetData(DataFormats.FileDrop)).GetValue(i).ToString();
//然后你要做的事情
if (Directory.Exists(fileName))//是文件夹的情况
{
GetDirWithDir(fileName);
}
else if (File.Exists(fileName))//是文件的情况
{
//单个文件处理
OneImageSet(fileName);
}
index++;
if (index % 20 == 0)
{
GC.Collect();
}
}
new Thread(() =>
{
this.Dispatcher.Invoke(new Action(() =>
{
this.ShowMessageAsync("处理完毕!", "共处理" + FinishedFileCount + "个文件 耗时:" + (DateTime.Now - StartDT).ToString(), MessageDialogStyle.Affirmative, new MetroDialogSettings() { AffirmativeButtonText = "确定" });
}));
}).Start();
}
/// <summary>
/// 遍历文件夹下的文件总数
/// </summary>
/// <param name="diruriFullName"></param>
/// <returns></returns>
public int GetDirWithDirGetNumber(string diruriFullName)
{
int filecount = 0;
DirectoryInfo dir = new DirectoryInfo(diruriFullName);
var Directories = dir.GetDirectories();
//当前目录下的目录
foreach (var d in Directories)
{
filecount += GetDirWithDirGetNumber(d.FullName);
}
Directories = null;
//当前目录下的文件
DirectoryInfo dirinfo = new DirectoryInfo(diruriFullName);
int count = 0;
foreach (var f in dir.GetFiles())
{
switch (f.FullName.Substring(f.FullName.LastIndexOf(".") + 1).ToLower())
{
case "jpeg":
case "jpg":
case "png":
case "bmp":
case "gif":
case "wmf":
count++;
break;
default:
break;
}
}
filecount += count;
return filecount;
}
public void SetFileInfo(string FileInfo)
{
new Thread(
delegate ()
{
this.Dispatcher.Invoke(new Action(() =>
Lable_SetFileInfo.Content = FileInfo
));
}
).Start();
}
/// <summary>
/// 更新文件处理数量和总数量
/// </summary>
/// <param name="FileInfo"></param>
public void SetmyFilePercentage()
{
new Thread(
delegate ()
{
this.Dispatcher.Invoke(new Action(() =>
myFilePercentage.Content = FinishedFileCount + " / " + FileALLCount
));
this.Dispatcher.Invoke(new Action(() =>
myp.Value = ((double)FinishedFileCount / (double)FileALLCount * 100)
));
this.Dispatcher.Invoke(new Action(() =>
myPercentage.Content = (int)myp.Value + "%"
));
}
).Start();
}
public class tImageReturn
{
public int smallWidth { get; set; }
public int smallHeight { get; set; }
public string smallImagePath { get; set; }
}
public void GetDirWithDir(string diruriFullName)
{
DirectoryInfo dir = new DirectoryInfo(diruriFullName);
var Directories = dir.GetDirectories();
//当前目录下的目录
foreach (var d in Directories)
{
GetDirWithDir(d.FullName);
GC.Collect();
}
Directories = null;
//当前目录下的文件
SetDirALLSmallImageToFile(diruriFullName);
}
public void SetDirALLSmallImageToFile(string diruriFullName)
{
DirectoryInfo dir = new DirectoryInfo(diruriFullName);
var files = dir.GetFiles();
int index = 0;
foreach (var f in files)
{
if(OneImageSet(f.FullName))
index++;
if (index % 20 == 0)
{
GC.Collect();
}
}
files = null;
}
public bool OneImageSet(string FileFullName)
{
SetFileInfo(FileFullName);
//if (File.Exists(
// f.FullName.Substring(0, f.FullName.LastIndexOf(".")) + "_s0" + f.FullName.Substring(f.FullName.LastIndexOf("."))
// ))
//{
// //continue;
// return false;
//}
//if (f.Name.Contains("_s0" + f.Name.Substring(f.Name.LastIndexOf("."))))
//{
// //continue;
// return false;
//}
switch (FileFullName.Substring(FileFullName.LastIndexOf(".") + 1).ToLower())
{
case "jpeg":
case "jpg":
case "png":
case "bmp":
case "gif":
case "wmf":
break;
default:
//continue;
return false;
break;
}
System.Drawing.Image img = System.Drawing.Image.FromFile(FileFullName);
var height = img.Height;
var Width = img.Width;
tImageReturn tp;
//if (height < 600 || Width < 600)
// tp = tImage(FileFullName, Width / 2, height / 2);//制作缩略图
//else
// tp = tImage(FileFullName, Width / 6, height / 6);//制作缩略图
int smallW = Width / (int)ReductionRatio;
int smallH = height / (int)ReductionRatio;
if (IsSetMaxWH)
{
if (smallW > MaxW || smallH > MaxH)
{
//获取第一张绘制图的大小,(比较 原图的宽/缩略图的宽 和 原图的高/缩略图的高)
if (((decimal)MaxW) / smallW >= ((decimal)MaxH) / smallH)
{
smallH = MaxH;
smallW = (int)((Width * MaxH) / height);
}
else
{
smallW = MaxW;
smallH = (int)((MaxW * height) / Width);
}
}
}
tp = tImage(FileFullName,smallW,smallH);//制作缩略图
FinishedFileCount++;
SetmyFilePercentage();
return true;
}
/// <summary>
/// 根据路径生成缩略图片
/// </summary>
/// <param name="filePath">源图片的完整路径</param>
/// <param name="_width">缩略图的宽</param>
/// <param name="_height">高</param>
/// <returns></returns>
public tImageReturn tImage(string filePath, int _width, int _height)
{
try
{
using (System.Drawing.Image sourceImage = System.Drawing.Image.FromFile(filePath))
{
//原图宽度和高度
int width = sourceImage.Width;
int height = sourceImage.Height;
int smallWidth = _width;
int smallHeight = _height;
////获取第一张绘制图的大小,(比较 原图的宽/缩略图的宽 和 原图的高/缩略图的高)
//if (((decimal)width) / _width >= ((decimal)height) / _height)
//{
// smallWidth = _width;
// smallHeight = (int)((double)height / ((double)width / (double)_width));
//}
//else
//{
// smallWidth = (int)((double)width / ((double)height / (double)_height));
// smallHeight = _height;
//}
//判断缩略图在当前文件夹下是否同名称文件存在
//缩略图保存的绝对路径
string smallImagePath = ExistsOrCreateFile(filePath);
// string smallImagePath = HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["PhotoPath"]);
//新建一个图板,以最小等比例压缩大小绘制原图
using (System.Drawing.Image bitmap = new System.Drawing.Bitmap(smallWidth, smallHeight))
{
using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap))
{
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
g.CompositingQuality = (System.Drawing.Drawing2D.CompositingQuality)OutImagequality;
g.Clear(System.Drawing.Color.Black);
g.DrawImage(
sourceImage,
new System.Drawing.Rectangle(-2, -2, smallWidth + 2, smallHeight + 2),
new System.Drawing.Rectangle(0, 0, width, height),
System.Drawing.GraphicsUnit.Pixel
);
g.Dispose();
bitmap.Save(smallImagePath, System.Drawing.Imaging.ImageFormat.Jpeg);
}
}
tImageReturn tir = new tImageReturn();
tir.smallHeight = smallHeight;
tir.smallWidth = smallWidth;
tir.smallImagePath = System.IO.Path.GetFileName(smallImagePath);
return tir;
}
}
catch
{
return null;
}
}
/// <summary>
/// 判断制定路径下是否存在新文件
/// </summary>
/// <param name="fullPath">源文件的完整路径</param>
/// <returns>新文件的完整路径</returns>
private string ExistsOrCreateFile(string fullPath)
{
int num = 0;
string fileName = System.IO.Path.GetFileNameWithoutExtension(fullPath);
string extendName = System.IO.Path.GetExtension(fullPath);
string path = System.IO.Path.GetDirectoryName(fullPath);
StringBuilder newPath = new StringBuilder();
while (true)
{
newPath.Length = 0;
newPath.Append(path + "\\");
//string[] sArray = fileName.Split('.');
//newPath.Append(sArray[0]);
newPath.Append(fileName);
newPath.Append("_small" + num);
//newPath.Append(sArray[1]);
newPath.Append(extendName);
if (!System.IO.File.Exists(newPath.ToString()))
break;
num++;
}
return newPath.ToString();
}
private void tb_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
System.Text.RegularExpressions.Regex re = new System.Text.RegularExpressions.Regex("[^0-9]");
e.Handled = re.IsMatch(e.Text);
}
//public void SetFileInfoLabel(string FileInfo)
//{
// new Thread()
// { }.Start();
//}
}
}

View File

@ -0,0 +1,55 @@
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
// 有关程序集的一般信息由以下
// 控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("HaoYue.Image2Thumbnail")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("HaoYue.Image2Thumbnail")]
[assembly: AssemblyCopyright("Copyright © 2018")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 会使此程序集中的类型
//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型
//请将此类型的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
//若要开始生成可本地化的应用程序,请设置
//.csproj 文件中的 <UICulture>CultureYouAreCodingWith</UICulture>
//例如,如果您在源文件中使用的是美国英语,
//使用的是美国英语,请将 <UICulture> 设置为 en-US。 然后取消
//对以下 NeutralResourceLanguage 特性的注释。 更新
//以下行中的“en-US”以匹配项目文件中的 UICulture 设置。
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //主题特定资源词典所处位置
//(未在页面中找到资源时使用,
//或应用程序资源字典中找到时使用)
ResourceDictionaryLocation.SourceAssembly //常规资源词典所处位置
//(未在页面中找到资源时使用,
//、应用程序或任何主题专用资源字典中找到时使用)
)]
// 程序集的版本信息由下列四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
// 可以指定所有值,也可以使用以下所示的 "*" 预置版本号和修订号
// 方法是按如下所示使用“*”: :
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

View File

@ -0,0 +1,71 @@
//------------------------------------------------------------------------------
// <auto-generated>
// 此代码由工具生成。
// 运行时版本: 4.0.30319.42000
//
// 对此文件的更改可能导致不正确的行为,如果
// 重新生成代码,则所做更改将丢失。
// </auto-generated>
//------------------------------------------------------------------------------
namespace HaoYue.Image2Thumbnail.Properties
{
/// <summary>
/// 强类型资源类,用于查找本地化字符串等。
/// </summary>
// 此类是由 StronglyTypedResourceBuilder
// 类通过类似于 ResGen 或 Visual Studio 的工具自动生成的。
// 若要添加或删除成员,请编辑 .ResX 文件,然后重新运行 ResGen
// (以 /str 作为命令选项),或重新生成 VS 项目。
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources
{
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources()
{
}
/// <summary>
/// 返回此类使用的缓存 ResourceManager 实例。
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager
{
get
{
if ((resourceMan == null))
{
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("HaoYue.Image2Thumbnail.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// 覆盖当前线程的 CurrentUICulture 属性
/// 使用此强类型的资源类的资源查找。
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture
{
get
{
return resourceCulture;
}
set
{
resourceCulture = value;
}
}
}
}

View File

@ -0,0 +1,117 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@ -0,0 +1,30 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace HaoYue.Image2Thumbnail.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
{
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default
{
get
{
return defaultInstance;
}
}
}
}

View File

@ -0,0 +1,7 @@
<?xml version='1.0' encoding='utf-8'?>
<SettingsFile xmlns="uri:settings" CurrentProfile="(Default)">
<Profiles>
<Profile Name="(Default)" />
</Profiles>
<Settings />
</SettingsFile>

View File

@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="ControlzEx" version="3.0.2.4" targetFramework="net40" />
<package id="MahApps.Metro" version="1.6.5" targetFramework="net40" />
</packages>