C#如何将DLL中封装的灰度处理方法适配到WinForm主程序Form1.cs
你当前遇到的问题主要有两个:
- DLL内的
DoGray方法修饰符为private,仅允许类内部访问,外部项目无法调用 - 主项目没有调用DLL类方法的对应逻辑,直接调用本地不存在的
DoGray方法会报编译错误
步骤1:修改DLL项目代码
修改gdll项目中Class1的代码,将DoGray方法改为公开静态方法(工具类方法用静态更易用,不需要每次实例化),修改后代码如下:
using System; using System.Drawing; namespace gdll { public class Class1 { // 把private改为public static,允许外部直接调用 public static Bitmap DoGray(Bitmap bmp) { // 提示:原代码循环条件少处理了最后一行和最后一列,不需要的话可以删掉-1 for (int i = 0; i < bmp.Height; i++) { for (int j = 0; j < bmp.Width; j++) { int value = (bmp.GetPixel(j, i).R + bmp.GetPixel(j, i).G + bmp.GetPixel(j, i).B) / 3; Color clr = Color.FromArgb(value, value, value); bmp.SetPixel(j, i, clr); } } return bmp; } } }
修改完成后重新编译DLL项目,得到新的gdll.dll文件。
步骤2:确认主项目引用配置
右键你的dnmimage主项目 → 选择【添加】→【引用】→ 选中上一步编译得到的gdll.dll,确认引用添加成功。你现有代码顶部已经写了using gdll;,这部分无需额外修改。
步骤3:修改Form1.cs中的按钮点击逻辑
修改button2_Click方法的代码,调用DLL中的静态方法即可,修改后代码如下:
private void button2_Click(object sender, EventArgs e) { Bitmap image= new Bitmap(pictureBox1.Image); // 调用DLL中Class1的公开静态方法 Bitmap gray = gdll.Class1.DoGray(image); pictureBox2.Image = gray; }
如果你没有把DoGray设置为静态方法,就需要先实例化Class1再调用:
private void button2_Click(object sender, EventArgs e) { Bitmap image= new Bitmap(pictureBox1.Image); gdll.Class1 handler = new gdll.Class1(); Bitmap gray = handler.DoGray(image); pictureBox2.Image = gray; }
内容的提问来源于stack exchange,提问作者user16815856
相关产品推荐
相关产品推荐

