A generic error occurred in GDI+. at System.Drawing.Image.Save - c#

Hi I am getting this error while saving an Image at the given path
string WriteImage(string data, string imgPath)
{
try
{
data = "*" + data + "*";
Bitmap barcode = new Bitmap(1, 1);
Font threeOfNine = new Font("IDAutomationHC39M", 60, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point);
Graphics graphics = Graphics.FromImage(barcode);
SizeF dataSize = graphics.MeasureString(data, threeOfNine);
barcode = new Bitmap(barcode, dataSize.ToSize());
graphics = Graphics.FromImage(barcode);
graphics.Clear(Color.White);
graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.SingleBitPerPixel;
graphics.DrawString(data, threeOfNine, new SolidBrush(Color.Black), 0, 0);
graphics.Flush();
threeOfNine.Dispose();
graphics.Dispose();
barcode.SetResolution(300, 300);
barcode.Save(imgPath, System.Drawing.Imaging.ImageFormat.Jpeg);
return imgPath.Substring(imgPath.LastIndexOf("\\")+1);
}
catch
{
return "";
}
}
Dont know what i am doing wrong.

As I wrote in my comment, I'm not seeing any problem. The following version of your code outputs information in the event of an error so you can debug it. It also disposes of resources properly:
public static string WriteImage(string data, string imgPath)
{
try
{
data = "*" + data + "*";
using (var dummyBitmap = new Bitmap(1, 1))
using (var threeOfNine = new Font("IDAutomationHC39M", 60, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point))
{
SizeF dataSize;
using (var graphics = Graphics.FromImage(dummyBitmap))
{
dataSize = graphics.MeasureString(data, threeOfNine);
}
using (var barcode = new Bitmap(dummyBitmap, dataSize.ToSize()))
using (var graphics = Graphics.FromImage(barcode))
using (var brush = new SolidBrush(Color.Black))
{
graphics.Clear(Color.White);
graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.SingleBitPerPixel;
graphics.DrawString(data, threeOfNine, brush, 0, 0);
graphics.Flush();
barcode.SetResolution(300, 300);
barcode.Save(imgPath, System.Drawing.Imaging.ImageFormat.Jpeg);
return imgPath.Substring(imgPath.LastIndexOf("\\") + 1);
}
}
}
catch (Exception ex)
{
Debug.WriteLine("Error saving string \"" + data + "\" to a bitmap at location: " + imgPath);
Debug.WriteLine(ex.ToString());
return "";
}
}

Related

Facial Recognition Using c# & EMGU CV Accuracy Problem

