C# 从资源文件访问图像对象
在我的项目中,我需要(从磁盘)检索一个自定义图像文件。如果提供的路径中不存在图像文件,则应用程序将使用默认图像(嵌入式资源)。一旦我有了图像,我需要调整它的大小,以便在我的应用程序中进一步使用 如果我尝试只访问嵌入式资源(代码第1节),那么一切都会按预期进行。如果试图在图像上设置条件(代码第2节),则对象返回时会出现对象上的各种异常,尤其是出于我的目的:C# 从资源文件访问图像对象,c#,image,bitmap,resx,C#,Image,Bitmap,Resx,在我的项目中,我需要(从磁盘)检索一个自定义图像文件。如果提供的路径中不存在图像文件,则应用程序将使用默认图像(嵌入式资源)。一旦我有了图像,我需要调整它的大小,以便在我的应用程序中进一步使用 如果我尝试只访问嵌入式资源(代码第1节),那么一切都会按预期进行。如果试图在图像上设置条件(代码第2节),则对象返回时会出现对象上的各种异常,尤其是出于我的目的: ((System.Drawing.Image)(ReportLogoToUse)).Height' threw an exception of
((System.Drawing.Image)(ReportLogoToUse)).Height' threw an exception of type 'System.ArgumentException' int {System.ArgumentException}
((System.Drawing.Image)(ReportLogoToUse)).Width' threw an exception of type 'System.ArgumentException' int {System.ArgumentException}
这是我的密码
// Code Section 1
using (var myImage = Resources.sie_logo_petrol_rgb){
// resize the image to max allowed dimensions (64 x 233)
var resizedImage = Helpers.ResizeImage(myImage, (int)maxWidth, (int)maxHeight); // this code executes with no errors
pictureBox1.Image = resizedImage;
}
// Code Section 2
using (var ReportLogoToUse = Helpers.ReportLogo(filePath)){
// resize the image to max allowed dimensions (64 x 233)
var resizedImage = Helpers.ResizeImage(ReportLogoToUse, (int)maxWidth, (int)maxHeight); // Invalid Parameter error
pictureBox2.Image = resizedImage;
}
public static Bitmap ReportLogo(string filePath){
try{
var myImage = Image.FromFile(filePath, true);
return (Bitmap)myImage;
}
catch (Exception ex){
// use the embedded logo
using (var myResourceImage = Resources.sie_logo_petrol_rgb){
var myImage = myResourceImage;
return (Bitmap)myImage;
}
}
}
代码部分1和代码部分2中的对象之间有什么区别?它们不是返回相同类型的对象吗?通过使用
catch…
部分中的…块删除,然后只返回文件本身,它现在似乎正在运行
public static Bitmap ReportLogo(string filePath){
try{
return (Bitmap)Image.FromFile(filePath, true);
}
catch (Exception ex){
// use the embedded logo
return Resources.sie_logo_petrol_rgb;
}
}
任何关于它为什么现在可以工作的见解都将非常感谢(因为我完全感到困惑)。通过使用catch…
部分中的块删除,然后只返回文件本身,它现在似乎可以工作了
public static Bitmap ReportLogo(string filePath){
try{
return (Bitmap)Image.FromFile(filePath, true);
}
catch (Exception ex){
// use the embedded logo
return Resources.sie_logo_petrol_rgb;
}
}
任何关于它为什么现在能工作的见解都将不胜感激(因为我完全困惑)。也许该程序正试图从参考资料中调整图像的大小。查看是否有类似于新位图(Helpers.ReportLogo(filePath))
@null的内容:问题在于reportlogouse对象在使用Helpers.ResizeImage
functionDebug herereturn(Bitmap)myImage之前存在代码>在try
和catch
上都可以,它是否以任何方式工作?这两种情况都是检索资源、强制转换资源的问题。还可以尝试使用(var myResourceImage…
删除,它将创建一个对象,但两种情况下的错误都是相同的。我在返回语句上尝试了使用和不使用强制转换到位图(可能是方法声明导致了问题?)可能程序正试图从资源中调整图像的大小。查看是否有类似于新位图(Helpers.ReportLogo(filePath))的内容。
@null:问题在于ReportLogouse对象在使用Helpers.ResizeImage
函数调试此处返回(位图)之前myImage;
在try
和catch
上都可以。它是否以任何方式工作?检索资源和强制转换资源都有问题。也可以尝试使用(var myResourceImage…
它将创建一个对象,但两种情况下的错误都是相同的。我在返回语句上使用和不使用强制转换到位图(可能是方法声明导致了问题?)