Clipping pixels under a polygon - c#

I am attempting to retrieve the pixels under a polygon; however, I seem to be unable to correctly get all the pixels accurately. Below is the code I have:
private void DrawPolygon()
{
PointF[] pts = new PointF[]{new PointF(5.196057f, 4.13434839f), new PointF(5.528517f, 4.621298f), new PointF(7.073008f, 6.5661006f), new PointF(5.28491259f, 9.206118f), new PointF(4.80768776f, 6.595068f), new PointF(5.196057f, 4.13434839f)};
GraphicsPath gp = new GraphicsPath(FillMode.Alternate);
gp.AddPolygon(pts);
Bitmap bmp = Bitmap.FromFile("...");
Graphics g = Graphics.FromImage(bmp);
g.SmoothingMode = SmoothingMode.None;
g.PixelOffsetMode = PixelOffsetMode.Half;
using (Brush b = new SolidBrush(Color.White))
{
g.FillPath(b, gp);
}
bmp.Save("...");
}
In the image below (left) you can see that several pixels under the polygon are excluded. Image on the right was the original with all pixels having a value. I feel that I am missing a setting in the 'Graphics', but I cannot figure out what.

Related

Cyotek ImageBox get zoomed part of image

I am using Cyotek ImageBox to zoom a image, now if I zoom to a part of image and that part is visible in the ImageBox how can I save that part of image which is visible in ImageBox.
The GetSourceImageRegion method allows you to get a RectangleF that describes the part of the image that is visible in the current state of an ImageBox.
The example code below will create a new Bitmap based on the visible part of the image. This example is not zoomed.
Rectangle visibleImageRegion;
Bitmap result;
visibleImageRegion = Rectangle.Round(imageBox.GetSourceImageRegion());
result = new Bitmap(visibleImageRegion.Width, visibleImageRegion.Height);
using (Graphics g = Graphics.FromImage(result))
{
g.DrawImage(imageBox.Image, new Rectangle(Point.Empty, visibleImageRegion.Size), visibleImageRegion, GraphicsUnit.Pixel);
}
This next example does the same as above, but also scales the new image to match the ImageBox
RectangleF visibleImageRegion;
Bitmap result;
double zoomFactor;
int w;
int h;
visibleImageRegion = imageBox.GetSourceImageRegion();
zoomFactor = imageBox.ZoomFactor;
w = Convert.ToInt32(visibleImageRegion.Width * zoomFactor);
h = Convert.ToInt32(visibleImageRegion.Height * zoomFactor);
result = new Bitmap(w, h);
using (Graphics g = Graphics.FromImage(result))
{
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.DrawImage(imageBox.Image, new Rectangle(0, 0, w, h), visibleImageRegion, GraphicsUnit.Pixel);
}
You could hook into the Scroll or Zoomed events of the control to detect when you need to update the image based on user activity.

How to crop an image with a rotated rectangle?

I have an image in the form of a System.Drawing.Bitmap and a rectangle in the form of 4 points (Vector2s which are trivially converted to PointFs).
I want to use those points to crop out a section of the image. I found this answer which is pretty close to what I want, but I'm not sure how to get the right matrix out of it.
Here's what I've got so far:
protected static Bitmap CropImage(Bitmap src, Vector2[] rect)
{
var width = (rect[1] - rect[0]).Length;
var height = (rect[3] - rect[0]).Length;
var result = new Bitmap(M2.Round(width), M2.Round(height));
using (Graphics g = Graphics.FromImage(result))
{
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
using (Matrix mat = new Matrix())
{
// ????
}
}
return result;
}
How can I get the proper transform matrix out of my rect?
It would be the same as in the linked answer, but instead of:
mat.Translate(-rect.Location.X, -rect.Location.Y);
mat.RotateAt(angle, rect.Location);
You would use:
double angle = Math.Atan2(rect[1].Y - rect[0].Y, rect[1].X - rect[0].X);
mat.Translate(-rect[0].X, -rect[0].Y);
mat.RotateAt((float)angle, rect[0]);
(Or something along those lines. It may be -angle, or rect[0] instead of rect[1] and vice-versa in Atan2. I can’t check immediately…)
Figured it out:
protected static Bitmap CropImage(Bitmap src, Vector2[] rect)
{
var width = (rect[1] - rect[0]).Length;
var height = (rect[3] - rect[0]).Length;
var result = new Bitmap(M2.Round(width), M2.Round(height));
using (Graphics g = Graphics.FromImage(result))
{
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
using (Matrix mat = new Matrix())
{
var rot = -Math.Atan2(rect[1].Y - rect[0].Y, rect[1].X - rect[0].X) * M2.RadToDeg;
mat.Translate(-rect[0].X, -rect[0].Y);
mat.RotateAt((float)rot, rect[0].ToPointF());
g.Transform = mat;
g.DrawImage(src, new Rectangle(0, 0, src.Width, src.Height));
}
}
return result;
}

