积极答复者
C#如何将.resx中的位图资源写到本地磁盘?求解答,求指正…

问题
-
我用ComponentResourceManager类的GetObject()取到.resx里的PNG位图资源返回的是object对象,如何把这个数据对象写到本地磁盘?用BinaryFormatter把对象序列化成流以后可以把数据写到文件,但是文件打不开,提示预览失败…不是有效的位图文件…可是大小和原图差不多啊,证明数据写进去了啊… 求解啊…我是这样写的,求指正!
private void button1_Click(object sender, EventArgs e)
{
ComponentResourceManager a = new ComponentResourceManager(typeof(Form1));
object ob = a.GetObject("人妖");
FileStream fs = new FileStream(@"d:\我的文档\桌面\1.png",FileMode.Create);
BinaryFormatter bf = new BinaryFormatter();
try
{
bf.Serialize(fs, ob);
fs.Flush();
} catch (Exception m)
{
MessageBox.Show (m.ToString());
}
fs.Close();
}
- 已编辑 菜菜菜菜菜鸟 2012年2月24日 1:21
答案
-
看来你要一个通用的保存办法,设法把获取的object转化为二进制数组即可。
Assembly asm = Assembly.GetExecutingAssembly();
string name = asm.GetName().Name;
Stream s = asm.GetManifestResourceStream(name+".Resources.Koala.jpg");
byte[] bytes = new byte[s.Length];
if (s.Length > int.MaxValue)
{
s.Write(bytes, 0, int.MaxValue);
s.Write(bytes, int.MaxValue, (int)(s.Length - int.MaxValue));
}
else
{
s.Read(bytes, 0, (int)s.Length);
}
File.WriteAllBytes("D:\\text.jpg", bytes);
s.Close();- 已建议为答案 Lie YouModerator 2012年2月24日 8:08
- 取消建议作为答案 菜菜菜菜菜鸟 2012年2月24日 20:33
- 已标记为答案 菜菜菜菜菜鸟 2012年2月25日 12:39
全部回复
-
VS是有这东西,可是Csharp develop没有啊 ....
哦,请以后把开发工具以及特殊情况说明清楚,不然就白做了,呵呵!
根据你的情况,你必须先确定你在Resources中的那个是图片文件,然后:
ResourceManager rm = new ResourceManager("WinFormCSharp.Properties.Resources", Assembly.GetExecutingAssembly());
object obj = rm.GetObject("Koala");
Image img = (Image)obj;
img.Save("d:\\test.jpg",ImageFormat.Jpeg);
QQ我:
下载MSDN桌面工具(Vista,Win7)
我的博客园
慈善点击,点击此处- 已编辑 ThankfulHeartModerator 2012年2月24日 5:17
- 已建议为答案 ThankfulHeartModerator 2012年2月24日 8:09
-
VS是有这东西,可是Csharp develop没有啊 ....
哦,请以后把开发工具以及特殊情况说明清楚,不然就白做了,呵呵!
根据你的情况,你必须先确定你在Resources中的那个是图片文件,然后:
ResourceManager rm = new ResourceManager("WinFormCSharp.Properties.Resources", Assembly.GetExecutingAssembly());
object obj = rm.GetObject("Koala");
Image img = (Image)obj;
img.Save("d:\\test.jpg",ImageFormat.Jpeg);
QQ我:
下载MSDN桌面工具(Vista,Win7)
我的博客园
慈善点击,点击此处
-
看来你要一个通用的保存办法,设法把获取的object转化为二进制数组即可。
Assembly asm = Assembly.GetExecutingAssembly();
string name = asm.GetName().Name;
Stream s = asm.GetManifestResourceStream(name+".Resources.Koala.jpg");
byte[] bytes = new byte[s.Length];
if (s.Length > int.MaxValue)
{
s.Write(bytes, 0, int.MaxValue);
s.Write(bytes, int.MaxValue, (int)(s.Length - int.MaxValue));
}
else
{
s.Read(bytes, 0, (int)s.Length);
}
File.WriteAllBytes("D:\\text.jpg", bytes);
s.Close();- 已建议为答案 Lie YouModerator 2012年2月24日 8:08
- 取消建议作为答案 菜菜菜菜菜鸟 2012年2月24日 20:33
- 已标记为答案 菜菜菜菜菜鸟 2012年2月25日 12:39