Graphics.DrawString doesn't work - c#

I want to draw a text over a PictureBox in a foreach loop. This is the code that is responsible for rendering(GG is a PictureBox that is currently in the loop)
if (GG != null)
{
((PictureBox)GG).Image = (Image)obj;
using (Graphics g = ((PictureBox)GG).CreateGraphics()) {
g.DrawString(i["amount"].ToString(), kryptonRichTextBox1.Font,
new SolidBrush(Color.Gold), new Point(16, 18));
}
}
But sadly, the text is not rendered. If I comment out the
//((PictureBox)GG).Image = (Image)obj;
line, it does work! I have no idea how to get it to work.
I wanted to use the TextRenderer, but I don't know how to get an IDeviceContext of a control(and all examples I see on the internet use PaintEventArgs.Graphics in Paint event).
Also, if this is relevant, the GG PictureBox is a child of another picturebox, and has a transparent background.
I tried to refresh the box after invalidating, the working code:
if (GG != null)
{
((PictureBox)GG).Image = (Image)obj;
((PictureBox)GG).Invalidate();
((PictureBox)GG).Refresh();
using (Graphics g = ((PictureBox)GG).CreateGraphics()) {
g.DrawString(i["amount"].ToString(), kryptonRichTextBox1.Font,
new SolidBrush(Color.Gold), new Point(16, 18));
}
}

You modified the image content but the PictureBox is completely unaware of that. You didn't reassign its Image property. You will need to tell it that it needs to redraw the image as displayed on the screen. Add this line of code:
GG.Invalidate();

Just draw on a Bitmap and show it in the PictureBox:
// A new bitmap with the same size as the PictureBox
var bitmap = new Bitmap(pictureBox.Width, pictureBox.Height);
//Get the graphics objectm which we can use to draw
var graphics = Graphics.FromImage(bitmap);
//Draw stuff
graphics.DrawString(i["amount"].ToString(), kryptonRichTextBox1.Font,
new SolidBrush(Color.Gold), new Point(16, 18));
//Show the bitmap with graphics image in the PictureBox
pictureBox.Image = bitmap;

Image digidashboard = new Bitmap(Properties.Resources.digidashboard);
//using (Graphics g = ((PictureBox)pictureBoxDashboard).CreateGraphics())
//{
// g.DrawString("80.00", this.Font, new SolidBrush(Color.Red), 3, 6);
// pictureBoxUnlock.Image = digidashboard;
// pictureBoxDashboard.Invalidate();
//}
Graphics g = Graphics.FromImage(digidashboard);
g.DrawString("80.00", this.Font, new SolidBrush(Color.Red), 3, 6);
pictureBoxDashboard.Image = digidashboard;
According to StevenHouben's answer, I paste my C# version. It works fine. Thanks #StevenHouben.

Related

Drawing over image

I'm trying to draw a rectangle over an image, the rectangle is drawn but the image disappears.
My code:
private void button12_Click(object sender, EventArgs e)
{
currentBitmap = (Bitmap)pictureBox1.Image;
Bitmap temp1 = new Bitmap(currentBitmap.Height, currentBitmap.Width);
Bitmap bmap = (Bitmap)temp1.Clone();
Graphics gr = Graphics.FromImage(bmap);
Pen pen = new Pen(Color.Red);
gr.DrawRectangle(pen, 120, 120, 100, 100);
currentBitmap = (Bitmap)bmap.Clone();
pictureBox1.Image = currentBitmap;
}
Put your drawing methods inside the pictureBox1 onPaint Method. Then you call that using
pictureBox1.Paint += picturebox1_OnPaint;
I fixed this.
It was an error on my code which I didnt realize, i was just taking the width and height of the picturebox instead of the image data.
I changed
Bitmap temp1 = new Bitmap(currentBitmap.Height, currentBitmap.Width);
To
Bitmap temp1 = new Bitmap(pictureBox1.Image);
This is likely due to the fact that your image is set in pictureBox1. Try making a new pictureBox to overlay the old one:
pictureBox1 = image itself
pictureBox2 = bitmap
Good luck!

split image to multiple image from the bottom up

