主要内容

在 App 中使用文件选择和警报对话框加载图像

此 App 说明如何配置和使用文件选择和警报对话框。在此 App 中,文件选择对话框允许 App 用户从其文件系统中选择图像。如果用户选择了无效文件类型的图像,则警报对话框会发出警报。该 App 显示所选图像和三个直方图,分别对应于图像包含的红色、绿色和蓝色像素。

此示例演示以下 App 构建任务:

  • 读取和显示图像。

  • 使用 uigetfile 函数浏览用户文件系统。

  • 使用 uialert 函数显示一个关于无效输入(本例中是不受支持的图像文件)的 App 内警报。

  • 使用直方图绘制图像数据。

Image Histograms app. The app contains an image, a drop-down list to select a new image, a Load Custom Image button, and three histograms of the red, green, and blue pixel intensities.

用文件选择对话框加载图像

对该 App 进行编程以显示一个文件选择对话框,供 App 用户选择自定义图像。如果您运行该 App 并点击 Load Custom Image 按钮,将出现文件选择对话框。

File selection dialog box with some image files

首先为 Load Custom Image 按钮创建一个 ButtonPushedFcn 回调。在 LoadCustomImageButtonPushed 回调函数中,指定有效的输入文件类型,并使用 uigetfile 函数创建对话框。

filterspec = {'*.jpg;*.tif;*.png;*.gif','All Image Files'};
[file,path] = uigetfile(filterspec);

函数 uigetfile 的输出提供所加载图像的文件名和路径。获取完整路径名称。

imagefile = [path file];

使用此完整路径名称显示图像并绘制图像的红色、绿色和蓝色像素的直方图。创建一个名为 updateImage 的新辅助函数来执行以下任务:

  • 使用完整路径名称读取并显示图像。

im = imread(imagefile);
imagesc(app.ImageAxes,im);
  • 在不同坐标区上绘制三个直方图,以显示红色、绿色和蓝色像素强度。

histr = histogram(app.RedAxes,im(:,:,1),"FaceColor",[1 0 0],"EdgeColor","none");
histg = histogram(app.GreenAxes,im(:,:,2),"FaceColor",[0 1 0],"EdgeColor","none");
histb = histogram(app.BlueAxes,im(:,:,3),"FaceColor",[0 0 1],"EdgeColor","none");

有关如何创建辅助函数的详细信息,请参阅使用辅助函数重用 App 中的代码

显示关于错误消息的 App 内警报

要在 App 用户执行无效操作时显示 App 内错误消息,请使用 uialert 创建一个警报对话框。例如,当用户选择文件类型不受支持的图像时,显示警报对话框。在 updateImage 函数中使用 try/catch 语句来处理不支持的文件类型的异常。首先使用 imread 函数读取图像文件。如果读取文件时出现错误,使用 uialert 显示错误消息。将 UI 图窗作为第一个参量传递,后跟指定为 MATLAB 错误文本的消息文本和警报标题。

try
    im = imread(imagefile);
catch ME
    % If problem reading image, display error message
    uialert(app.UIFigure,ME.message,"Image Error");
    return;
end

如果您尝试加载 App 不支持的自定义图像,则会出现警报对话框。

Image Histograms app with an alert dialog box. The title of the dialog box is "Image Error" and the text is "Unable to determine the file format".

另请参阅

函数

属性

主题