How to delete image file from specific folder path? - c#

i created two images 1st one is Barcode Image and 2nd is SkuImage after that I Merged It in 3rd image(final Image). after Successfully Merged
i want to delete Barcode Image and Sku image from Specific folder, but when i try to delete image file it Gives me a error i.e "The process cannot access the file \Path\ because it is being used by another process".
before deleting i disposed the image like this "SkuImage.Dispose()" but it doesnt delete. How do i delete this?
barcodeImage = b.Encode(BarcodeLib.TYPE.CODE128, "001234", Color.Black, Color.White, 113, 18);
Bitmap SkuImage = new Bitmap(113, 18, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
RectangleF rectf = new RectangleF(10, 5, 113, 18);
Graphics graphics = Graphics.FromImage(SkuImage);
// SkuImage.SetPixel(10,10,Color.Blue);
graphics.DrawString(StringToEncode, new Font("Arial", 4), Brushes.Black, rectf);
b.SaveImage(MemStream, savetype);
MemStream.Close();
barcodeImage.Dispose();
SkuImage.Save(imgSkupath);
SkuImage.Dispose();
g.Clear(Color.White); //here change BG color of Image
g.DrawImage(Image.FromFile("E:\\" + #"Pankaj/BarcodeDemo/BarcodeDemo/BarcodeImage/" + Filename), new Point(15, 15));
g.DrawImage(Image.FromFile("E:\\" + #"Pankaj/BarcodeDemo/BarcodeDemo/BarcodeImage/Sku.jpg"), new Point(25, 30));
img.Save("E:\\" + #"Pankaj/BarcodeDemo/BarcodeDemo/BarcodeImage/FinalImage.jpeg", ImageFormat.Jpeg);
File.Delete("E:\\" + #"Pankaj/BarcodeDemo/BarcodeDemo/BarcodeImage/Sku.jpg");
File.Delete("E:\\" + #"Pankaj/BarcodeDemo/BarcodeDemo/BarcodeImage/" + Filename);

You should dispose every class that implements IDisposable. Then you can delete the image file.

string Filename = "Barcodeimage" + i + ".jpeg";
string imgsavepath = "E:\\Pankaj\\BarcodeDemo\\BarcodeDemo\\BarcodeImage\\" + "BarcodeImg.jpeg";
string imgSkupath = "E:\\Pankaj\\BarcodeDemo\\BarcodeDemo\\BarcodeImage\\" + "Sku.jpeg";
BarcodeLib.SaveTypes savetype = BarcodeLib.SaveTypes.UNSPECIFIED;
savetype = BarcodeLib.SaveTypes.JPG;
System.IO.FileStream MemStream = new FileStream(imgsavepath, FileMode.Create, FileAccess.Write);
System.Drawing.Image barcodeImage = null;
//Bitmap FinalImage = null;
BarcodeLib.Barcode b = new BarcodeLib.Barcode();
//b.IncludeLabel = true;
b.LabelFont = new Font("Arial", 5);
string sku = "SKU:VXN4214IN";
string StringToEncode = "16280/" + i + ' ' + sku;
Image img = new Bitmap(130, 50); //final image
Graphics g = Graphics.FromImage(img);
barcodeImage = b.Encode(BarcodeLib.TYPE.CODE128, "001234", Color.Black, Color.White, 113, 18);
Bitmap SkuImage = new Bitmap(113, 18, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
RectangleF rectf = new RectangleF(10, 5, 113, 18);
Graphics graphics = Graphics.FromImage(SkuImage);
// SkuImage.SetPixel(10,10,Color.Blue);
graphics.DrawString(StringToEncode, new Font("Arial", 4), Brushes.Black, rectf);
b.SaveImage(MemStream, savetype);
MemStream.Close();
barcodeImage.Dispose();
SkuImage.Save(imgSkupath);
graphics.Dispose();
SkuImage.Dispose();
g.Clear(Color.White); //here change BG color of Image
System.IO.FileStream fileStream1 = new FileStream("E:\\" + #"Pankaj/BarcodeDemo/BarcodeDemo/BarcodeImage/BarcodeImg.jpeg", FileMode.Open, FileAccess.Read);
System.IO.FileStream fileStream2 = new FileStream("E:\\" + #"Pankaj/BarcodeDemo/BarcodeDemo/BarcodeImage/Sku.jpeg", FileMode.Open, FileAccess.Read);
g.DrawImage(Image.FromStream(fileStream1), new Point(15, 15));
g.DrawImage(Image.FromStream(fileStream2), new Point(25, 30));
// g.DrawImage(Image.FromFile("E:\\" + #"Pankaj/BarcodeDemo/BarcodeDemo/BarcodeImage/" + Filename), new Point(15, 15));
//g.DrawImage(Image.FromFile("E:\\" + #"Pankaj/BarcodeDemo/BarcodeDemo/BarcodeImage/Sku.jpg"), new Point(25, 30));
img.Save("E:\\" + #"Pankaj/BarcodeDemo/BarcodeDemo/BarcodeImage/"+Filename, ImageFormat.Jpeg);
fileStream1.Close();
fileStream2.Close();
g.Dispose();
File.Delete("E:\\" + #"Pankaj/BarcodeDemo/BarcodeDemo/BarcodeImage/Sku.jpeg");
File.Delete("E:\\" + #"Pankaj/BarcodeDemo/BarcodeDemo/BarcodeImage/BarcodeImg.jpeg");

Dim _strImagePath = ""
Dim _strImageName = "image.jpg"
'Get the path
_strImagePath = "YOUR_IMAGE_PATH"
'Delete the image physically
Dim strImageName As New FileInfo(_strImagePath & _strImageName)
If strImageName.Exists Then
strImageName.Delete()
End If

Related

how create pdf after image Draw c#

I'm working with PdfSharp to create some pdf files
I am trying to write an image after that save pdf and force download user
but after show box to download and open file, pdf was empty
var foo = new PrivateFontCollection();
foo.AddFontFile(HttpContext.Current.Server.MapPath("~/assets/css/base/fonts/Coustom.ttf"));
var Font_6 = new Font((FontFamily)foo.Families[0], 6f);
StringFormat rf = new StringFormat();
rf.LineAlignment = StringAlignment.Far;
rf.Alignment = StringAlignment.Far;
Brush _RedColor = new SolidBrush(Color.FromArgb(63, 110, 123));
System.Drawing.Image imgBackground = System.Drawing.Image.FromFile(Server.MapPath("../assets/EmptyDoc/Letterhead-FA-A4.jpg"));
int _X = 2300;
int _Y = 450;
using (Graphics graphics = Graphics.FromImage(imgBackground))
{
graphics.DrawString("TEST", Font_6, _RedColor, new PointF((_X - 40), (_Y)), rf);
}
imgBackground.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Png);
PdfDocument document = new PdfDocument();
PdfPage page = document.AddPage();
XGraphics gfx = XGraphics.FromPdfPage(page);
byte[] fileContents = null;
MemoryStream memoryStream = new MemoryStream();
document.Save(memoryStream, true);
fileContents = memoryStream.ToArray();
Response.Clear();
Response.ContentType = "application/force-download";
Response.AddHeader("content-disposition", "attachment; filename=TEST.pdf");
Response.BinaryWrite(fileContents);
With PdfSharp, you can add an image as the following :
using (FileStream stream = new FileStream(pngFile, FileMode.Open, FileAccess.ReadWrite, FileShare.Read))
{
XImage image = XImage.FromStream(stream);
XGraphics graphics = XGraphics.FromPdfPage(this.currentPage);
graphics.DrawImage(image, 0 , 0, 200, 100);
}
you just need to replace pngFile by the full path of your drawing file.
Edit :
After reading your code, you could try to add this after the line XGraphics gfx = XGraphics.FromPdfPage(page); :
XImage image = XImage.FromStream(strm);
XGraphics graphics = XGraphics.FromPdfPage(page);
graphics.DrawImage(image, 0 , 0, 200, 100);
Then replace
imgBackground.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Png);
by
MemoryStream strm = new MemoryStream();
imgBackground.Save(strm, System.Drawing.Imaging.ImageFormat.Png);
Seems the function doesn't accept your Stream, so try with a MemoryStream

Barcode ASP.NET C# Issue

I have this code for generating barcode when page is loaded.(code below) txtBarcodeBlack.Text content is pulled from SQL Server Database as varchar.
I have a button submit that will do another process like saving the txtBarcodeBlack.text to database. My problem is when I press the button, it gives me this Problem please help. I'm stuck for 2 days.
private void loadBlackBarcode() {
//barcode black
//txtBarcodeBlack.Text = vBarcodeBlack;
string barCodeBlack = txtBarcodeBlack.Text;
System.Web.UI.WebControls.Image imgBarCodeBlack = new System.Web.UI.WebControls.Image();
using (Bitmap bitMap = new Bitmap(barCodeBlack.Length * 40, 80))
{
using (Graphics graphics = Graphics.FromImage(bitMap))
{
Font oFont = new Font("IDAutomationHC39M", 16);
PointF point = new PointF(2f, 2f);
SolidBrush blackBrush = new SolidBrush(Color.Black);
SolidBrush whiteBrush = new SolidBrush(Color.White);
graphics.FillRectangle(whiteBrush, 0, 0, bitMap.Width, bitMap.Height);
graphics.DrawString("*" + barCodeBlack + "*", oFont, blackBrush, point);
}
using (MemoryStream ms = new MemoryStream(100000))
{
bitMap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
byte[] byteImage = ms.ToArray();
Convert.ToBase64String(byteImage);
imgBarCodeBlack.ImageUrl = "data:image/png;base64," + Convert.ToBase64String(byteImage);
}
PlaceHolder1.Controls.Add(imgBarCodeBlack);
}
}
<div class="col-xs-12 col-sm-12 col-lg-12" style="margin-bottom:20px;">
<h3>Digital Black</h3>
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
</div>
UPDATE
Okay I tried searching for other solution, and I found the answer.
I changed this line:
using (Bitmap bitMap = new Bitmap(barCodeBlack.Length * 40, 80))
to this line:
using (Bitmap bitMap = new Bitmap(800, 80))
for some reason the new Bitmap does not accept variable inside the parameter, so I guess I need to hard code my measurement of the barcode.

ASP.NET MVC Error when saving image

I am trying to save an image I've created from Bitmap in a given Path in my project, but I get this error: Additional information: A generic error occurred in GDI+.
This is the code :
public void SaveCaptchaImage(string name)
{
Bitmap image = new Bitmap(128, 64);
string path = "/content/images";
if (System.IO.File.Exists(path + name))
System.IO.File.Delete(path + name);
using (Pen myPen = new Pen(Color.Red, 5))
using (Brush myBrush = new SolidBrush(Color.Silver))
using (Font myFont = new Font("Arial", 16))
using (Graphics graphObject = Graphics.FromImage(image))
{
graphObject.FillRectangle(myBrush, new Rectangle(0, 0, 128, 64));
graphObject.DrawString(GetRandomCaptcha(), myFont, myBrush, new Point(20, 20));
image.Save(path + name + ".png", ImageFormat.Png);
}
image.Dispose();
}
The exception occurs at this line:
image.Save(path + name + ".png", ImageFormat.Png);
What can I do to solve this problem ?
Edit: I don't get why I got downvoted, but ok.
Wrap your path with Server.MapPath like:
image.Save(HttpContext.Current.Server.MapPath(Path.Combine(path, name + ".png")), ImageFormat.Png);
to get absolute path instead of relative.
and use Path.Combine method like #stuartd suggested in comments.

Move dynamically created image to a new page

I can dynamically create a barcode using sample tutorials.
This block of code is in a loop and generates a number of images determined by user input. The image is in a place holder and is displayed on the same webpage.
I want the user to be able to have all the images on a separate page or file for them to print, but I'm not quite sure the best approach to do that. I tried placing it in a session, but I only get 1 image as opposed to the amount the user entered.
System.Web.UI.WebControls.Image imgBarCode = new System.Web.UI.WebControls.Image();
using (Bitmap bitMap = new Bitmap(barCode.Length * 27, 100))
{
using (Graphics graphics = Graphics.FromImage(bitMap))
{
Font oFont = new Font("IDAutomationHC39M", 16);
PointF point = new PointF(2f, .2f);
SolidBrush blackBrush = new SolidBrush(Color.Black);
SolidBrush whiteBrush = new SolidBrush(Color.White);
graphics.FillRectangle(whiteBrush, 0, 0, bitMap.Width, bitMap.Height);
graphics.DrawString("*" + barCode + "*", oFont, blackBrush, point);
}
using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
{
bitMap.Save(ms, ImageFormat.Png);
byte[] byteImage = ms.ToArray();
Convert.ToBase64String(byteImage);
imgBarCode.ImageUrl = "data:image/png;base64," + Convert.ToBase64String(byteImage);
}
plBarCode.Controls.Add(imgBarCode);
}

Barcode in MVC3 with Crystal Reports

Technologies: Visual Studio 2010 and Crystal Reports, MVC3 Web Application, multi tier app.
My web app build one report to label print. The report works fine but not generates the bar code. When I view the report the barcode field is blank. I already installed the IDAutomationHC39M and works in winforms project.
The code that generates the report:
public void Barcode()
{
BarCode report = new BarCode();
Barcodes barcodeDetails = new Barcodes();
DataTable dataTable = barcodeDetails._Barcodes;
for (int i = 0; i < 80; i++)
{
DataRow row = dataTable.NewRow();
string nome = "nome" + i;
decimal preco = i;
string barcode = i + "ADF" + i;
row["nome"] = nome;
row["preco"] = preco;
row["barcode"] = barcode;
dataTable.Rows.Add(row);
}
report.Database.Tables["Barcodes"].SetDataSource((DataTable)dataTable);
report.ExportToHttpResponse(ExportFormatType.PortableDocFormat, System.Web.HttpContext.Current.Response, false, "crReport");
}
Is more easy transform the barcode in a jpeg? If yes, how can i make this in crystal reports?
EDI I: I try change the code for:
for (int i = 0; i < 80; i++)
{
DataRow row = dataTable.NewRow();
string nome = "nome" + i;
decimal preco = i;
string barcode = "*" + i + "ADF" + i + "*";
row["nome"] = nome;
row["preco"] = preco;
System.Web.UI.WebControls.Image imgBarCode = new System.Web.UI.WebControls.Image();
using (Bitmap bitMap = new Bitmap(barcode.Length * 40, 80))
{
using (Graphics graphics = Graphics.FromImage(bitMap))
{
Font oFont = new Font("IDAutomationHC39M", 10);
PointF point = new PointF(2f, 2f);
SolidBrush blackBrush = new SolidBrush(Color.Black);
SolidBrush whiteBrush = new SolidBrush(Color.White);
graphics.FillRectangle(whiteBrush, 0, 0, bitMap.Width, bitMap.Height);
graphics.DrawString("*" + barcode + "*", oFont, blackBrush, point);
}
using (MemoryStream ms = new MemoryStream())
{
bitMap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
byte[] byteImage = ms.ToArray();
Convert.ToBase64String(byteImage);
imgBarCode.ImageUrl = "data:image/png;base64," + Convert.ToBase64String(byteImage);
row["barcode"] = imgBarCode.ImageUrl;
}
}
dataTable.Rows.Add(row);
}
But no effects.
The process to display barcodes in asp.net app (MVC in my case) is really transform the font in an jpeg.
Step 1: get the value for barcode and add "*" in start and end, then creates the Bitmap, Font and Graphics.
DataRow row = dataTable.NewRow();
string barcode = "*" + ID.ToString() + VALOR_VENDA.Value.ToString() + "*";
row["nome"] = NOME_PRODUTO;
row["preco"] = VALOR_VENDA.Value;
int w = barcode.Length * 40;
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(barcode, oFont, oBrushWrite, oPoint);
Next use an MemoryStream to add the bitmap. Make sure that your dataset field is the type Byte[]. With the memorystream add to dataset the value .ToArray();
using (MemoryStream ms = new MemoryStream())
{
oBitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] byteImage = ms.ToArray();
row["barcode"] = byteImage;
}
dataTable.Rows.Add(row);

Categories