I have a picture I want to print, but it's too big for one page
so i have decided to split it into multiple images
i have tried a method, but now im using this (Talha Irfan answer)
i also tried the other solutions there but those didnt worked as well
(ex. bm.Clone(rec, bm.PixelFormat);)
and here's my code(this is on non-form class)
Bitmap bm = new Bitmap(frmPrint.Width, frmPrint.Height);
Rectangle rec = new Rectangle(0, 200, 576, 300);
Bitmap bitmap = cropImg(bm, rec);
frmPrint.DrawToBitmap(bitmap, rec);
frmPrint._img = bitmap;
frmPrint.setImage();
and setImage function(on some form)
public void setImage()
{
pictureBox3.BackgroundImage = _img;
this.ShowDialog();
}
and cropImg is the same as cropAtRect
the below shows the original image (on the left)
the wanted result in the blue rectangle
and the actual result on the right
PS
my actual image size is (height = 698, wifht = 576)
Edit - as suggested below
on non-form class
Rectangle cropRect = new Rectangle(0, 0, 576, 698);
Bitmap target = new Bitmap(cropRect.Width, cropRect.Height, bm.PixelFormat);
frmPrint.setImage(bm, target, cropRect);
target.Dispose();
at form class
public void setImage(Bitmap src, Bitmap target, Rectangle cropRect)
{
pictureBox3.Visible = false;
using (Graphics g = Graphics.FromImage(target))
{
g.DrawImage(src, new Rectangle(pictureBox3.Location.X, pictureBox3.Location.Y, target.Width, target.Height),
cropRect,
GraphicsUnit.Pixel);
}
this.ShowDialog();
}
Control.DrawToBitmap will always try to draw the whole control or form and will always start at the top. The parameter:
targetBounds
Type: System.Drawing.Rectangle
The bounds within which the control is rendered.
as the name implies, sets the target, not the source rectangle. Hence the white space above your result.
Move the line before cropping with a rectangle that holds the full area, maybe like this:
DrawToBitmap(bm, ClientRectangle);
and then crop the lower part as before..
Note that the cropping trick from your link will not work for DrawToBitmap; using a rectangle with a negative offset will cause a parameter exception.
Btw: to safely dispose of a Bitmap in a PictureBox use this:
Bitmap dummy = (Bitmap )somePictureBox.Image;
somePictureBox.Image = null;
if (dummy != null) dummy.Dispose;
And, indeed, the answer by ChrisJJ in the link leaks the Graphics object.
Update:
Since you seem to have lost control over the various changes and suggestions, here is the minimal code change from the original post:
Bitmap bm = new Bitmap(frmPrint.ClientWidth, frmPrint.ClientHeight);
DrawToBitmap(bm, frmPrint.ClientRectangle);
Rectangle rec = new Rectangle(0, 200, 576, 300);
Bitmap bitmap = cropImg(bm, rec);
frmPrint._img = bitmap;
frmPrint.setImage();
With:
public void setImage()
{
Bitmap dummy = pictureBox3.BackgroundImage;
pictureBox3.BackgroundImage = null;
if (dummy != bnull) dummy.Dispose();
pictureBox3.BackgroundImage = _img;
this.ShowDialog();
}
In the cropImg function add a g.Dispose before returning.

How to save graphics created on a PictureBox?

