【发布时间】:2010-01-14 21:22:56
【问题描述】:
我需要在图像上绘制一个黑色矩形。我必须加载一个 tif,然后在它上面显示一个黑盒。我得到了一些代码的帮助,但我不断收到错误:无法从具有索引像素格式的图像创建图形对象。
所以我不得不将它读入位格式,但是当我显示框时,它会调整框的大小。并完全显示原始图像的全黑无画框。如果有人能帮我解决我哪里出错了,那就太棒了。
Bitmap original = (Bitmap)System.Drawing.Image.FromFile(coveted, true);
Bitmap newImage = new Bitmap(original.Width, original.Height);
pictureBox1.Image = newImage;
using (Graphics g = Graphics.FromImage(pictureBox1.Image))
{
using (SolidBrush brush = new SolidBrush(Color.Black))
{
g.FillRectangle(brush, new Rectangle(x1value, y1value, x3value, y3value));
}
}
我不确定如何才能更清楚地说明这一点。发生的事情是我的 tif 格式不受支持。所以我必须把它改成一个位图,这样我才能在上面画一个矩形。然后我需要在图片框中显示这个编辑过的图像(带有编辑的原始图像)。上面的代码是怎么回事,一旦完成,它显示的只是一个没有原始图像的黑盒。
我相信我运行了一些关于使用流中的位图然后关闭流的操作。有人熟悉这个吗?
感谢STO会员的帮助!!如果您遇到错误“无法从具有索引像素格式的图像创建图形对象”,这是编辑图像的正确代码。 如果您获得了编辑的起点(显然您必须使正则表达式适合您的情况):
//Regex for pulling points from a file
string x1 = x1 = Regex.Match(l, @"\r\n(\d+)\r\n(\d+)").Groups[2].Value;
string y1 = y1 = Regex.Match(l, @"\r\n(\d+)\r\n(\d+)\r\n(\d+)").Groups[3].Value;
string x2 = x2 = Regex.Match(l, @"\r\n(\d+)\r\n(\d+)\r\n(\d+)\r\n(\d+)").Groups[4].Value;
string y2 = y2 = Regex.Match(l, @"\r\n(\d+)\r\n(\d+)\r\n(\d+)\r\n(\d+)\r\n(\d+)").Groups[5].Value;
string x3 = x3 = Regex.Match(l, @"\r\n(\d+)\r\n(\d+)\r\n(\d+)\r\n(\d+)\r\n(\d+)\r\n(\d+)").Groups[6].Value;
string y3 = y3 = Regex.Match(l, @"\r\n(\d+)\r\n(\d+)\r\n(\d+)\r\n(\d+)\r\n(\d+)\r\n(\d+)\r\n(\d+)").Groups[7].Value;
{
//convert string to int for redacted points
int x1value = Convert.ToInt32(x1);
int y1value = Convert.ToInt32(y1);
int x3value = Convert.ToInt32(x3);
int y3value = Convert.ToInt32(y3);
{
//BEGIN Workaround for indexed pixels
Bitmap original = (Bitmap)System.Drawing.Image.FromFile(YOURFILE, true);
Bitmap newImage = new Bitmap(original);
pictureBox1.Image = newImage; //END Workaround for indexed pixels
using (Graphics g = Graphics.FromImage(pictureBox1.Image)) //start redaction
{
using (SolidBrush brush = new SolidBrush(Color.Black))
{
g.DrawImageUnscaled(newImage, 0,0);
g.FillRectangle(brush, new Rectangle(x1value, y1value, x3value, y3value));
}
} //End Redaction
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage; //Resized to fit into a static picturebox
}
}
【问题讨论】:
-
“我怎样才能使它更清楚” -> 首先取消缩进一点源代码。
标签: c#