I have project code to create a face recognition system using EMGUCV. I have trained the database with 2 people. When the webcam detects those people and able to show the name correctly but the problem is the third person whose do not exist in trained database detect by webcam, it will take the nearest face and display the name on it instead of show "Unknown". How can I improve the accuracy? I have tried to change the threshold value but didn't help. What's going wrong?
MCvFont font = new MCvFont(Emgu.CV.CvEnum.FONT.CV_FONT_HERSHEY_TRIPLEX, 0.6d, 0.6d);
HaarCascade faceDetected;
Image<Bgr, Byte> Frame;
Capture camera;
Image<Gray, byte> result;
Image<Gray, byte> TrainedFace = null;
Image<Gray, byte> grayFace = null;
List<Image<Gray, byte>> trainingImages = new List<Image<Gray, byte>>();
List<string> labels = new List<string>();
List<string> Users = new List<string>();
EigenObjectRecognizer recognizer;
int Count, NumLabels, t;
string name, names = null;
public Form1()
{
InitializeComponent();
PhotoPers.Image = Properties.Resources.EmptyPiC;
//HaarCascade is for face detection
faceDetected = new HaarCascade("haarcascade_frontalface_default.xml");
try
{
string Labelsinfo = File.ReadAllText(Application.StartupPath + "/Faces/Faces.txt");
string[] Labels = Labelsinfo.Split(',');
NumLabels = Convert.ToInt16(Labels[0]);
Count = NumLabels;
string LoadFaces;
// if (result)
// {
// CvInvoke.cvPutText(Frame, name[result.Labels], new Point(face.X - 2, face.Y - 2),
// FontFace.HersheyComplex, 1.0, new Bgr(Color.Orange).MCvScalar);
// CvInvoke.cvRectangle(Frame, face, new Bgr(Color.Green).MCvScalar, 2);
//}
for (int tf = 1; tf < NumLabels + 1; tf++)
{
LoadFaces = "face" + tf + ".bmp";
trainingImages.Add(new Image<Gray, byte>(Application.StartupPath + "/Faces/" + LoadFaces));
labels.Add(Labels[tf]);
}
}
catch (Exception e)
{
}
}
string imgLocation = " ";
private void button1_Click(object sender, EventArgs e)
{
camera = new Capture();
camera.QueryFrame();
Application.Idle += new EventHandler(FrameProcedure);
}
private void BtnSave_Click(object sender, EventArgs e)
{
byte[] images = null;
FileStream Streem = new FileStream(imgLocation, FileMode.Open, FileAccess.Read);
BinaryReader brs = new BinaryReader(Streem);
images = brs.ReadBytes((int)Streem.Length);
if (txtName.Text == "" || txtLName.Text == " " || txtIDNo.Text == " " || cboDepartment.Text == " ")
{
MessageBox.Show("All fields must be fillup!");
}
else
{
Count = Count + 1;
grayFace = camera.QueryGrayFrame().Resize(320, 240, Emgu.CV.CvEnum.INTER.CV_INTER_CUBIC);
MCvAvgComp[][] DetectedFaces = grayFace.DetectHaarCascade(faceDetected, 1.2, 10, Emgu.CV.CvEnum.HAAR_DETECTION_TYPE.DO_CANNY_PRUNING, new Size(20, 20));
foreach (MCvAvgComp f in DetectedFaces[0])
{
TrainedFace = Frame.Copy(f.rect).Convert<Gray, byte>();
break;
}
TrainedFace = result.Resize(100, 100, Emgu.CV.CvEnum.INTER.CV_INTER_CUBIC);
trainingImages.Add(TrainedFace);
labels.Add(txtName.Text);
File.WriteAllText(Application.StartupPath + "/Faces/Faces.txt", trainingImages.ToArray().Length.ToString() + ",");
for (int i = 1; i < trainingImages.ToArray().Length + 1; i++)
{
trainingImages.ToArray()[i - 1].Save(Application.StartupPath + "/Faces/face" + i + ".bmp");
File.AppendAllText(Application.StartupPath + "/Faces/Faces.txt", labels.ToArray()[i - 1] + ",");
}
}
mCon.ConOpen();
string SaveStr = "INSERT INTO tblRegister (FirstName, LastName, IDno, Department, Image)" +
"VALUES(#FirstName, #LastName, #IDno, #Department, #Image)";
SqlCommand myCommand = new SqlCommand(SaveStr, mCon.myCon);
myCommand.Parameters.AddWithValue("#FirstName", txtName.Text);
myCommand.Parameters.AddWithValue("#LastName", txtLName.Text);
myCommand.Parameters.AddWithValue("#IDno", txtIDNo.Text);
myCommand.Parameters.AddWithValue("#Department", cboDepartment.Text);
myCommand.Parameters.AddWithValue("#Image", images);
myCommand.ExecuteNonQuery();
mCon.ConClose();
MessageBox.Show("Data has been Save!");
txtName.Text = " ";
txtLName.Text = " ";
txtIDNo.Text = " ";
cboDepartment.Text = " ";
}
private void PhotoPers_Click(object sender, EventArgs e)
{
}
private void FrameProcedure(object sender, EventArgs e)
{
Users.Add("");
Frame = camera.QueryFrame().Resize(500, 300, Emgu.CV.CvEnum.INTER.CV_INTER_CUBIC);
grayFace = Frame.Convert<Gray, Byte>();
MCvAvgComp[][] facesDetectedNow = grayFace.DetectHaarCascade(faceDetected, 1.2, 10, Emgu.CV.CvEnum.HAAR_DETECTION_TYPE.DO_CANNY_PRUNING, new Size(20, 20));
foreach (MCvAvgComp f in facesDetectedNow[0])
{
result = Frame.Copy(f.rect).Convert<Gray, Byte>().Resize(100, 100, Emgu.CV.CvEnum.INTER.CV_INTER_CUBIC);
Frame.Draw(f.rect, new Bgr(Color.Cyan), 3);
if (trainingImages.ToArray().Length != 0)
{
MCvTermCriteria termCriterias = new MCvTermCriteria(Count, 0.001);
EigenObjectRecognizer recognizer = new EigenObjectRecognizer(trainingImages.ToArray(), labels.ToArray(), 4500, ref termCriterias);
name = recognizer.Recognize(result);
Frame.Draw(string.IsNullOrEmpty(name) ? "UNKNOWN" : name, ref font, new Point(f.rect.X - 2, f.rect.Y - 2), new Bgr(Color.Red));
}
Users.Add("");
}
CameraBox.Image = Frame;
names = "";
Users.Clear();
}
private void TrainImagesFromDir()
{
//string path = Directory.GetCurrentDirectory() + "/Faces/Faces.txt";
//Users.Add("");
//Frame = camera.QueryFrame().Resize(320, 240, Emgu.CV.CvEnum.INTER.CV_INTER_CUBIC);
//grayFace = Frame.Convert<Gray, Byte>();
//MCvAvgComp[][] facesDetectedNow = grayFace.DetectHaarCascade(faceDetected, 1.2, 10, Emgu.CV.CvEnum.HAAR_DETECTION_TYPE.DO_CANNY_PRUNING, new Size(20, 20));
//foreach (MCvAvgComp f in facesDetectedNow[1])
//{
// result = Frame.Copy(f.rect).Convert<Gray, Byte>().Resize(100, 100, Emgu.CV.CvEnum.INTER.CV_INTER_CUBIC);
// Frame.Draw(f.rect, new Bgr(Color.Green), 3);
// if (trainingImages.ToArray().Length != 0)
// {
// MCvTermCriteria termCriterias = new MCvTermCriteria(Count, 0.001);
// EigenObjectRecognizer recognizer = new EigenObjectRecognizer(trainingImages.ToArray(), labels.ToArray(), 1500, ref termCriterias);
// name = recognizer.Recognize(result);
// Frame.Draw(name, ref font, new Point(f.rect.X - 2, f.rect.Y - 2), new Bgr(Color.Red));
}
private void btnUpload_Click(object sender, EventArgs e)
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Filter = "png files(*.png)|*.png|jpg files(*.jpg)|*.jpg|All files (*.*)|*.*";
if (dialog.ShowDialog() == DialogResult.OK)
{
imgLocation = dialog.FileName.ToString();
PhotoPers.ImageLocation = imgLocation;
}
}
}