In c# and Visual Studio Windows forms I have loaded an image into a picture box (pictureBox2) and then cropped it and show in another picture box (pictureBox3).
Now I want to save what is inside pictureBox3 as an image file.
How can I do this?
private void crop_bttn_Click(object sender, EventArgs e)
{
Image crop = GetCopyImage("grayScale.jpg");
pictureBox2.Image = crop;
Bitmap sourceBitmap = new Bitmap(pictureBox2.Image,
pictureBox2.Width, pictureBox2.Height);
Graphics g = pictureBox3.CreateGraphics();
g.DrawImage(sourceBitmap, new Rectangle(0, 0,
pictureBox3.Width, pictureBox3.Height), rectCropArea, GraphicsUnit.Pixel);
sourceBitmap.Dispose();
}
Never use control.CreateGraphics! Either draw into a Bitmap bmp using a Graphics g = Graphics.FromImage(bmp) or in the Paint event of a control, using the e.Graphics parameter..
Here is a cropping code that draws into a new Bitmap and that makes use of your controls etc but changes a few things:
It uses a Graphics object that is created from a new Bitmap
It make use of using clauses to make sure it won't leak
It takes the size of the pictureBox3.ClientSize so it won't include any borders..
private void crop_bttn_Click(object sender, EventArgs e)
{
Image crop = GetCopyImage("grayScale.jpg");
pictureBox2.Image = crop;
Bitmap targetBitmap = new Bitmap(pictureBox3.ClientSize.Width,
pictureBox3.ClientSize.Height);
using (Bitmap sourceBitmap = new Bitmap(pictureBox2.Image,
pictureBox2.ClientSize.Width, pictureBox2.ClientSize.Height))
{
using (Graphics g = Graphics.FromImage(targetBitmap))
{
g.DrawImage(sourceBitmap, new Rectangle(0, 0,
pictureBox3.ClientSize.Width, pictureBox3.ClientSize.Height),
rectCropArea, GraphicsUnit.Pixel);
}
}
if (pictureBox3.Image != null) pictureBox3.Image.Dispose();
pictureBox3.Image = targetBitmap;
targetBitmap.Save(somename, someFormat);
}
The alternative would be to..:
move all your code to the Paint event
replace the Graphics g = pictureBox3.CreateGraphics(); be Graphics g = e.Graphics;
insert these two lines to the click event:
Bitmap targetBitmap = new Bitmap(pictureBox3.ClientSize.Width,
pictureBox3.ClientSize.Height);
pictureBox3.DrawToBitmap(targetBitmap, pictureBox3.ClientRectangle);
The method PictureBox.CreateGraphics() should not be used unless you know what you are doing because it can cause some not-so-obvious problems. For example, in you scenario, the image in pictureBox3 will disappear when you minimize or resize the window.
A better way is to draw to a bitmap, which you also can save:
var croppedImage = new Bitmap(pictureBox3.Width, pictureBox3.Height);
var g = Graphics.FromImage(croppedImage);
g.DrawImage(crop, new Point(0, 0), rectCropArea, GraphicsUnit.Pixel);
g.Dispose();
//Now you can save the bitmap
croppedImage.Save(...);
pictureBox3.Image = croppedImage;
Btw, please use more reasonable variable names, especially for pictureBox1..3.

drawing on image of a picturebox c#

