我正在尝试将此类用于处理图像,我希望它具有一个位图字段,而构造函数则可以让我允许我进入位图路径,以便其他方法可以使用该位图。所以我希望它能够做到这一点:
ImageProcessing image = new ImageProcessing("D:\image.bmp");
int time_of_processing = image.grayscale();
image.SaveTo("D:\image2.bmp");
,这是我的代码:
public class ImageProcessing
{
Bitmap image;
public ImageProcessing(string path)
{
image = new Bitmap(path);
}
public int Grayscale()
{
Stopwatch time = new Stopwatch();
time.Start();
for (int x = 0; x < image.Width; x++)
{
for (int y = 0; y < image.Height; y++)
{
Color pixelColor = image.GetPixel(x, y);
int grayScale = (int)((pixelColor.R * 0.21) + (pixelColor.G * 0.72) + (pixelColor.B * 0.07));
Color newColor = Color.FromArgb(grayScale, grayScale, grayScale);
image.SetPixel(x, y, newColor);
}
}
time.Stop();
TimeSpan ts = time.Elapsed;
int milliseconds = ts.Milliseconds + (ts.Seconds * 1000);
return milliseconds;
}
public void SaveTo(string path)
{
image.Save(path);
}
}
当我拥有这个时,Visual Studio告诉我,图像将永远是无效的。构造函数应该如何工作?
当您使用它时,将命名空间添加到ImageProcessing类中,以确保其始终使用正确的类。以下代码(主要仅是原始代码(已进行了测试并有效(刻在列出的图像(中。
namespace WindowsFormsApplication10
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
string path1 = @"C:worktest.bmp";
string path2 = @"C:worktest2.bmp";
WindowsFormsApplication10.ImageProcessing image = new WindowsFormsApplication10.ImageProcessing(path1);
int time_of_processing = image.Grayscale();
image.SaveTo(path2);
}
}
public class ImageProcessing
{
Bitmap image;
public ImageProcessing(string path)
{
image = new Bitmap(path);
}
public int Grayscale()
{
Stopwatch time = new Stopwatch();
time.Start();
for (int x = 0; x < image.Width; x++)
{
for (int y = 0; y < image.Height; y++)
{
Color pixelColor = image.GetPixel(x, y);
int grayScale = (int)((pixelColor.R * 0.21) + (pixelColor.G * 0.72) + (pixelColor.B * 0.07));
Color newColor = Color.FromArgb(grayScale, grayScale, grayScale);
image.SetPixel(x, y, newColor);
}
}
time.Stop();
TimeSpan ts = time.Elapsed;
int milliseconds = ts.Milliseconds + (ts.Seconds * 1000);
return milliseconds;
}
public void SaveTo(string path)
{
image.Save(path);
}
}
}