从资源文件访问图像对象

本文关键字:图像 对象 访问 源文件 资源 | 更新日期: 2023-09-27 18:00:59

在我的项目中,我需要(从磁盘(检索一个自定义图像文件。如果提供的路径中不存在图像文件,则应用程序将使用默认图像(嵌入资源(。一旦我有了图像,我需要调整它的大小,以便在我的应用程序中进一步使用。

如果我尝试只访问嵌入的资源(代码部分1(,一切都会按预期进行。如果试图在图像上设置条件(代码部分2(,则对象返回时会出现对象上的各种异常,尤其是出于我的目的:

((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...部分中的using...块,并仅返回文件本身,它现在似乎正在运行。

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;
    }
}

任何关于它为什么现在有效的见解都将不胜感激(因为我完全困惑(。