Drawing a textured triangle

I have one image and three vertices with its position and its texcoord.
How can I draw this textured triangle in a picturebox?
This is an image explaining what it is:
You can use a GraphicsPath and a TextureBrush:
// Create the triangle
GraphicsPath p = new GraphicsPath();
p.AddLine(triangleVertex1, triangleVertex2);
p.AddLine(triangleVertex2, triangleVertex3);
p.CloseFigure();
// Draw the triangle
Bitmap b = new Bitmap(pictureBox.ClientSize.Width, pictureBox.ClientSize.Height);
using(Graphics g = Graphics.FromImage(b), TextureBrush t = new TextureBrush(myImage)) {
g.FillPath(t, p);
}
// Finally, set the PictureBox's image
pictureBox.Image = b;

c# write text on bitmap

I have following problem. I want to make some graphics in c# windows form.
I want to read bitmap to my program and after it write some text on this bitmap. In the end I want this picture load to pictureBox. And it's my question. How can I do it?
example, how must it work:
Bitmap a = new Bitmap(#"path\picture.bmp");
a.makeTransparent();
// ? a.writeText("some text", positionX, positionY);
pictuteBox1.Image = a;
Is it possible do to?
Bitmap bmp = new Bitmap("filename.bmp");
RectangleF rectf = new RectangleF(70, 90, 90, 50);
Graphics g = Graphics.FromImage(bmp);
g.SmoothingMode = SmoothingMode.AntiAlias;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
g.DrawString("yourText", new Font("Tahoma",8), Brushes.Black, rectf);
g.Flush();
image.Image=bmp;
Very old question, but just had to build this for an app today and found the settings shown in other answers do not result in a clean image (possibly as new options were added in later .Net versions).
Assuming you want the text in the centre of the bitmap, you can do this:
// Load the original image
Bitmap bmp = new Bitmap("filename.bmp");
// Create a rectangle for the entire bitmap
RectangleF rectf = new RectangleF(0, 0, bmp.Width, bmp.Height);
// Create graphic object that will draw onto the bitmap
Graphics g = Graphics.FromImage(bmp);
// ------------------------------------------
// Ensure the best possible quality rendering
// ------------------------------------------
// The smoothing mode specifies whether lines, curves, and the edges of filled areas use smoothing (also called antialiasing).
// One exception is that path gradient brushes do not obey the smoothing mode.
// Areas filled using a PathGradientBrush are rendered the same way (aliased) regardless of the SmoothingMode property.
g.SmoothingMode = SmoothingMode.AntiAlias;
// The interpolation mode determines how intermediate values between two endpoints are calculated.
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
// Use this property to specify either higher quality, slower rendering, or lower quality, faster rendering of the contents of this Graphics object.
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
// This one is important
g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
// Create string formatting options (used for alignment)
StringFormat format = new StringFormat()
{
Alignment = StringAlignment.Center,
LineAlignment = StringAlignment.Center
};
// Draw the text onto the image
g.DrawString("yourText", new Font("Tahoma",8), Brushes.Black, rectf, format);
// Flush all graphics changes to the bitmap
g.Flush();
// Now save or use the bitmap
image.Image = bmp;
References
https://msdn.microsoft.com/en-us/library/system.drawing.graphics.smoothingmode(v=vs.110).aspx
https://msdn.microsoft.com/en-us/library/system.drawing.drawing2d.interpolationmode(v=vs.110).aspx
https://msdn.microsoft.com/en-us/library/system.drawing.graphics.pixeloffsetmode(v=vs.110).aspx
https://msdn.microsoft.com/en-us/library/system.drawing.graphics.textrenderinghint(v=vs.110).aspx
https://msdn.microsoft.com/en-us/library/system.drawing.stringformat(v=vs.110).aspx
https://msdn.microsoft.com/en-us/library/21kdfbzs(v=vs.110).aspx
You need to use the Graphics class in order to write on the bitmap.
Specifically, one of the DrawString methods.
Bitmap a = new Bitmap(#"path\picture.bmp");
using(Graphics g = Graphics.FromImage(a))
{
g.DrawString(....); // requires font, brush etc
}
pictuteBox1.Image = a;
var bmp = new Bitmap(#"path\picture.bmp");
using( Graphics g = Graphics.FromImage( bmp ) )
{
g.DrawString( ... );
}
picturebox1.Image = bmp;
If you want wrap your text, then you should draw your text in a rectangle:
RectangleF rectF1 = new RectangleF(30, 10, 100, 122);
e.Graphics.DrawString(text1, font1, Brushes.Blue, rectF1);
See: https://msdn.microsoft.com/en-us/library/baw6k39s(v=vs.110).aspx

C# GDI+ curve drawing issue

I'm trying to draw a series of connected segments, but the curved segments seem to produce an artifact, whereby the outer side of the curve is not smooth at all, but very jagged. This is part of a GIS program I am making.
For these lines, the line itself needs to be quite wide, as this represents the range of data that can be collected on this line for the GIS data. There also has to be an area directly under the line where no data is collected. This also can be wide, but not as wide as the main line.
I have done this using a graphics path, which I then widen and use as a clipping region to block the area directly under the line. I then draw the actual line. The sample code below does this, with made up values for ease of regenerating.
This works fine with straight lines, but with curved lines there are very irregular shapes on the outside of the curves. I have no idea why this happens.
Any ideas would be much appreciated, cheers,
Greg
I made this sample code using a basic form with a picturebox and a button on it, whereby when I clicked the button it would execute this method:
private void drawCurvedLine()
{
//initialise the plot area:
Bitmap image = new Bitmap(pictureBox1.Width, pictureBox1.Height);
pictureBox1.BackgroundImage = image;
Graphics g = Graphics.FromImage(image);
//the width of the pen represents the width of a sonar swathe:
Pen widePen = new Pen(new SolidBrush(Color.FromArgb(80, Color.Blue)), 50);
PointF[] points = new PointF[4];
//first straight:
points[0] = new PointF(287.284149F,21.236269F);
points[1] = new PointF(183.638443F,406.936249F);
//second straight:
points[2] = new PointF(130.842773F, 515.574036F);
points[3] = new PointF(-1950.91321F, 3491.868F);
//graphics path for the line:
GraphicsPath gPath = new GraphicsPath();
gPath.AddLine(points[0], points[1]);
gPath.AddArc(new RectangleF(-445.464447F,3.84924316F,640.067444F,640.067444F), -(90 - 105.0412369999982F), 10.8775282F);
gPath.AddArc(new RectangleF(-445.464417F, 3.84915161F, 640.067444F, 640.067444F), -(90 - 115.91811484539707F), 10.8775091F);
gPath.AddLine(points[2], points[3]);
//widen the line to the width equal to what the fish will not be able to see:
gPath.Widen(new Pen(Color.White, 10));
//now exclude that widened line from the main graphics:
g.ExcludeClip(new Region(gPath));
//draw the swathe line:
g.DrawPath(widePen, gPath);
//reset the clipping for the next line:
g.ResetClip();
}
Try to use a separate GraphicsPath for excluded region:
private void drawCurvedLine()
{
//initialise the plot area:
Bitmap image = new Bitmap(pictureBox1.Width, pictureBox1.Height);
pictureBox1.BackgroundImage = image;
using(Graphics g = Graphics.FromImage(image))
{
PointF[] points = new PointF[4];
//first straight:
points[0] = new PointF(287.284149F, 21.236269F);
points[1] = new PointF(183.638443F, 406.936249F);
//second straight:
points[2] = new PointF(130.842773F, 515.574036F);
points[3] = new PointF(-1950.91321F, 3491.868F);
//graphics path for the line:
using(GraphicsPath gPath = new GraphicsPath())
{
gPath.AddLine(points[0], points[1]);
gPath.AddArc(new RectangleF(-445.464447F, 3.84924316F, 640.067444F, 640.067444F), -(90 - 105.0412369999982F), 10.8775282F);
gPath.AddArc(new RectangleF(-445.464417F, 3.84915161F, 640.067444F, 640.067444F), -(90 - 115.91811484539707F), 10.8775091F);
gPath.AddLine(points[2], points[3]);
//widen the line to the width equal to what the fish will not be able to see:
using(GraphicsPath innerPath = (GraphicsPath)gPath.Clone())
{
using(Pen pen = new Pen(Color.White, 10))
{
innerPath.Widen(pen);
}
//now exclude that widened line from the main graphics:
using(Region reg = new Region(innerPath))
{
g.ExcludeClip(reg);
//draw the swathe line:
//the width of the pen represents the width of a sonar swathe:
using(Pen widePen = new Pen(new SolidBrush(Color.FromArgb(80, Color.Blue)), 50))
{
g.DrawPath(widePen, gPath);
}
//reset the clipping for the next line:
g.ResetClip();
}
}
}
}
}
Set the smoothing mode properly on your Graphics instance. Take a look here.
Try setting the CompositingQuality, the InterpolationMode and the SmoothingMode properties to increase the quality of your Graphics object:
using(Graphics g = Graphics.FromImage(image))
{
g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
g.SmoothingMode = SmoothingMode.AntiAlias;
//...
}

Categories