背景:
有时,我们需要从现有Winform程序中得到程序中的相关图片。
但是,有些项目中,图片嵌入到资源文件中,但在资源浏览器中无法查看到相关图片,这时,就需要用类似本程序来导出所有资源图片了。
关键代码:
string ImagePath = @"images";
public Dictionary<string, object> Resources { get; private set; }
private CultureInfo _culture;
ComponentResourceManager _resourceManager;
private void btnGetAllPng_Click(object sender, EventArgs e)
{
_resourceManager = new System.ComponentModel.ComponentResourceManager(typeof(MainForm));
Resources = new Dictionary<string, object>();
_culture = CultureInfo.CurrentUICulture;
LoadAndSaveBitmapAsPng();
}
/// <summary>
/// Determines whether the specified data is zip.
/// </summary>
/// <param name="data">The data.</param>
/// <returns><c>true</c> if the specified data is zip; otherwise, <c>false</c>.</returns>
private bool IsZIP(byte[] data)
{
if (data[0] == 0x50 && data[1] == 0x4b && data[2] == 0x03 && data[3] == 0x04)
{
return true;
}
return false;
}
/// <summary>
/// Loads this instance.
/// </summary>
private void LoadAndSaveBitmapAsPng()
{
var resourceSet = _resourceManager.GetResourceSet(_culture, true, true);
int i = 0;
foreach (DictionaryEntry entry in resourceSet)
{
string resourceKey = entry.Key.ToString();
if (entry.Value is byte[] data)
{
if (IsZIP(data))
{
LoadZIP(resourceKey, data);
}
else
{
Resources.Add(resourceKey, data);
}
}
else
{
Resources.Add(resourceKey, entry.Value);
if (entry.Value is Bitmap)
{
Bitmap b = entry.Value as Bitmap;
string imgPath = Path.Combine(Application.StartupPath, this.ImagePath);
if (!Directory.Exists(imgPath))
Directory.CreateDirectory(imgPath);
b.Save(Path.Combine(Application.StartupPath, this.ImagePath+@"\" + i + ".png"), System.Drawing.Imaging.ImageFormat.Png);
i++;
}
}
}
}
/// <summary>
/// Loads the zip.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="data">The data.</param>
private void LoadZIP(string name, byte[] data)
{
try
{
using (var zipMemoryStream = new MemoryStream(data))
{
using (var zip = new ZipArchive(zipMemoryStream, ZipArchiveMode.Read))
{
foreach (var entry in zip.Entries)
{
using (var stream = entry.Open())
{
using (var ms = new MemoryStream())
{
stream.CopyTo(ms);
ms.Position = 0; // rewind
var entryData = new byte[ms.Length];
ms.Read(entryData, 0, entryData.Length);
Resources.Add(entry.Name, entryData);
}
}
}
}
}
}
catch (Exception ex)
{
//Debug.WriteLine($"Unable to load ZIP resource file: {name}");
}
}
/// <summary>
/// Gets the text value.
/// </summary>
/// <param name="name">The name.</param>
/// <returns>System.String.</returns>
public string GetTextValue(string name)
{
if (!Resources.ContainsKey(name))
{
return null;
}
if (!(Resources[name] is byte[]))
{
return null;
}
return System.Text.Encoding.UTF8.GetString((byte[])Resources[name]);
}