Getting exception when trying to save an image that was edited locally

I'm trying to edit an image by including a water mark on it. I make my changes using Graphics and when I try to save the file it throws me an exception Message:"A generic error occurred in GDI+."
Below is my code:
public static void Test()
{
try
{
Bitmap bmpPic = new Bitmap(Image.FromFile("Desktop/cropped/cropped/croppedsent1386.jpeg"));
using (Graphics g = Graphics.FromImage(bmpPic))
{
Brush brush = new SolidBrush(Color.FromArgb(80, 255, 255, 255));
Point postionWaterMark = new Point((bmpPic.Width / 6), (bmpPic.Height / 2));
g.DrawString("Identifid", new System.Drawing.Font("Arial", 30, FontStyle.Bold, GraphicsUnit.Pixel), brush, postionWaterMark);
}
string filepath = "Desktop/cropped/cropped/croppedsent1386.jpeg";
bmpPic.Save(filepath, ImageFormat.Jpeg);
}
catch(Exception ex)
{
Console.WriteLine(ex);
}
Console.WriteLine("End of test ");
}
-Stack Trace-
StackTrace " at System.Drawing.SafeNativeMethods.Gdip.CheckStatus(Int32 status)\r\n at System.Drawing.Image.Save(String filename, ImageCodecInfo encoder, EncoderParameters encoderParams)\r\n at System.Drawing.Image.Save(String filename, ImageFormat format)\r\n at ConsoleWatermark.Program.Test() in C:\\Users\\xavie\\source\\repos\\Samples\\ConsoleWatermark\\Program.cs:line 49"
I'm stumped as to why this is failing as I have permissions to edit files .
Error appears because you trying to overwrite (when bmpPic.Save()) same image file, which you already loaded as Bitmap. Until Bitmap wouldn't be disposed - file would be locked by it. To solve, you should save new watermarked image to an other new file:
string filepath = ".../croppedsent1386_WATERMARKED.jpeg"; // <--- New file
bmpPic.Save(filepath, ImageFormat.Jpeg);
Complete version (with few notations):
static void Main(string[] args)
{
try
{
// Source image file
string imageFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), "myImage.png");
// Add "using" to bitmap too for proper disposage and to release file after completion
using (Bitmap bitmap = new Bitmap(Image.FromFile(imageFile)))
{
using (Graphics g = Graphics.FromImage(bitmap))
{
Brush brush = new SolidBrush(Color.FromArgb(80, 255, 255, 255));
Point watermarkPosition = new Point(bitmap.Width / 6, bitmap.Height / 2);
g.DrawString("IDENTIFID", new Font("Arial", 30, FontStyle.Bold, GraphicsUnit.Pixel), brush, watermarkPosition);
// Save to a new file
string newImageFile = imageFile.Replace("myImage.png", "myImage_WATERMARKED.png");
bitmap.Save(newImageFile, ImageFormat.Png);
}
}
Console.WriteLine("Image saved!");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message + "\n\nStack trace:\n" + ex.StackTrace);
}
Console.ReadKey();
}

