Reputation: 4259
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.
Upvotes: 0
Views: 2425
Reputation: 116670
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 "";
}
}
Upvotes: 2