好的,我有一个带有图像的pictureBox,其sizeMode设置为:StretchImage,
现在,我想要得到我点击的像素。(bitmap.GetPixel (x, y))。
但是当图像从正常大小拉伸时,我得到原始像素。就像在拉伸之前的像素一样(如果有意义的话?)
Private void pictureBox1_MouseUp(object sender, MouseEventArgs e) {
Bitmap img = (Bitmap)pictureBox1.Image;
var color = img.GetPixel(e.X, e.Y)
}
Thanks In Advance
应该有一种方法来补偿由图片框引起的拉伸因子。我正在考虑从图片框中获取拉伸的宽度和高度,以及原始图像的宽度和高度,计算拉伸因子,并将它们与e.X
和e.Y
坐标相乘。比如:
Bitmap img = (Bitmap)pictureBox1.Image;
float stretch_X = img.Width / (float)pictureBox1.Width;
float stretch_Y = img.Height / (float)pictureBox1.Height;
var color = img.GetPixel((int)(e.X * stretch_X), (int)(e.Y * stretch_Y));
将e.X
和e.Y
用拉伸因子相除。这里是填充整个图片框的拉伸图像。
Bitmap img = (Bitmap)pictureBox1.Image;
float factor_x = (float)pictureBox1.Width / img.Width;
float factor_y = (float)pictureBox1.Height / img.Height;
var color = img.GetPixel(e.X / factor_x, e.Y / factor_y)
通过这样做,我们确保e.X
和e.Y
不会超过原始图像的限制。
您可以存储原始图像并保持不变。这将比调整拉伸图像的大小并获得指定的像素后记更容易。确保e.X和e.Y不会超出原始位图的边界。
private Bitmap _img;
public void LoadImage(string file) {
// Get the image from the file.
pictureBox1.Image = Bitmap.FromFile(file);
// Convert it to a bitmap and store it for later use.
_img = (Bitmap)pictureBox1.Image;
// Code for stretching the picturebox here.
// ...
}
private void pictureBox1_MouseUp(object sender, MouseEventArgs e) {
var color = _img.GetPixel(e.X, e.Y);
}
编辑:无视。马克西米利安的答案更好。