Hello i am in problem with drawing in picturebox. I am trying to draw over a picturebox. picturebox contains an image.I draw a sine wave using drawline method. when the wave reaches the end of the width of picturebox then i use
g.Clear(pictureBox1.BackColor);
this clears the wave over the picturebox.But the problem is it also clears the image of the picturebox.I want draw a wave over a image and then clears it when it reaches the picturebox.width and again starts from the initial position. please help!
Graphics g;
g = pictureBox1.CreateGraphics();
g.DrawLine(System.Drawing.Pens.Crimson, ti, old_gval1, ti + trackBar1.Value, gval1);
usb.SpecifiedDevice.SendData(OUTBuffer);
old_gval1 = gval1;
ti = ti + trackBar1.Value;
if (ti > pictureBox1.Width) {
ti = 0;
g.Clear(pictureBox1.BackColor);
g.DrawLine(System.Drawing.Pens.Gray, 0, ((pictureBox1.Height - 1) - (gnd_val) * ((pictureBox1.Height - 10) / 1023f)), pictureBox1.Width, ((pictureBox1.Height - 1) - (gnd_val) * ((pictureBox1.Height - 10) / 1023f)));
g.DrawLine(System.Drawing.Pens.Gray, pictureBox1.Width / 2, 0, pictureBox1.Width/ 2,pictureBox1.Height);
}
You can use a special feature of the PictureBox:
It has not only the Image everybody is using but also a BackgroundImage usually overlooked.
You can paint freely on the Image and still keep a BackgroundImage untouched.
Obviosly you need to paint on a transparent Bitmap.
Here is some code:
// load the background image:
this.pictureBox1.BackgroundImage = new Bitmap(yourImageFileName);
// prepare the image:
Bitmap bmp = new Bitmap(pictureBox1.Width, pictureBox1.Height);
using (Graphics g = Graphics.FromImage(bmp) )
{
g.FillRectangle(Brushes.Transparent, new Rectangle(Point.Empty, bmp.Size) );
}
pictureBox1.Image = bmp;
Now paint stuff:
Random R = new Random();
private void button1_Click(object sender, EventArgs e)
{
Image bmp = pictureBox2.Image;
using (Graphics g = Graphics.FromImage(bmp))
{
g.DrawEllipse(Pens.Blue, R.Next(33), R.Next(33), R.Next(500), R.Next(500));
g.DrawEllipse(Pens.Red, R.Next(33), R.Next(33), R.Next(500), R.Next(500));
g.DrawEllipse(Pens.White, R.Next(33), R.Next(33), R.Next(500), R.Next(500));
}
pictureBox2.Image = bmp;
}
When your plotting has reached the right edge you would use a call to FillRectangle(Brushes.Transparent,.. to clear the foreground image and reset your x value.
Sounds like the cheapest solution to your problem.
You have two options here.
You could create your graphics from the image using Graphics.FromImage, then assign the image from that to the picture box.
Draw the image into your new Graphics object using Graphics.DrawImage.
It sounds like the latter might be a bit more appropriate for you, since you aren't actually altering the in-memory image. So every time you clear the Graphics instance, just draw in the Image.

C# redaction drawing on Image

Whats going on is i need to draw a black rectangle over the image. I have to load a tif and then show a blackbox over it. I was helped with some code but i continously got the error: A Graphics object cannot be created from an image that has an indexed pixel format.
So i had to read it in to bit format, but when i display the box it resizes the box wierd. And completly displays the the picture box in all black nothing of the original image. if someone could help me where i'm going wrong that would be awesome.
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));
}
}
I'm not sure how I can make this clearer. Whats happening is I have a tif in a unsupported format. So I have to change it to a Bitmap so I can actually draw a rectangle on it. Then I need to display this redacted image (the original with the redaction) in a picturebox. Whats going on with the code above, is once it's completed, all it displays is a blackbox with no original image.
I believe i ran something about using a Bitmap from stream and then closing the stream. Anybody familiar with this?
Thanks to all the help from STO members!! heres the correct code for redacting images if you encounter the error "A Graphics object cannot be created from an image that has an indexed pixel format.".
if you're given the redacted starting points (obviously you have to make the Regex work to your situation):
//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
}
}
Instead of
Bitmap newImage = new Bitmap(original.Width, original.Height);
you want
Bitmap newImage = new Bitmap(original);
This will make your newImage start with the contents of original.
The difference will be that you will end up with newImage.PixelFormat == PixelFormat.Format32bppArgb, while I'm assuming original.PixelFormat == PixelFormat.Format1bppIndexed.
With PixelFormat.Format32bppArgb, you can create a Graphics object; you cannot with PixelFormat.Format1bppIndexed.
This should work for you:
original = (Bitmap)System.Drawing.Image.FromFile(coveted, true);
using (Graphics g = Graphics.FromImage(original))
{
using (SolidBrush brush = new SolidBrush(Color.Black))
{
g.FillRectangle(brush, new Rectangle(x1value, y1value, x3value, y3value));
}
}
pictureBox1.Image = original;
You aren't drawing the original image on the newImage.
To do so :
g.DrawImageUnscaled(original, 0, 0);
Also, I would do it as follows, I think it works better drawing in RAM, and then showing it to screen. Perhaps I'm wrong though.
using (Graphics g = Graphics.FromImage(newImage))
{
g.DrawImageUnscaled(original, 0, 0);
using (SolidBrush brush = new SolidBrush(Color.Black))
{
g.FillRectangle(brush, new Rectangle(x1value, y1value, x3value, y3value));
}
}
pictureBox1.Image = newImage;
I haven't tested the code above.. good luck though.

Categories

Resources