Read text from screenshot

I'm using selenium to go to x website and take screenshot
public static void TakeScreenshot(IWebDriver driver, int x, int y, int width, int height)
{
var name =
$#"{Environment.GetFolderPath(Environment.SpecialFolder.Desktop)}\{"screenshots"}\{Guid.NewGuid()}.{
ScreenshotImageFormat.Png
}";
Rectangle rect = new Rectangle(x, y, width, height);
Screenshot screenshot = ((ITakesScreenshot)driver).GetScreenshot();
var bitmapScreen = new Bitmap(new MemoryStream(screenshot.AsByteArray));
var croppedArea = new Rectangle(rect.Location, rect.Size);
bitmapScreen.Clone(croppedArea, bitmapScreen.PixelFormat).Save(name);
}
and after saving that I'm trying to read text from that image using tesseract
var testImagePath = #".\Content\300.png";
var dataPath = #".\tessdata";
try
{
using (var tEngine = new TesseractEngine(dataPath, "eng", EngineMode.Default)) //creating the tesseract OCR engine with English as the language
{
using (var img = Pix.LoadFromFile(testImagePath)) // Load of the image file from the Pix object which is a wrapper for Leptonica PIX structure
{
using (var page = tEngine.Process(img)) //process the specified image
{
var text = page.GetText(); //Gets the image's content as plain text.
Console.WriteLine(text); //display the text
Console.WriteLine(page.GetMeanConfidence()); //Get's the mean confidence that as a percentage of the recognized text.
Console.ReadLine();
}
}
}
}
catch (Exception e)
{
Console.WriteLine("Unexpected Error: " + e.Message);
}
but I'm getting that dummy text:
so I tried to rescale that image
bitmapScreen.SetResolution(300, 300);
as I found here
but result is the same

Random "Parameter is not valid" error with bitmap

