I am trying to draw a rectangle into a panel and then save this into a bitmap. the screen shows that I have been successful drawing the rectangles but when I view the saved bitmaps, they are empty white rectangles.
System.Drawing.Graphics graphicsObj;
graphicsObj = panel1.CreateGraphics();
Pen myPen = new Pen(System.Drawing.Color.Black, 1);
System.Drawing.Rectangle myRectangle = new System.Drawing.Rectangle(x, y, 50, 50);
greenBrush = new SolidBrush(Color.MediumVioletRed);
graphicsObj.FillRectangle(greenBrush, myRectangle);
graphicsObj.DrawString("SomeString", new System.Drawing.Font
("Arial", 12), Brushes.Blue, myRectangle);
graphicsObj.DrawRectangle(myPen, myRectangle);
string dir = Directory.GetCurrentDirectory();
string img = t.Field<int>("ID").ToString() + ".png";
string total = dir + "\\pics\\" + img;
Bitmap bmp = new Bitmap(panel1.ClientRectangle.Width,
panel1.ClientRectangle.Height);
panel1.DrawToBitmap(bmp, panel1.ClientRectangle);
string dira = Directory.GetCurrentDirectory();
string imga = t.Field<int>("ID").ToString() + "cal.bmp";
string totala = dira + "\\pics\\" + imga;
bmp.Save(totala);
Related
I want to draw black text over with grey opacity PNG file so text is BLACK.
What I am getting is the text is some % of grey:
Even if I use Brushes.Black the text is still grey;
My code is following:
List<string> GenerateDeviceIcon(string backgroundImageFile, string deviceImageFile, string deviceNumber, int deviceID, string saveNewFilePath, string fontName, int fontSize, Brush textColor)
{
var r = new List<string>();
try
{
Image background = Image.FromFile(backgroundImageFile);
Image logo = Image.FromFile(deviceImageFile);
PointF firstLocation = new PointF(2f, 2f);
using (background)
{
using (var bitmap = new Bitmap(background.Width, background.Height))
{
using (var canvas = Graphics.FromImage(bitmap))
{
using (Font arialFont = new Font(fontName, fontSize))
{
canvas.DrawString(deviceNumber, arialFont, textColor, firstLocation);
}
canvas.InterpolationMode = InterpolationMode.HighQualityBicubic;
canvas.DrawImage(background, new Rectangle(0, 0, background.Width, background.Height), new Rectangle(0, 0, background.Width, background.Height), GraphicsUnit.Pixel);
canvas.DrawImage(logo, (bitmap.Width / 2) - (logo.Width / 2), (bitmap.Height / 2) - (logo.Height / 2));
canvas.Save();
}
try
{
var filename = Path.Combine(saveNewFilePath, deviceID.ToString() + ".png");
if (File.Exists(filename))
{
File.Delete(filename);
}
bitmap.Save(filename, System.Drawing.Imaging.ImageFormat.Png);
}
catch (Exception ex)
{
r.Add(ex.Message);
}
}
}
}
catch (Exception ex)
{
r.Add(ex.Message);
}
return r;
}
How to fix it?
Many thanks!
Well I found the bug: dont draw text BEFORE you draw a background!
And I've improved the code so it draws multiple lines of a transport ID.
Enjoy if you need create complex icons in .NET!
Code:
static List<string> GenerateDeviceIcon2(string backgroundImageFile, string deviceImageFile,
string deviceNumber, int deviceID, string saveNewFilePath, string fontName, int fontSize, Color textColor)
{
var r = new List<string>();
try
{
Image background = Image.FromFile(backgroundImageFile);
Image logo = Image.FromFile(deviceImageFile);
PointF firstLocation = new PointF(2f, 2f);
#region Create text as Image with Transparancy
//first, create a dummy bitmap just to get a graphics object
Image img = new Bitmap(1, 1);
Graphics drawingText = Graphics.FromImage(img);
//measure the string to see how big the image needs to be
int maxWidth = background.Width - 2;
var font = new Font(fontName, fontSize, new FontStyle());
SizeF textSize = drawingText.MeasureString(deviceNumber, font, maxWidth);
//set the stringformat flags to rtl
StringFormat sf = new StringFormat
{
//uncomment the next line for right to left languages
//sf.FormatFlags = StringFormatFlags.DirectionRightToLeft;
Trimming = StringTrimming.Word
};
//free up the dummy image and old graphics object
img.Dispose();
drawingText.Dispose();
//create a new image of the right size
img = new Bitmap((int)textSize.Width, (int)textSize.Height);
// drawingText = Graphics.FromImage(img);
#endregion
//create a brush for the text
Brush textBrush = new SolidBrush(textColor);
using (background)
{
using (var bitmap = new Bitmap(background.Width, background.Height))
{
using (var canvas = Graphics.FromImage(bitmap))
{
//Adjust for high quality
canvas.CompositingQuality = CompositingQuality.HighQuality;
canvas.InterpolationMode = InterpolationMode.HighQualityBilinear;
canvas.PixelOffsetMode = PixelOffsetMode.HighQuality;
canvas.SmoothingMode = SmoothingMode.HighQuality;
canvas.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
//paint the background
canvas.Clear(Color.Transparent);
// First - draw a background!
canvas.DrawImage(background, new Rectangle(0, 0, background.Width, background.Height),
new Rectangle(0, 0, background.Width, background.Height), GraphicsUnit.Pixel);
// Second - draw the text in multiple rows over background
canvas.DrawImage(logo, (bitmap.Width / 2) - (logo.Width / 2), (bitmap.Height / 2) - (logo.Height / 2));
// Third - draw the logo over background
canvas.DrawString(deviceNumber, font, textBrush, new RectangleF(0, 0, textSize.Width, textSize.Height), sf);
canvas.Save();
}
try
{
var filename = Path.Combine(saveNewFilePath, deviceID.ToString() + ".png");
if (File.Exists(filename))
{
File.Delete(filename);
}
bitmap.Save(filename, System.Drawing.Imaging.ImageFormat.Png);
}
catch (Exception ex)
{
r.Add(ex.Message);
}
}
}
textBrush.Dispose();
img.Dispose();
}
catch (Exception ex)
{
r.Add(ex.Message);
}
return r;
}
why using this snippet does not draw an image on the screen? there are other commands to draw before this line they work fine. for example, there some rectangle and fill shape command that works.
Graphics imgGB = e.Graphics;
imgGB.DrawImage(
Properties.Resources.logo,
new Rectangle(
new Point(DoorGlassFill.Left, DoorPrimeter.Bottom + Drawing_HandleHeight),
new Size(200,200)));
the whole method is:
//draw door
Graphics DoorGP = e.Graphics;
Rectangle DoorFrame = new Rectangle(new Point(DoorPrimeter.Left + Drawing_LeftDis + Drawing_Off, DoorPrimeter.Top + TopDistance + (2*Drawing_Off)+Drawing_TopBlockHeight), new Size(Drawing_DoorWidth,DoorPrimeter.Height-TopDistance-Drawing_TopBlockHeight-(2*Drawing_Off)));
DoorGP.DrawRectangle(pen, DoorFrame);
Rectangle GP113 = new Rectangle(new Point(DoorFrame.Left+Drawing_GP113,DoorFrame.Top+Drawing_GP113), new Size(DoorFrame.Width-(2*Drawing_GP113),DoorFrame.Height-Drawing_GP113));
DoorGP.DrawRectangle(pen, GP113);
Rectangle DoorGlass = new Rectangle(new Point(GP113.Left+Drawing_GP119,GP113.Top+Drawing_GP119), new Size(GP113.Width-(2*Drawing_GP119),GP113.Height-Drawing_GP119));
Graphics GlassFillGP = e.Graphics;
Rectangle DoorGlassFill = new Rectangle(new Point(GP113.Left + Drawing_GP119, GP113.Top + Drawing_GP119), new Size(GP113.Width - (2 * Drawing_GP119), GP113.Height - (2 * Drawing_GP119)));
GlassFillGP.FillRectangle(new LinearGradientBrush(DoorGlassFill, Color.AliceBlue, Color.LightSkyBlue, 45f), DoorGlassFill);
DoorGP.DrawRectangle(pen, DoorGlass);
Graphics imgGB = e.Graphics;
imgGB.DrawImage(Properties.Resources.logo__sajiran1,new Rectangle(new Point(DoorGlassFill.Left, DoorPrimeter.Bottom + Drawing_HandleHeight),new Size(200,200)));
tried this too:
//draw door
Graphics DoorGP = e.Graphics;
Rectangle DoorFrame = new Rectangle(new Point(DoorPrimeter.Left + Drawing_LeftDis + Drawing_Off, DoorPrimeter.Top + TopDistance + (2*Drawing_Off)+Drawing_TopBlockHeight), new Size(Drawing_DoorWidth,DoorPrimeter.Height-TopDistance-Drawing_TopBlockHeight-(2*Drawing_Off)));
DoorGP.DrawRectangle(pen, DoorFrame);
Rectangle GP113 = new Rectangle(new Point(DoorFrame.Left+Drawing_GP113,DoorFrame.Top+Drawing_GP113), new Size(DoorFrame.Width-(2*Drawing_GP113),DoorFrame.Height-Drawing_GP113));
DoorGP.DrawRectangle(pen, GP113);
Rectangle DoorGlass = new Rectangle(new Point(GP113.Left+Drawing_GP119,GP113.Top+Drawing_GP119), new Size(GP113.Width-(2*Drawing_GP119),GP113.Height-Drawing_GP119));
Graphics GlassFillGP = e.Graphics;
Rectangle DoorGlassFill = new Rectangle(new Point(GP113.Left + Drawing_GP119, GP113.Top + Drawing_GP119), new Size(GP113.Width - (2 * Drawing_GP119), GP113.Height - (2 * Drawing_GP119)));
GlassFillGP.FillRectangle(new LinearGradientBrush(DoorGlassFill, Color.AliceBlue, Color.LightSkyBlue, 45f), DoorGlassFill);
DoorGP.DrawRectangle(pen, DoorGlass);
Bitmap img = Properties.Resources.Handle_Meroni;
Graphics imgGB = e.Graphics;
img.SetResolution(imgGB.DpiX, imgGB.DpiY);
imgGB.DrawImage(img,new Rectangle(new Point(DoorGlassFill.Left, DoorPrimeter.Bottom + Drawing_HandleHeight),new Size(200,200)));
Hi I am using below code and the bar code is generating well but how can I remove text written down to label.
public void generateBarcode(string id)
{
int w = id.Length * 55;
Bitmap oBitmap = new Bitmap(w, 100);
Graphics oGraphics = Graphics.FromImage(oBitmap);
Font oFont = new Font("IDAutomationHC39M", 18);
PointF oPoint = new PointF(2f, 2f);
SolidBrush oBrushWrite = new SolidBrush(Color.Black);
SolidBrush oBrush = new SolidBrush(Color.White);
oGraphics.FillRectangle(oBrush, 0, 0, w, 100);
oGraphics.DrawString("*" + id + "*", oFont, oBrushWrite, oPoint);
System.Web.UI.WebControls.Image imgBarCode = new System.Web.UI.WebControls.Image();
using (System.IO.FileStream fs = System.IO.File.Open(Server.MapPath("~/img/barcodes/") + id + ".jpg", FileMode.Create))
{
oBitmap.Save(fs, System.Drawing.Imaging.ImageFormat.Jpeg);
}
oBitmap.Dispose();
imgbarcode.ImageUrl = "~/img/barcodes/" + id + ".jpg";
}
My bar code is generating as below. Here I need to remove the bar code text as 76
According to this, the font you need to use without text is "IDAutomationC39M". Unfortunately, that's not in the free version.
I am getting a out of memory every time I try to add a picture to a picture box
I have tried doing a dispose at the beginning of it but it still just gives me out of memory when I try to add a image from file
public void water(string path,string oupath)
{
pictureBox1.Image = Image.FromFile(path);
Font myfont = new Font("Times New Roman", 12.0f);
Graphics g = Graphics.FromImage(pictureBox1.Image);
// Calculate the size of the text
string waterString = waterText.Text;
SizeF sz = g.MeasureString(waterString, myfont);
// drawing position (X,Y)
Brush myBrush = new SolidBrush(Color.White);
int X;
int Y;
//Set the drawing position based on the users
//selection of placing the text at the bottom or top of the image
X = (int)(pictureBox1.Image.Width - sz.Width) / 2;
Y = (int)(pictureBox1.Image.Height - sz.Height);
// draw the water mark text
g.DrawString(waterString, myfont, myBrush, new Point(X, Y));
string filename = Path.GetFileName(path);
path = oupath+"/"+filename;
pictureBox1.Image.Save(#"path",ImageFormat.Jpeg);
pictureBox1.Image.Dispose();
}
I am creating a PNG picture, using the Bitmap object, using Drawing.Graphics . I create a Bitmap, insert a background image and draw some strings.
Now, when I save the image on the disk, the files does not have my strings!
I am doing this in ASP.NET MVC, where this is my controllers signature:
[AcceptVerbs(HttpVerbs.Get)]
public string GetNewsletterPicture(string headline, string tagline)
When I don't save the image on the disk and instead returns a FileStreamResult from a MemoryStream, the image looks perfectly.
So there is some problem that when I save the image to the disk, the strings are "forgotten" somehow.
Any ideas?
My code:
ColorConverter converter = new ColorConverter();
Color textColor = (Color)converter.ConvertFromString("#FF58595B");
int width = 598;
int height = 77;
int offSet = 40;
int shadowOffset = 1;
var bmp = new Bitmap(width, height);
using (Graphics g = Graphics.FromImage(bmp))
{
g.Clear(Color.LightGray);
Image backgroundImg = new Bitmap(Server.MapPath("~/Static/Images/bgimg.png"));
g.DrawImage(backgroundImg,0,0);
StringFormat sf= new StringFormat();
sf.Alignment = StringAlignment.Center;
var rectangleTop = new RectangleF(0, 0, width, height);
var rectangleTopShadowHack = new RectangleF(shadowOffset, shadowOffset, width + shadowOffset, height + shadowOffset);
g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
// only show headline and center it
if (!string.IsNullOrEmpty(tagline))
{
var rectangleBottomShadowHack = new RectangleF(shadowOffset, offSet + shadowOffset, width + shadowOffset, height - offSet + shadowOffset);
var rectangleBottom = new RectangleF(0, offSet, width, height - offSet);
g.DrawString(tagline, new Font("Verdana", 18), new SolidBrush(Color.White), rectangleBottomShadowHack, sf);
g.DrawString(tagline, new Font("Verdana", 18), new SolidBrush(textColor), rectangleBottom, sf);
}
else
{
sf.LineAlignment = StringAlignment.Center;
}
g.DrawString(headline, GetFont("Sentinel-Bold", 28, FontStyle.Bold), new SolidBrush(Color.White), rectangleTopShadowHack, sf);
g.DrawString(headline, GetFont("Sentinel-Bold", 28, FontStyle.Bold), new SolidBrush(textColor), rectangleTop, sf);
g.Save();
var fileName = Guid.NewGuid().ToString() + ".png";
var path = Server.MapPath("~/Static/Previews/" + fileName);
bmp.Save(path, ImageFormat.Png);
return fileName;
If in doubt, it is the g.DrawString which is not being saved on the picture.
NEW atttempt (still not working):
[AcceptVerbs(HttpVerbs.Get)]
public string GetNewsletterPicture(string headline, string tagline)
{
ColorConverter converter = new ColorConverter();
Color textColor = (Color)converter.ConvertFromString("#FF58595B");
int width = 598;
int height = 77;
int offSet = 40;
int shadowOffset = 1;
var bmp = new Bitmap(width, height);
using (Graphics g = Graphics.FromImage(bmp))
{
g.Clear(Color.LightGray);
Image backgroundImg = new Bitmap(Server.MapPath("~/Static/Images/bgimg.png"));
g.DrawImage(backgroundImg,0,0);
StringFormat sf= new StringFormat();
sf.Alignment = StringAlignment.Center;
var rectangleTop = new RectangleF(0, 0, width, height);
var rectangleTopShadowHack = new RectangleF(shadowOffset, shadowOffset, width + shadowOffset, height + shadowOffset);
g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
// only show headline and center it
if (!string.IsNullOrEmpty(tagline))
{
var rectangleBottomShadowHack = new RectangleF(shadowOffset, offSet + shadowOffset, width + shadowOffset, height - offSet + shadowOffset);
var rectangleBottom = new RectangleF(0, offSet, width, height - offSet);
g.DrawString(tagline, new Font("Verdana", 18), new SolidBrush(Color.White), rectangleBottomShadowHack, sf);
g.DrawString(tagline, new Font("Verdana", 18), new SolidBrush(textColor), rectangleBottom, sf);
}
else
{
sf.LineAlignment = StringAlignment.Center;
}
g.DrawString(headline, GetFont("Sentinel-Bold", 28, FontStyle.Bold), new SolidBrush(Color.White), rectangleTopShadowHack, sf);
g.DrawString(headline, GetFont("Sentinel-Bold", 28, FontStyle.Bold), new SolidBrush(textColor), rectangleTop, sf);
g.Flush(FlushIntention.Sync);
}
var fileName = Guid.NewGuid().ToString() + ".png";
var path = Server.MapPath("~/Static/Previews/" + fileName);
bmp.Save(path, ImageFormat.Png);
return fileName;
//MemoryStream stm = new MemoryStream();
//bmp.Save(stm,System.Drawing.Imaging.ImageFormat.Png);
//stm.Position = 0;
//return new FileStreamResult(stm, "image/png");
}
I can't tell for sure, but it looks like you might be confusing g.Save() with g.Flush().
You need to call g.Flush(FlushIntention.Sync) instead of g.Save(). You should probably also call bmp.Save() outside of the using block:
var bmp = new Bitmap(width, height);
using (Graphics g = Graphics.FromImage(bmp))
{
//...
g.Flush(FlushIntention.Sync);
}
var fileName = Guid.NewGuid().ToString() + ".png";
var path = Server.MapPath("~/Static/Previews/" + fileName);
bmp.Save(path, ImageFormat.Png)
Save() is used to save the current graphics state so that you can modify it and then restore it later.:
GraphicsState oldState = g.Save();
// Make some changes to the graphics state...
g.Restore(oldState);
Flush() on the other hand, is used to force the graphics object to complete any pending operations. By passing FlushIntention.Sync as a parameter, Flush() won't return until the flushing is complete.