I have a large DrawingVisual that is added to a Canvas and I want to get the color value of a pixel when I click the mouse. I tried rendering the entire Visaul to a RenderTargetBitmap but got an "Out of memory" exception. then using an example I found here How to render (bitmap) only part of a Visual?
I tried rendering only part of the Visual but I dont get the correct pixel value. currently my code looks like this
private void OnMouseDown(object sender, System.Windows.Input.MouseEventArgs e)
{
// Retreive the coordinates of the mouse button event.
Point pt = e.GetPosition((UIElement)sender);
VisualBrush vb = new VisualBrush(myDrawingVisual);
vb.ViewboxUnits = BrushMappingMode.Absolute;
// create rect from the position in the canvas - starting point of the DrawingVisual
vb.Viewbox = new Rect(point.X - myDrawingVisual.ContentBounds.Left,point.Y - myDrawingVisual.ContentBounds.Top, 1, 1);
vb.ViewportUnits = BrushMappingMode.Absolute;
vb.Viewport = new Rect(point, new Size(1, 1));
System.Windows.Shapes.Rectangle r = new System.Windows.Shapes.Rectangle();
r.Width = 1;
r.Height = 1;
r.Fill = vb;
// Use RenderTargetBitmap to get the visual, in case the image has been transformed.
var renderTargetBitmap = new RenderTargetBitmap(1,
1,
96, 96, PixelFormats.Default);
renderTargetBitmap.Render(r);
var pixels = new byte[4];
renderTargetBitmap.CopyPixels(pixels, 4, 0);
}
You haven't laid out the Rectangle. For details refer to the Layout article on MSDN.
Add the following lines:
r.Measure(new Size(1, 1));
r.Arrange(new Rect(0, 0, 1, 1));
var renderTargetBitmap = ...
renderTargetBitmap.Render(r);
Related
Trying to add a watermark image to a png image, i´ve been able to do it, but i want to take out the hardCoded size regulation for the rectangle of the waterMark, and make it always stay in the center of the image. How can i achieve this.
public Form1()
{
InitializeComponent();
picBox.Parent = this;
picBox.Dock = DockStyle.Fill;
picBox.SizeMode = PictureBoxSizeMode.Zoom;
Bitmap Jpg = new Bitmap(#"C:\Users\tferreira\Desktop\213123.PNG");
using (Bitmap Bmp = new Bitmap(#"C:\Users\tferreira\Desktop\logo.png"))
{
using (Bitmap WatermarkBmp = new Bitmap(Bmp, Bmp.Width / 1, Bmp.Height / 1))
{
picBox.Image = WatermarkImage(Jpg, WatermarkBmp, new Point(400, 100), 0.40F);
}
}
}
public Bitmap WatermarkImage(Bitmap ImageToWatermark, Bitmap Watermark, Point WatermarkPosition, float Opacity)
{
using (Graphics G = Graphics.FromImage(ImageToWatermark))
{
using (ImageAttributes IA = new ImageAttributes())
{
ColorMatrix CM = new ColorMatrix();
CM.Matrix33 = Opacity;
IA.SetColorMatrix(CM);
G.DrawImage(Watermark, new Rectangle(WatermarkPosition, Watermark.Size), 0, 0, Watermark.Width, Watermark.Height, GraphicsUnit.Pixel, IA);
}
}
return ImageToWatermark;
}
Right now the images are hardCoded but that will be taken out. If anyone can help me make this watermark allways stay centered i thank you.
I fixed this problem with this nice peace of code.
System.Drawing.Image img = System.Drawing.Image.FromFile(JpgFilePath);
Bitmap jpg = new Bitmap(img);
filePath = JpgFilePath;
int Width = jpg.Width;
int Height = jpg.Height;
jpg.SetResolution(300, 300);
WaterMarked = WatermarkImage(jpg, WaterMarkBit, new Point((Width - WaterMarkBit.Width) / 2, (Height - WaterMarkBit.Height) / 2), 0.4F);
WaterMarked.Save(filePath.Replace(".jpg", "") + ".tif", ImageFormat.Tiff);
filesJpgForTif.Add(JpgFilePath.Replace("jpg", "tif"));
Using the the sizes of the image and sizes of the watermark and divide it by 2 it makes the image always stay centered.
I'm trying to make an image cropping tool.
I am following this https://www.codeproject.com/Articles/703519/Cropping-Particular-Region-In-Image-Using-Csharp
But since it's a bit old and the plugin/DLL's it uses have changed I have been trying to adapt his code from OpenCvSharp 2.0 to OpenCvSharp 2.4
When I'm converting the bitmaps to IplImages and using Cv.Mul() it gives me this error:
Attempted to read or write protected memory. This is often an indication that other memory is corrupt
I have never used OpenCvSharp other ways of creating the IplImage even reading the IplImage from a written image.
Code:
public static IplImage BitmapToIplImage(Bitmap bitmap)
{
IplImage tmp, tmp2;
System.Drawing.Rectangle bRect = new System.Drawing.Rectangle(new System.Drawing.Point(0, 0), new System.Drawing.Size((int)bitmap.Width, (int)bitmap.Height));
BitmapData bmData = bitmap.LockBits(bRect, ImageLockMode.ReadWrite, bitmap.PixelFormat);
tmp = Cv.CreateImage(Cv.Size(bitmap.Width, bitmap.Height), BitDepth.U8, 3);
tmp2 = Cv.CreateImage(Cv.Size(bitmap.Width, bitmap.Height), BitDepth.U8, 1);
byte[] data = new byte[Math.Abs(bmData.Stride * bmData.Height)];
tmp.SetData(bmData.Scan0, data.Length);
bitmap.UnlockBits(bmData);
// Cv.CvtColor(tmp, tmp2, ColorConversion.RgbToGray);
return tmp;
}
private void CropImage()
{
IplImage ipl = Cv.CreateImage(new CvSize(curBmp.Width, curBmp.Height), BitDepth.U8, 3);
Graphics ga = Graphics.FromImage(curBmp);
ga.FillRectangle(new SolidBrush(System.Drawing.Color.Black), new System.Drawing.Rectangle(0, 0, curBmp.Width, curBmp.Height));
SolidBrush brush = new SolidBrush(System.Drawing.Color.FromArgb(1, 1, 1));
curGraphics.FillClosedCurve(brush, imagePoints.ToArray());
Cv.Mul(BitmapToIplImage(curOgBmp), BitmapToIplImage(curBmp), ipl, 1);
ComputeCrop();
Stream s = null;
ipl.ToStream(s, ".png", null);
curBmp = new Bitmap(s);
RefreshImageViewer();
}
-----------------------------EDIT-----------------------------------------
I tried to follow what Markus posted, and I got it to work without any errors in the code.
Although the image cropped is a bit strange here are the methods I use, plus the RefreshImageViewer that is how I put the bitmap in the image control.
I have been trying to see if I missed something for hours, but I think not.
Output example: Imgur image link
Code:
public void RefreshImageViewer()
{
bmpSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
curBmp.GetHbitmap(),
IntPtr.Zero,
System.Windows.Int32Rect.Empty,
BitmapSizeOptions.FromWidthAndHeight(curBmp.Width, curBmp.Height));
imageViewer.Source = bmpSource;
curGraphics = Graphics.FromImage(curBmp);
}
private void CropImage()
{
Graphics Ga = Graphics.FromImage(curBmp);
//the black image
Ga.FillRectangle(new SolidBrush(System.Drawing.Color.Black), new System.Drawing.Rectangle(0, 0, curBmp.Width, curBmp.Height));
//draw from the last point to first point
Ga.DrawLine(new System.Drawing.Pen(System.Drawing.Color.Red, 3), imagePoints[imagePoints.Count - 1], imagePoints[0]);
//all of the rgb values are being set 1 inside the polygon
SolidBrush Brush = new SolidBrush(System.Drawing.Color.FromArgb(1, 1, 1));
//we have to prepare one mask of Multiplying operation for cropping region
curGraphics.FillPolygon(Brush, imagePoints.ToArray());
Mat accc = (BitmapToMat(curOgBmp).Mul(BitmapToMat(curBmp))).ToMat();
System.Drawing.Rectangle r = ComputeCrop();
curBmp = accc.ToBitmap().Clone(r, curOgBmp.PixelFormat);
RefreshImageViewer();
}
private System.Drawing.Rectangle ComputeCrop()
{
int smallestX = curBmp.Width, biggestX = 0, biggestY = 0, smallestY = curBmp.Height;
for (int i = 0; i < imagePoints.Count; i++)
{
biggestX = Math.Max(biggestX, imagePoints[i].X);
smallestX = Math.Min(smallestX, imagePoints[i].X);
biggestY = Math.Max(biggestY, imagePoints[i].Y);
smallestY = Math.Min(smallestY, imagePoints[i].Y);
}
System.Drawing.Rectangle rectCrop = new System.Drawing.Rectangle(smallestX, smallestY, biggestX - smallestX, biggestY - smallestY);
return rectCrop;
}
public static Mat BitmapToMat(Bitmap bitmap)
{
Mat tmp, tmp2;
System.Drawing.Rectangle bRect = new System.Drawing.Rectangle(new System.Drawing.Point(0, 0), new System.Drawing.Size((int)bitmap.Width, (int)bitmap.Height));
BitmapData bmData = bitmap.LockBits(bRect, ImageLockMode.ReadWrite, bitmap.PixelFormat);
tmp2 = new Mat(new OpenCvSharp.Size(bitmap.Width, bitmap.Height), MatType.CV_8U);
tmp = new Mat(bitmap.Height, bitmap.Width, MatType.CV_8UC3, bmData.Scan0);
bitmap.UnlockBits(bmData);
return tmp;
}
“IplImage” ist the old image container from OpenCv 1. As Andreas already mentioned, today you should use “Mat” instead. Have also a look here : Difference between cvMat, Mat and IpImage
Unfortunately, your code sample is not complete, hence I corrected the two methods from the original project ( https://www.codeproject.com/Articles/703519/Cropping-Particular-Region-In-Image-Using-Csharp).
The following methods are tested and work as intended in the original project in combination with the latest OpenCVSharp version (v4.x) . It should be very simple now to convert the changes to your code.
public static Mat BitmapToIplImage(Bitmap bitmap)
{
Mat tmp, tmp2;
Rectangle bRect = new Rectangle(new System.Drawing.Point(0, 0), new System.Drawing.Size((int)bitmap.Width, (int)bitmap.Height));
BitmapData bmData = bitmap.LockBits(bRect, ImageLockMode.ReadWrite, bitmap.PixelFormat);
tmp2 = new Mat(new Size(bitmap.Width, bitmap.Height), MatType.CV_8U);
tmp = new Mat(bitmap.Height, bitmap.Width, MatType.CV_8UC3, bmData.Scan0);
bitmap.UnlockBits(bmData);
return tmp;
}
private void crop()
{
timer1.Stop();
Graphics Ga = Graphics.FromImage(bmp);
//the black image
Ga.FillRectangle(new SolidBrush(Color.Black), new Rectangle(0, 0, bmp.Width, bmp.Height));
//draw from the last point to first point
Ga.DrawLine(new Pen(Color.Red, 3), polygonPoints[polygonPoints.Count - 1], polygonPoints[0]);
//all of the rgb values are being set 1 inside the polygon
SolidBrush Brush = new SolidBrush(Color.FromArgb(1, 1, 1));
//we have to prepare one mask of Multiplying operation for cropping region
G.FillClosedCurve(Brush, polygonPoints.ToArray());
var accc= (BitmapToIplImage(Source).Mul(BitmapToIplImage(bmp))).ToMat();
computecrop();
croplast = accc.ToBitmap().Clone(rectcrop, Source.PixelFormat);//just show cropped region part of image
pictureBox2.Image = croplast; // crop region of image
}
Im drawing Text using the following code onto a Bitmap
GraphicsPath pth = new GraphicsPath();
var style = (int)myfont.Style;
pth.AddString(tcaption.Text, myfont.FontFamily, style, myfont.Size, point, StringFormat.GenericTypographic);
p = new Pen(new SolidBrush(bc), 2f);
mygraphics.DrawPath(p, pth);
I'm using the TextRenderer to measure the size of the string..
int Width = TextRenderer.MeasureText(tcaption.Text, myfont).Width;
But this does not produce the correct size of the drawn string; there is around 20-30% difference from the actual size of the drawn string?
What im i doing wrong? Please advice.
UPDATE:
I want to draw a Text and an Image onto a Bitmap,so inorder to accommodate both i'm creating an Bitmap like this
intWidth = TextRenderer.MeasureText(tcaption.Text, cfont).Width + image.Width;
intHeight = TextRenderer.MeasureText(tcaption.Text, cfont).Height +image.Height;
tempimage= new Bitmap(intWidth, intHeight);
Then i create Graphics object from the Bitmap like this
using (Graphics newg = Graphics.FromImage(tempimage))
#Hans Passant
I have also tried the Graphics.MeasureString as an alternative to TextRenderer
Now i set the position of the text and image-I need to draw the image at the top left corner .. so
imageposy = 0;
imageposx = 10;
textposy = image.Height;
textposx = 0;
Then i draw the text like this
po=new Point(textposx, textposy);
newg.SmoothingMode = SmoothingMode.AntiAlias;
GraphicsPath pth = new GraphicsPath();
var style = (int)myfont.Style;
pth.AddString(tcaption.Text, myfont.FontFamily, style, myfont.Size, po,
StringFormat.GenericTypographic);
newg.FillPath(new SolidBrush(fc), pth);
Now i draw the image like this
Rectangle nrect = new Rectangle(imageposx, imageposy, image.Width,
image.Height);
objGraphics = Graphics.FromImage(tempimage);
objGraphics.DrawImage(image, nrect);
As you have seen i need to add the offset 10 to imageposition x coordinate to correct the measurement issue.
Hope my update throws more light into the question... what im i doing wrong?
Please advice..
instead of using TextRenderer use GraphicsPath:
var path = new GraphicsPath();
path.AddString(text, font.FontFamily, (int)font.Style, size, new Point(0, 0), StringFormat.GenericTypographic);
var area = Rectangle.Round(path.GetBounds());
Here is sample code that generates image with size of text:
private Image DrawText(String text, Font font, int size, Color textColor, Color backColor)
{
var path = new GraphicsPath();
path.AddString(text, font.FontFamily, (int)font.Style, size, new Point(0, 0), StringFormat.GenericTypographic);
var area = Rectangle.Round(path.GetBounds());
Rectangle br = Rectangle.Round(path.GetBounds());
var img = new Bitmap(br.Width, br.Height);
var drawing = Graphics.FromImage(img);
drawing.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit;
drawing.SmoothingMode = SmoothingMode.HighSpeed;
drawing.Clear(backColor);
drawing.TranslateTransform((img.Width - br.Width) / 2 - br.X, (img.Height - br.Height) / 2 - br.Y);
drawing.FillPath(Brushes.Black, path);
Brush textBrush = new SolidBrush(textColor);
drawing.Save();
textBrush.Dispose();
drawing.Dispose();
return img;
}
Here are sample results:
I have a bug in my image editor with the blur tool.
When I select the rectangle to set the blur effect, and when I apply, result is a bit different see:
To create the "Before" I do:
var blurredImage = ExtractImageToBlur(); // extract the selected area from image
BlurredImageRectangle.Fill = new ImageBrush(blurredImage);
var effect = new BlurEffect();
effect.KernelType = KernelType.Gaussian;
effect.RenderingBias = RenderingBias.Quality;
effect.Radius = m_blurValue;
BlurredImageRectangle.Effect = effect;
To create the "After", I do:
var blurredImage = ExtractImageToBlur(); // extract the selected area from image
Rectangle rectangleToRender = new Rectangle();
rectangleToRender.Fill = new ImageBrush(blurredImage);
var effect = new BlurEffect();
effect.KernelType = KernelType.Gaussian;
effect.RenderingBias = RenderingBias.Quality;
effect.Radius = m_blurValue;
rectangleToRender.Effect = effect;
Size size = new Size(croppedImg.PixelWidth, croppedImg.PixelHeight);
rectangleToRender.Measure(size);
rectangleToRender.Arrange(new Rect(size));
var render = new RenderTargetBitmap(croppedImg.PixelWidth, croppedImg.PixelHeight, 96, 96, PixelFormats.Pbgra32);
render.Render(rectangleToRender);
// Merge the source with the blurred section
DrawingVisual drawingVisual = new DrawingVisual();
using (DrawingContext context = drawingVisual.RenderOpen())
{
int left = (int)(Canvas.GetLeft(BlurredImageRectangle) * WidthRatio);
int top = (int)(Canvas.GetTop(BlurredImageRectangle) * HeightRatio);
context.DrawImage(Source, new Rect(0, 0, Source.PixelWidth, Source.PixelHeight));
context.DrawImage(render, new Rect(left, top, croppedImg.PixelWidth, croppedImg.PixelHeight));
}
var bitmap = new RenderTargetBitmap(Source.PixelWidth, Source.PixelHeight, 96, 96, PixelFormats.Pbgra32);
bitmap.Render(drawingVisual);
And when I play with the blur radius, its sometimes a lot more different from both images.
Why its not the same?
Found the problem.
When I was drawing the rectangle on the screen, I applied the blur effect on the pixels on the screen.
When I hit save, the blur effect is applied on the pixel on the image on disk.
Huge difference.
I want to rotate an image in the picture box. Here is my code.
public static Bitmap RotateImage(Image image, PointF offset, float angle)
{
if (image == null)
{
throw new ArgumentNullException("image");
}
var rotatedBmp = new Bitmap(image.Width, image.Height);
rotatedBmp.SetResolution(image.HorizontalResolution, image.VerticalResolution);
var g = Graphics.FromImage(rotatedBmp);
g.TranslateTransform(offset.X, offset.Y);
g.RotateTransform(angle);
g.TranslateTransform(-offset.X, -offset.Y);
g.DrawImage(image, new PointF(0, 0));
return rotatedBmp;
}
private void button1_Click(object sender, EventArgs e)
{
Image image = new Bitmap(pictureBox1.Image);
pictureBox1.Image = (Bitmap)image.Clone();
var oldImage = pictureBox1.Image;
var p = new Point(image.Width / 2, image.Height);
pictureBox1.Image = null;
pictureBox1.Image = RotateImage(image, p, 1);
pictureBox1.SizeMode = PictureBoxSizeMode.CenterImage;
pictureBox1.Refresh();
if (oldImage != null)
{
oldImage.Dispose();
}
}
private void button2_Click(object sender, EventArgs e)
{
Image image = new Bitmap(pictureBox1.Image);
pictureBox1.Image = (Bitmap)image.Clone();
var oldImage = pictureBox1.Image;
var p = new Point(image.Width / 2, image.Height);
pictureBox1.Image = null;
pictureBox1.Image = RotateImage(image, p, -1);
pictureBox1.SizeMode = PictureBoxSizeMode.CenterImage;
pictureBox1.Refresh();
if (oldImage != null)
{
oldImage.Dispose();
}
}
Now the problem is that when I rotate the image it gets cut. Here is the situation.
I have stretched the picture box and changed the colour of form just for clear picture.
My question is when I have used the statement
pictureBox1.Image = RotateImage(image, p, 1);
Then why is the picture not getting right after postion as this is the same statement used for any situation where we have to assign some image to groupbox. Why is not it working here? I have searched it before but the most of the searches seem irrelevant to me because they use filip function which rotate through 90,180,270. But I want to rotate by some degree maximum upto 10 degree.
Rotating Controls is not something supported by default (links talking about this: link1, link2). The reason why the picture gets cut is because, after the rotation, its width is bigger than the pictureBox1 one; thus a quick solution would be updating its size after the rotation:
pictureBox1.SizeMode = PictureBoxSizeMode.AutoSize; //Adapts the size automatically
or
pictureBox1.Width = image.Width;
pictureBox1.Height = image.Height;
This should be an acceptable solution (there has to be enough free space to account for the new dimensions of the image after being rotated anyway). The other option would be affecting the PictureBox control directly (by affecting the rectangle defining its boundaries, for example) what would be much more difficult.
Well i have come to know that win Forms are not meant for any transformations and rotations.Changing the mode to AutoSize does not make a difference. The best thing for rotation and transformation is WPF.
WPF has a good transformation classes which rotate and transform objects without affecting the object. The object does not get blurred.
You can use This for rotations and transformations.