The method below takes in some FileInfo of a certain pdf file and will then proceed to convert that pdf into bitmaps. This method works randomly it seems. Sometimes it will finish with no problems, other times it will fail at the using (Bitmap bmp = image.ToBitmap()) part. Once it hits that line I get a "Parameter is not valid" error. I have no clue how to fix this random error nor dissect it even further. Any help would be appreciated
static void ParseOutEachBitmap(FileInfo[] pdfFiles)
{
string BmpPath = "C:\\temp\\bmps\\";
if (!Directory.Exists(BmpPath))
{
Directory.CreateDirectory(BmpPath);
}
using (MagickImageCollection images = new MagickImageCollection())
{
MagickReadSettings settings = new MagickReadSettings();
settings.Density = new MagickGeometry(300, 300);
for (int p = 0; p < pdfFiles.Count(); p++)
{
images.Read(#"c:\temp\pdfs\" + pdfFiles[p].Name, settings);
int pageNumber = 1;
string pdfName = pdfFiles[p].Name;
foreach (MagickImage image in images)
{
using (Bitmap bmp = image.ToBitmap())
{
Console.WriteLine("PDF Filename: " + pdfName);
Console.WriteLine("Page Number: " + pageNumber + " of " + images.Count);
pageNumber++;
using (tessnet2.Tesseract tessocr = new tessnet2.Tesseract())
{
tessocr.GetThresholdedImage(bmp, System.Drawing.Rectangle.Empty).Save("c:\\temp\\bmps\\" + Guid.NewGuid().ToString() + ".bmp");
}
}
}
}
}
}

How to display ✔ in PDF using iTextSharp?

I am trying to display the "✔" character in a PDF using iTextSharp. However the character won't show up on the created PDF. Please help me on this.
Phrase phrase = new Phrase("A check mark: ");
Font zapfdingbats = new Font(Font.FontFamily.ZAPFDINGBATS);
phrase.Add(new Chunk("\u0033", zapfdingbats));
phrase.Add(" and more text");
document.Add(phrase);
Font Wingdings prints this character instead of "o".
You need to connect this font to your application, then apply this font to letter and embedd the font into pdf for compatibility.
This is my function (not cleaned) that I have used in one of my projects a while back.
please clean it up, but it has some essential features that you need. (I had my custom fonts (font1.ttf and font2.ttf) copied in the project directory)
I am hoping it will help you.
public void StartConvert(String originalFile, String newFile)
{
Document myDocument = new Document(PageSize.LETTER);
PdfWriter.GetInstance(myDocument, new FileStream(newFile, FileMode.Create));
myDocument.Open();
int totalfonts = FontFactory.RegisterDirectory("C:\\WINDOWS\\Fonts");
iTextSharp.text.Font content = FontFactory.GetFont("Pea Heather's Handwriting", 13);//13
iTextSharp.text.Font header = FontFactory.GetFont("assign", 16); //16
BaseFont customfont = BaseFont.CreateFont(#"font1.ttf", BaseFont.CP1252, BaseFont.EMBEDDED);
Font font = new Font(customfont, 13);
string s = " ";
myDocument.Add(new Paragraph(s, font));
BaseFont customfont2 = BaseFont.CreateFont(#"font2.ttf", BaseFont.CP1252, BaseFont.EMBEDDED);
Font font2 = new Font(customfont2, 16);
string s2 = " ";
myDocument.Add(new Paragraph(s2, font2));
try
{
try
{
using (StreamReader sr = new StreamReader(originalFile))
{
// Read and display lines from the file until the end of
// the file is reached.
String line;
while ((line = sr.ReadLine()) != null)
{
String newTempLine = "";
String[] textArray;
textArray = line.Split(' ');
newTempLine = returnSpaces(RandomNumber(0, 6)) + newTempLine;
int counterMax = RandomNumber(8, 12);
int counter = 0;
foreach (String S in textArray)
{
if (counter == counterMax)
{
Paragraph P = new Paragraph(newTempLine + Environment.NewLine, font);
P.Alignment = Element.ALIGN_LEFT;
myDocument.Add(P);
newTempLine = "";
newTempLine = returnSpaces(RandomNumber(0, 6)) + newTempLine;
}
newTempLine = newTempLine + returnSpaces(RandomNumber(1, 5)) + S;
counter++;
}
Paragraph T = new Paragraph(newTempLine, font2);
T.Alignment = Element.ALIGN_LEFT;
myDocument.Add(T);
}
}
}
catch (Exception e)
{
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
}
catch (DocumentException de)
{
Console.Error.WriteLine(de.Message);
}
catch (IOException ioe)
{
Console.Error.WriteLine(ioe.Message);
}
try
{
myDocument.Close();
}
catch { }
}
Define font at master
protected static Font ZAPFDINGBATS(float size, bool bold = false, bool italic = false, bool underline = false, Color color = null)
=> new(StandardFonts.ZAPFDINGBATS, size, bold, italic, underline, color);
declare font
private readonly Font ZapFont = ZAPFDINGBATS(10, bold: false, color: ColorConstants.BLACK);
private readonly Action<Cell> _cellRight = cell => cell.RemoveBorder().SetTextAlignment(TextAlignment.RIGHT);
Use
document.AddTable(
columns: new float[1]
{
100
},
table => table.SetWidth(document.GetPageEffectiveArea(PageSize).GetWidth())
.SetMargins(0, 0, 0, 0)
.AddCell(model.IsTrue ? "4" : "o", ZapFont, _cellRight );
This worked for me:
pdfStamper.FormFlattening = true;

Categories

Resources